Quantumbraid commited on
Commit
61d2843
Β·
verified Β·
1 Parent(s): 80a764a

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +13 -4
  2. __pycache__/app.cpython-311.pyc +0 -0
  3. app.py +446 -0
README.md CHANGED
@@ -1,13 +1,22 @@
1
  ---
2
  title: HF2HF
3
- emoji: πŸ¦€
4
  colorFrom: blue
5
- colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.13'
9
  app_file: app.py
 
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: HF2HF
3
+ emoji: πŸ”€
4
  colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.31.0
 
8
  app_file: app.py
9
+ short_description: Transfer files between HF Buckets, Datasets & Models
10
  pinned: false
11
  ---
12
 
13
+ # HF2HF: Hugging Face Bucket & Repo Transfer
14
+
15
+ A utility to transfer files directly between **Hugging Face Buckets**, **Datasets**, and **Models** in the cloud without downloading anything locally.
16
+
17
+ ### Key Capabilities
18
+ - ⚑ **Direct Cloud-to-Cloud**: Runs entirely inside Hugging Face infrastructure. Your local internet bandwidth and disk space are untouched.
19
+ - πŸ“¦ **Bucket ↔ Bucket Instant Copy**: Leverages Hugging Face XET hashes for server-side file copying.
20
+ - πŸ—ƒοΈ **Bucket βž” Dataset & Model**: Effortlessly move files from S3-compatible HF Buckets into git-versioned Dataset or Model repositories.
21
+ - πŸ“ **Selective Transfer**: Filter files by prefix, inspect sizes, and checkmark exactly what you need.
22
+ - πŸ›‘οΈ **Zero Disk Residue**: Buffer files are safely cleaned up after each file commit.
__pycache__/app.cpython-311.pyc ADDED
Binary file (24.1 kB). View file
 
