-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrocli
More file actions
executable file
·292 lines (229 loc) · 11.5 KB
/
Copy pathrocli
File metadata and controls
executable file
·292 lines (229 loc) · 11.5 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env python3
"""RedOcean CLI - Compact GCS utility"""
from google.cloud import storage
from pathlib import Path
import sys, os, json, base64, zlib, tempfile, time
class ProgressBar:
def __init__(self, total_bytes, desc="Processing", width=30):
self.total_bytes = total_bytes
self.current_bytes = 0
self.desc = desc
self.width = width
self.start_time = time.time()
self.last_update_time = 0
def update_to(self, current):
self.current_bytes = current
now = time.time()
# Update at most every 0.1s to avoid flicker, or if complete
if now - self.last_update_time > 0.1 or self.current_bytes >= self.total_bytes:
self._draw()
self.last_update_time = now
def _draw(self):
percent = min(1.0, self.current_bytes / self.total_bytes) if self.total_bytes > 0 else 1.0
filled = int(self.width * percent)
bar = "█" * filled + "░" * (self.width - filled)
elapsed = time.time() - self.start_time
speed = self.current_bytes / elapsed if elapsed > 0 else 0
speed_str = self._format_size(speed) + "/s"
sys.stdout.write(f"\r{self.desc} |{bar}| {int(percent*100)}% ({speed_str}) ")
sys.stdout.flush()
def close(self):
sys.stdout.write("\n")
sys.stdout.flush()
@staticmethod
def _format_size(size):
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024.0:
return f"{size:.1f}{unit}"
size /= 1024.0
return f"{size:.1f}TB"
# Helper for google-cloud-storage callbacks, only works with upload_from_file/filename if supported
# But GCS python client doesn't support callback on upload_from_filename directly easily without wrapping file object.
# We will wrap file object for uploads.
class FileWithProgress:
def __init__(self, path, pbar):
self._f = open(path, 'rb')
self._pbar = pbar
def read(self, size=-1):
chunk = self._f.read(size)
if self._pbar:
self._pbar.update_to(self._f.tell())
return chunk
def tell(self):
return self._f.tell()
def seek(self, offset, whence=0):
return self._f.seek(offset, whence)
def seekable(self):
return self._f.seekable()
def close(self):
self._f.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# Obfuscated credentials (base64 + zlib compressed)
_CREDS = b'eJyVVsmuo0oS/ZVSSb1yvwIz81bNaDBgjDGTZemKIZnnGZ7639u+ddWqLvWiOxe5yDznRGSEQif/+j5uLfj+57fvA+jnLAQffhg2Uz1+//u3723f5CAcP7LoDaibPptB//Mim/0RfBRg+7qkgU+FCB7iJOUfaTIgQx+NAREfSZoANBYdYQxGQkD9xn5T/3gvVjjJl2/Xm2wzd+GbInifp89ak2VhTmSW4ZkLmxRdWmQneoFZxhBEhjE5VkmWJDELJhEYpnnhDL6YjEdpMmfxyI3ks/YYv1FwldI6uGVXnUfWEQ1OHuV1Bh1vpJxcH4udI7vb2xeYa5EjaCE1jgZJxpE+mMpn3e5eepNgDkrsyPbyFDXP0YMvsi6m7e1hUdpV95DhDp0sZltbaMgujGJeQ9P3NnxdkOGlQBh61wIlqE0gSruM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MXEekj1826lDYcNbsYDG4iys9Kv14RcnqAF8UBspZqD4vxfOPlJJ8VP3TyAjMcdMlOgOlXjASZnuKmIRcKA3m8K04KhPWvycruWGGQUCFfgamGw2lyJ+wWkXaxXYuxmDiXhzpq8w4KTrhXq0/C4NLq7LnKqJuaofJrutGIoC6BRmRZGkUCepCPnBeJQV0LUGocEF55ZBNm6x77zlo0uQtceBDMXHBRMaHuWrwUxDVVvNMQ2zVu7Q6/kCHX4A/ijsJSCeWsJUY8pzqWNvFQRhfccqNpY3FIousPQ+z1zxrD43louQMlxdyZ4Zy8Y/PINjO2NKU8IW6Ks0bC+ehel32tkRuHEX5flHyS3Q6pG2XCs46sM58fcknZC8y7RkwgiFjoFtyz/rQk4cL/F5t621pYZqAeP0DlZ+Xb13oQNSHw6z+Gsen9BPzjy0B/ZH71I/my2y+3/RE21S8aPz315ZkkAmM0ReMoCb8WitPoG+VPY/ox9dkblI5jO/wJQV9Cw4+kaZISvAWhBmreUAR672/i2BSg/p35E/PF89ts+OR+Qv8d7PUTmLMI9B8rDtMfIejHl0r5q8qyLL9LfAWfj9CbMPzyvv9HpW+CZnyLVGD0I3/0oTcb+r26f8Pg/6G+U/1GDOAjal5tqt+h/zPc93/+Cwr+CN0='
BUCKET = "redocean-ai-models"
def get_client():
"""Create GCS client with embedded credentials"""
creds_json = zlib.decompress(base64.b64decode(_CREDS))
creds_dict = json.loads(creds_json)
# Write to temp file for google-cloud-storage
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump(creds_dict, f)
tmp_path = f.name
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = tmp_path
client = storage.Client()
# Cleanup temp file
try:
os.unlink(tmp_path)
except:
pass
return client
def upload(local_path: str, remote_folder: str = ""):
"""Upload local folder to GCS bucket root or specific folder"""
client = get_client()
bucket = client.bucket(BUCKET)
# Resolve path to handle relative paths like ../Folder
local = Path(local_path).expanduser().resolve()
if not local.exists():
print(f"❌ Path not found: {local_path}")
return 1
files = [local] if local.is_file() else list(local.rglob("*"))
files = [f for f in files if f.is_file()]
target_msg = f" to {remote_folder}" if remote_folder else " to root"
print(f"📤 Uploading {len(files)} files from {local_path}{target_msg}...")
# Check if we should upload contents (current dir) or the folder itself
is_current_dir = os.path.normpath(local_path) == "."
for f in files:
if local.is_dir():
# Get path relative to the directory root
rel = f.relative_to(local)
# If not uploading current dir (.) AND no remote folder specified, include the folder name
if not is_current_dir and not remote_folder:
rel = Path(local.name) / rel
else:
rel = f.name
# Prepend remote folder if specified
blob_path = str(rel)
if remote_folder:
blob_path = f"{remote_folder.rstrip('/')}/{blob_path}"
blob = bucket.blob(blob_path)
file_size = os.path.getsize(f)
pbar = ProgressBar(file_size, desc=f" ✓ {blob_path[:30]:<30}", width=20)
try:
with FileWithProgress(f, pbar) as file_obj:
blob.upload_from_file(file_obj, size=file_size)
finally:
pbar.close()
target_display = f"gs://{BUCKET}/{remote_folder}" if remote_folder else f"gs://{BUCKET}/"
print(f"✅ Upload complete: {target_display}")
return 0
def download(gcs_folder: str, target: str):
"""Download GCS folder to local target"""
client = get_client()
bucket = client.bucket(BUCKET)
target_path = Path(target).expanduser()
# List all blobs with prefix
prefix = gcs_folder.rstrip("/") + "/" if gcs_folder else ""
blobs = list(bucket.list_blobs(prefix=prefix))
if not blobs:
print(f"❌ No files found at gs://{BUCKET}/{gcs_folder}")
return 1
print(f"📥 Downloading {len(blobs)} files to {target}...")
for blob in blobs:
# Remove prefix to get relative path
rel = blob.name[len(prefix):] if prefix else blob.name
dest = target_path / rel
dest.parent.mkdir(parents=True, exist_ok=True)
blob.reload() # Ensure we have size
pbar = ProgressBar(blob.size, desc=f" ✓ {rel[:30]:<30}", width=20)
try:
bytes_downloaded = 0
with blob.open("rb") as reader:
with open(dest, 'wb') as f:
while True:
chunk = reader.read(1024 * 1024) # 1MB chunks
if not chunk:
break
f.write(chunk)
bytes_downloaded += len(chunk)
pbar.update_to(bytes_downloaded)
except Exception as e:
print(f"\n❌ Error downloading {rel}: {e}")
finally:
pbar.close()
print(f"✅ Download complete: {target}")
return 0
def list_files(prefix: str = ""):
"""List direct objects under folder (non-recursive)"""
client = get_client()
bucket = client.bucket(BUCKET)
prefix = prefix.rstrip("/") + "/" if prefix else ""
blobs = bucket.list_blobs(prefix=prefix, delimiter="/")
files = list(blobs)
folders = list(blobs.prefixes) if hasattr(blobs, 'prefixes') else []
if not files and not folders:
print(f"📂 gs://{BUCKET}/{prefix} (empty)")
return 0
print(f"📂 gs://{BUCKET}/{prefix}")
for folder in folders:
print(f" 📁 {folder}")
for blob in files:
size = f"{blob.size / 1024 / 1024:.2f}MB" if blob.size > 1024*1024 else f"{blob.size / 1024:.1f}KB"
rel = blob.name[len(prefix):] if blob.name.startswith(prefix) else blob.name
print(f" 📄 {rel} ({size})")
return 0
def delete(gcs_folder: str):
"""Delete GCS folder and all contents"""
client = get_client()
bucket = client.bucket(BUCKET)
prefix = gcs_folder.rstrip("/") + "/" if gcs_folder else ""
blobs = list(bucket.list_blobs(prefix=prefix))
# Also check for folder marker itself
folder_marker = bucket.blob(gcs_folder.rstrip("/") + "/")
if folder_marker.exists():
blobs.append(folder_marker)
if not blobs:
print(f"❌ No files found at gs://{BUCKET}/{gcs_folder}")
return 1
print(f"🗑️ Deleting {len(blobs)} items from gs://{BUCKET}/{gcs_folder}...")
for blob in blobs:
blob.delete()
print(f" ✗ {blob.name}")
print(f"✅ Deleted {len(blobs)} items")
return 0
def main():
if len(sys.argv) < 2:
print("Usage:")
print(" rocli upload LOCAL_FOLDER [REMOTE_FOLDER]")
print(" rocli download GCS_FOLDER TARGET_FOLDER")
print(" rocli list [GCS_FOLDER]")
print(" rocli delete GCS_FOLDER")
return 1
cmd = sys.argv[1]
match cmd:
case "upload":
if len(sys.argv) < 3:
print("❌ upload requires: LOCAL_FOLDER [REMOTE_FOLDER]")
return 1
remote = sys.argv[3] if len(sys.argv) > 3 else ""
return upload(sys.argv[2], remote)
case "download":
if len(sys.argv) < 4:
print("❌ download requires: GCS_FOLDER TARGET_FOLDER")
return 1
return download(sys.argv[2], sys.argv[3])
case "list":
prefix = sys.argv[2] if len(sys.argv) > 2 else ""
return list_files(prefix)
case "delete":
if len(sys.argv) < 3:
print("❌ delete requires: GCS_FOLDER")
return 1
return delete(sys.argv[2])
case _:
print(f"❌ Unknown command: {cmd}")
return 1
if __name__ == "__main__":
sys.exit(main())