forked from feast-dev/feast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgs_utils.py
More file actions
86 lines (68 loc) · 2.25 KB
/
Copy pathgs_utils.py
File metadata and controls
86 lines (68 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Copyright 2018 The Feast Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import os
import re
import tempfile
import time
import pandas as pd
import requests
from google.cloud import storage
_GCS_PATH_REGEX = r"^gs:\/\/[a-z0-9\.\-_\/]*$"
def gcs_to_df(path):
"""Reads a file from gs to pandas
Args:
path (str): full gcs path to the file
Returns:
pandas.DataFrame: dataframe
"""
bucket_name, blob_name = split_gs_path(path)
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
temp_file_path = "temp{}.csv".format(int(round(time.time() * 1000)))
with open(temp_file_path, "wb") as temp_file:
blob.download_to_file(temp_file)
df = pd.read_csv(temp_file_path)
os.remove(temp_file_path)
return df
def df_to_gcs(df, path):
"""Writes the given df to the path specified. Will fail if the bucket does
not exist.
Args:
df (pandas.DataFrame): dataframe
path (str): path in gcs to write to
"""
bucket_name, blob_name = split_gs_path(path)
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
s = io.StringIO()
df.to_csv(s, index=False)
blob.upload_from_string(s.getvalue())
def df_to_gcs_signed_url(df, signed_url):
f = tempfile.NamedTemporaryFile()
df.to_csv(f)
requests.put(signed_url, data=f)
def split_gs_path(path):
path = path.replace("gs://", "", 1)
return path.split("/", 1)
def is_gs_path(path):
"""Check if path is a gcs path
Args:
path (str): path to file
Returns:
bool: is a valid gcs path
"""
return re.match(_GCS_PATH_REGEX, path) != None