app.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ import shutil
5
+ import tempfile
6
+ import traceback
7
+ from pathlib import Path
8
+ from typing import Generator, List, Tuple, Dict, Any
9
+
10
+ import gradio as gr
11
+ from huggingface_hub import HfApi, create_repo, create_bucket
12
+ from huggingface_hub.utils import HfHubHTTPError, RepositoryNotFoundError, EntryNotFoundError
13
+
14
+
15
+ def get_token(custom_token: str | None = None) -> str | None:
16
+ """Return explicit custom token if provided, else fall back to HF_TOKEN env var."""
17
+ if custom_token and custom_token.strip():
18
+ return custom_token.strip()
19
+ return os.environ.get("HF_TOKEN") or None
20
+
21
+
22
+ def format_size(size_bytes: int | float | None) -> str:
23
+ """Format byte count into human-readable string."""
24
+ if size_bytes is None:
25
+ return "Unknown size"
26
+ try:
27
+ size = float(size_bytes)
28
+ except (ValueError, TypeError):
29
+ return "Unknown size"
30
+ if size < 1024:
31
+ return f"{int(size)} B"
32
+ elif size < 1024 * 1024:
33
+ return f"{size / 1024:.1f} KB"
34
+ elif size < 1024 * 1024 * 1024:
35
+ return f"{size / (1024 * 1024):.1f} MB"
36
+ else:
37
+ return f"{size / (1024 * 1024 * 1024):.2f} GB"
38
+
39
+
40
+ def clean_identifier(uri_or_id: str, kind: str = "bucket") -> str:
41
+ """Normalize user input by stripping hf:// URIs and prefixes."""
42
+ val = (uri_or_id or "").strip()
43
+ if not val:
44
+ return ""
45
+ # Strip hf:// URI prefixes if user copied full URI
46
+ if val.startswith("hf://"):
47
+ val = val[len("hf://"):]
48
+ if val.startswith("buckets/"):
49
+ val = val[len("buckets/"):]
50
+ elif val.startswith("datasets/"):
51
+ val = val[len("datasets/"):]
52
+ elif val.startswith("models/"):
53
+ val = val[len("models/"):]
54
+ return val.strip("/")
55
+
56
+
57
+ def get_user_buckets(custom_token: str | None = None) -> List[str]:
58
+ """Fetch existing buckets for the logged-in user or orgs."""
59
+ token = get_token(custom_token)
60
+ api = HfApi(token=token)
61
+ buckets = []
62
+ try:
63
+ user_info = api.whoami()
64
+ username = user_info.get("name")
65
+ orgs = [org["name"] for org in user_info.get("orgs", []) if "name" in org]
66
+ namespaces = [username] + orgs if username else []
67
+
68
+ for ns in namespaces:
69
+ try:
70
+ for b in api.list_buckets(namespace=ns):
71
+ buckets.append(b.id)
72
+ except Exception:
73
+ pass
74
+ except Exception:
75
+ # Fallback to general list if whoami fails
76
+ try:
77
+ for b in api.list_buckets():
78
+ buckets.append(b.id)
79
+ except Exception:
80
+ pass
81
+ return sorted(list(set(buckets)))
82
+
83
+
84
+ def list_files_in_bucket(
85
+ bucket_input: str,
86
+ prefix_filter: str,
87
+ custom_token: str | None = None
88
+ ) -> Tuple[Any, str, Dict[str, Any]]:
89
+ """List files in the selected source bucket and prepare CheckboxGroup choices."""
90
+ bucket_id = clean_identifier(bucket_input, kind="bucket")
91
+ if not bucket_id:
92
+ return gr.update(choices=[], value=[]), "⚠️ Please enter or select a source bucket name.", {}
93
+
94
+ token = get_token(custom_token)
95
+ api = HfApi(token=token)
96
+ prefix = prefix_filter.strip() if prefix_filter else None
97
+
98
+ try:
99
+ tree = list(api.list_bucket_tree(bucket_id, prefix=prefix, recursive=True))
100
+ except Exception as e:
101
+ return gr.update(choices=[], value=[]), f"❌ Error accessing bucket '{bucket_id}': {str(e)}", {}
102
+
103
+ # Filter only file items
104
+ files_map = {}
105
+ choices = []
106
+ total_size = 0
107
+
108
+ for item in tree:
109
+ # Item has attribute 'type', 'path', 'size', 'xet_hash'
110
+ item_type = getattr(item, "type", "file")
111
+ if item_type != "file":
112
+ continue
113
+ path = getattr(item, "path", None) or str(item)
114
+ size = getattr(item, "size", 0)
115
+ xet_hash = getattr(item, "xet_hash", None)
116
+
117
+ total_size += (size or 0)
118
+ display_label = f"{path} ({format_size(size)})"
119
+ choices.append((display_label, path))
120
+ files_map[path] = {
121
+ "path": path,
122
+ "size": size,
123
+ "xet_hash": xet_hash,
124
+ "display": display_label,
125
+ }
126
+
127
+ count = len(choices)
128
+ if count == 0:
129
+ msg = f"ℹ️ Bucket '{bucket_id}' contains no files" + (f" matching prefix '{prefix}'." if prefix else ".")
130
+ else:
131
+ msg = f"βœ… Found {count} file{'s' if count != 1 else ''} ({format_size(total_size)}) in bucket `{bucket_id}`."
132
+
133
+ return gr.update(choices=choices, value=[]), msg, files_map
134
+
135
+
136
+ def select_all_files(files_map: Dict[str, Any]) -> List[str]:
137
+ """Select all available files."""
138
+ return list(files_map.keys())
139
+
140
+
141
+ def deselect_all_files() -> List[str]:
142
+ """Deselect all files."""
143
+ return []
144
+
145
+
146
+ def transfer_files(
147
+ src_bucket_input: str,
148
+ selected_files: List[str],
149
+ files_metadata: Dict[str, Any],
150
+ dest_type: str,
151
+ dest_id_input: str,
152
+ dest_subfolder: str,
153
+ preserve_structure: bool,
154
+ create_dest_if_missing: bool,
155
+ is_private_dest: bool,
156
+ custom_token: str | None = None
157
+ ) -> Generator[str, None, None]:
158
+ """Execute transfer of files from source bucket to target bucket, dataset, or model."""
159
+ src_bucket = clean_identifier(src_bucket_input, kind="bucket")
160
+ dest_id = clean_identifier(dest_id_input, kind=dest_type.lower())
161
+
162
+ if not src_bucket:
163
+ yield "❌ Error: Source bucket is not specified."
164
+ return
165
+
166
+ if not selected_files:
167
+ yield "⚠️ No files selected. Please check at least one file to transfer."
168
+ return
169
+
170
+ if not dest_id:
171
+ yield f"❌ Error: Destination {dest_type} identifier is required."
172
+ return
173
+
174
+ token = get_token(custom_token)
175
+ if not token:
176
+ yield "⚠️ Warning: No Hugging Face token detected. Operations on private buckets/repos or write actions may fail. Configure HF_TOKEN secret or input your token."
177
+
178
+ api = HfApi(token=token)
179
+ dest_kind = dest_type.lower() # 'bucket', 'dataset', or 'model'
180
+ subfolder = (dest_subfolder or "").strip().strip("/")
181
+
182
+ logs = []
183
+ def log(msg: str):
184
+ logs.append(f"[{time.strftime('%H:%M:%S')}] {msg}")
185
+ return "\n".join(logs)
186
+
187
+ yield log(f"πŸš€ Initializing transfer of {len(selected_files)} file(s) from bucket `{src_bucket}` to {dest_type} `{dest_id}`...")
188
+
189
+ # Step 1: Ensure destination exists or create it
190
+ if create_dest_if_missing:
191
+ try:
192
+ if dest_kind == "bucket":
193
+ yield log(f"Checking/Creating destination bucket `{dest_id}`...")
194
+ api.create_bucket(dest_id, private=is_private_dest, exist_ok=True)
195
+ elif dest_kind in ["dataset", "model"]:
196
+ yield log(f"Checking/Creating destination {dest_kind} `{dest_id}`...")
197
+ api.create_repo(dest_id, repo_type=dest_kind, private=is_private_dest, exist_ok=True)
198
+ yield log(f" Destination `{dest_id}` is ready.")
199
+ except Exception as e:
200
+ yield log(f"⚠️ Destination verification warning: {e}. Attempting transfer regardless...")
201
+
202
+ # Step 2: Temporary staging directory in the Space container
203
+ temp_dir = tempfile.mkdtemp(prefix="hf2hf_transfer_")
204
+
205
+ total_files = len(selected_files)
206
+ success_count = 0
207
+ fail_count = 0
208
+ start_time = time.time()
209
+
210
+ try:
211
+ for idx, file_rel_path in enumerate(selected_files, start=1):
212
+ file_meta = files_metadata.get(file_rel_path, {})
213
+ xet_hash = file_meta.get("xet_hash")
214
+ file_size = file_meta.get("size")
215
+ file_size_str = format_size(file_size)
216
+
217
+ # Determine destination path in repo/bucket
218
+ if preserve_structure:
219
+ target_rel_path = f"{subfolder}/{file_rel_path}" if subfolder else file_rel_path
220
+ else:
221
+ filename = Path(file_rel_path).name
222
+ target_rel_path = f"{subfolder}/{filename}" if subfolder else filename
223
+ target_rel_path = target_rel_path.lstrip("/")
224
+
225
+ yield log(f"\n({idx}/{total_files}) Transferring `{file_rel_path}` ({file_size_str}) -> `{target_rel_path}`...")
226
+
227
+ # Scenario A: Destination is another Bucket
228
+ if dest_kind == "bucket":
229
+ server_side_done = False
230
+ # Try server-side copy if xet_hash exists
231
+ if xet_hash:
232
+ try:
233
+ yield log(f" Attempting instant server-side copy via xet hash `{xet_hash[:12]}...`")
234
+ api.batch_bucket_files(
235
+ bucket_id=dest_id,
236
+ copy=[("bucket", src_bucket, xet_hash, target_rel_path)]
237
+ )
238
+ server_side_done = True
239
+ yield log(f" ⚑ Instant server-side copy succeeded!")
240
+ except Exception as err:
241
+ yield log(f" ⚠️ Server-side copy skipped ({err}). Falling back to cloud-buffered transfer...")
242
+
243
+ if not server_side_done:
244
+ # Download to Space container temporary disk and upload to target bucket
245
+ local_dest = Path(temp_dir) / Path(file_rel_path).name
246
+ try:
247
+ yield log(f" Downloading from `{src_bucket}` to Space buffer...")
248
+ api.download_bucket_files(src_bucket, [(file_rel_path, str(local_dest))])
249
+
250
+ yield log(f" Uploading from Space buffer to bucket `{dest_id}`...")
251
+ api.batch_bucket_files(dest_id, add=[(str(local_dest), target_rel_path)])
252
+ yield log(f" Transferred to bucket successfully!")
253
+ except Exception as err:
254
+ fail_count += 1
255
+ yield log(f" ❌ Transfer failed: {err}")
256
+ continue
257
+ finally:
258
+ if local_dest.exists():
259
+ try:
260
+ local_dest.unlink()
261
+ except Exception:
262
+ pass
263
+
264
+ success_count += 1
265
+
266
+ # Scenario B: Destination is Dataset or Model repo
267
+ else:
268
+ local_dest = Path(temp_dir) / Path(file_rel_path).name
269
+ try:
270
+ yield log(f" Downloading `{file_rel_path}` from bucket to Space buffer...")
271
+ api.download_bucket_files(src_bucket, [(file_rel_path, str(local_dest))])
272
+
273
+ yield log(f" Uploading to {dest_kind} `{dest_id}` at `{target_rel_path}`...")
274
+ api.upload_file(
275
+ path_or_fileobj=str(local_dest),
276
+ path_in_repo=target_rel_path,
277
+ repo_id=dest_id,
278
+ repo_type=dest_kind,
279
+ commit_message=f"HF2HF: Transfer {target_rel_path} from bucket {src_bucket}"
280
+ )
281
+ success_count += 1
282
+ yield log(f" Committed and uploaded to {dest_kind} `{dest_id}`!")
283
+ except Exception as err:
284
+ fail_count += 1
285
+ yield log(f" ❌ Transfer failed: {err}")
286
+ finally:
287
+ # Always clean up local buffer immediately
288
+ if local_dest.exists():
289
+ try:
290
+ local_dest.unlink()
291
+ except Exception:
292
+ pass
293
+
294
+ finally:
295
+ # Clean up staging directory
296
+ shutil.rmtree(temp_dir, ignore_errors=True)
297
+
298
+ elapsed = time.time() - start_time
299
+ yield log("\n" + "=" * 50)
300
+ yield log(f"πŸŽ‰ Transfer Completed in {elapsed:.1f}s!")
301
+ yield log(f" Successfully transferred: {success_count}/{total_files} file(s)")
302
+ if fail_count > 0:
303
+ yield log(f"⚠️ Failed: {fail_count} file(s)")
304
+
305
+ dest_url = f"https://huggingface.co/{'buckets/' if dest_kind == 'bucket' else ('datasets/' if dest_kind == 'dataset' else '')}{dest_id}"
306
+ yield log(f"πŸ”— View destination: {dest_url}")
307
+
308
+
309
+ # Build Gradio UI
310
+ with gr.Blocks(title="HF2HF - Hugging Face Bucket & Repo Transfer") as demo:
311
+ files_state = gr.State({})
312
+
313
+ gr.Markdown(
314
+ """
315
+ # πŸ”€ HF2HF: Direct Cloud-to-Cloud Storage Transfer
316
+ Transfer files directly between **Hugging Face Buckets**, **Datasets**, and **Models** inside Hugging Face's cloud infrastructure β€” **no local downloading or intermediary bandwidth needed!**
317
+ """
318
+ )
319
+
320
+ with gr.Row():
321
+ with gr.Column(scale=1):
322
+ gr.Markdown("### 1️⃣ Source Bucket")
323
+ with gr.Row():
324
+ src_bucket = gr.Dropdown(
325
+ label="Source Bucket",
326
+ choices=get_user_buckets(),
327
+ allow_custom_value=True,
328
+ info="Select your bucket or type custom bucket ID (e.g. username/my-bucket)",
329
+ scale=4,
330
+ )
331
+ refresh_buckets_btn = gr.Button("πŸ”„", scale=1, min_width=50)
332
+
333
+ prefix_input = gr.Textbox(
334
+ label="Prefix / Subfolder Filter (Optional)",
335
+ placeholder="e.g. checkpoints/ or data/ (leave empty for entire bucket)",
336
+ )
337
+ list_btn = gr.Button("πŸ” List Files in Bucket", variant="secondary")
338
+
339
+ source_status = gr.Markdown("Select or enter a source bucket and click **List Files**.")
340
+
341
+ with gr.Column(scale=1):
342
+ gr.Markdown("### 2️⃣ Destination Target")
343
+ dest_type = gr.Radio(
344
+ label="Destination Type",
345
+ choices=["Bucket", "Dataset", "Model"],
346
+ value="Bucket",
347
+ )
348
+ dest_id = gr.Textbox(
349
+ label="Destination Identifier",
350
+ placeholder="e.g. username/target-bucket or username/my-dataset",
351
+ )
352
+ dest_subfolder = gr.Textbox(
353
+ label="Destination Subfolder / Path (Optional)",
354
+ placeholder="e.g. exports/ or leave blank to keep original path",
355
+ )
356
+ with gr.Row():
357
+ preserve_structure = gr.Checkbox(
358
+ label="Preserve source directory structure",
359
+ value=True,
360
+ )
361
+ create_missing = gr.Checkbox(
362
+ label="Create destination if missing",
363
+ value=True,
364
+ )
365
+ is_private = gr.Checkbox(
366
+ label="Make new destination private",
367
+ value=True,
368
+ )
369
+
370
+ gr.Markdown("### 3️⃣ File Selection")
371
+ with gr.Row():
372
+ select_all_btn = gr.Button("βœ… Select All", size="sm")
373
+ deselect_all_btn = gr.Button("❌ Deselect All", size="sm")
374
+
375
+ file_checkboxes = gr.CheckboxGroup(
376
+ label="Files to Transfer",
377
+ choices=[],
378
+ value=[],
379
+ )
380
+
381
+ with gr.Row():
382
+ transfer_btn = gr.Button("πŸš€ Start Cloud Transfer", variant="primary", size="lg")
383
+
384
+ with gr.Accordion("βš™οΈ Advanced Settings / HF Token Override", open=False):
385
+ token_input = gr.Textbox(
386
+ label="Custom Hugging Face Access Token (Optional)",
387
+ type="password",
388
+ placeholder="Leave empty to use Space's default HF_TOKEN secret",
389
+ )
390
+
391
+ gr.Markdown("### 4️⃣ Live Transfer Log")
392
+ log_output = gr.Code(
393
+ label="Progress and Logs",
394
+ value="Awaiting transfer initiation...",
395
+ lines=15,
396
+ interactive=False,
397
+ )
398
+
399
+ # Event handlers
400
+ def on_refresh_buckets(tok: str):
401
+ b = get_user_buckets(tok)
402
+ return gr.update(choices=b)
403
+
404
+ refresh_buckets_btn.click(
405
+ fn=on_refresh_buckets,
406
+ inputs=[token_input],
407
+ outputs=[src_bucket],
408
+ )
409
+
410
+ list_btn.click(
411
+ fn=list_files_in_bucket,
412
+ inputs=[src_bucket, prefix_input, token_input],
413
+ outputs=[file_checkboxes, source_status, files_state],
414
+ )
415
+
416
+ select_all_btn.click(
417
+ fn=select_all_files,
418
+ inputs=[files_state],
419
+ outputs=[file_checkboxes],
420
+ )
421
+
422
+ deselect_all_btn.click(
423
+ fn=deselect_all_files,
424
+ inputs=[],
425
+ outputs=[file_checkboxes],
426
+ )
427
+
428
+ transfer_btn.click(
429
+ fn=transfer_files,
430
+ inputs=[
431
+ src_bucket,
432
+ file_checkboxes,
433
+ files_state,
434
+ dest_type,
435
+ dest_id,
436
+ dest_subfolder,
437
+ preserve_structure,
438
+ create_missing,
439
+ is_private,
440
+ token_input,
441
+ ],
442
+ outputs=[log_output],
443
+ )
444
+
445
+ if __name__ == "__main__":
446
+ demo.launch(theme="soft", mcp_server=True)