Hfzune commited on
Commit
d2e467f
·
verified ·
1 Parent(s): cff6414

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -106
app.py CHANGED
@@ -1,127 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
 
 
 
 
2
  import gradio as gr
 
 
 
3
  from huggingface_hub import HfApi, list_repo_files, hf_hub_download
4
- from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
5
-
6
- # ------------------------------------------------------------------
7
- # 1. Authentication
8
- # ------------------------------------------------------------------
9
- # The token must be added as a "Repository secret" in the Space settings.
10
- # It will be available as the environment variable HF_TOKEN.
11
- HF_TOKEN = os.environ.get("HF_TOKEN")
12
- if not HF_TOKEN:
13
- raise RuntimeError(
14
- "HF_TOKEN secret is missing. "
15
- "Add it in Settings → Repository secrets of your Space."
16
- )
17
 
18
- api = HfApi(token=HF_TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- # ------------------------------------------------------------------
21
- # 2. Core copy function
22
- # ------------------------------------------------------------------
23
- def copy_dataset_files(source_repo_id: str, dest_repo_id: str):
24
- """
25
- Copy every file from `source_repo_id` to `dest_repo_id` one by one,
26
- preserving the original filename and relative path.
27
- """
28
- # -------- 2a. Validate inputs ---------------------------------
29
- if not source_repo_id or not dest_repo_id:
30
- return "❌ Please provide both the source and destination repo IDs."
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  try:
33
- # Ensure the destination repository exists; create it if not.
34
- api.create_repo(
35
- repo_id=dest_repo_id,
36
- repo_type="dataset",
37
- exist_ok=True,
38
- private=False, # change to True if you need a private repo
 
 
 
 
 
 
39
  )
40
- except Exception as e:
41
- return f"❌ Could not create/access destination repo: {e}"
42
 
43
- # -------- 2b. List all files in the source dataset ------------
44
- try:
45
- files = list_repo_files(
46
- repo_id=source_repo_id,
47
- repo_type="dataset",
48
- token=HF_TOKEN,
49
  )
50
- except RepositoryNotFoundError:
51
- return f"❌ Source dataset '{source_repo_id}' not found."
52
- except HfHubHTTPError as e:
53
- return f"❌ Hub error while listing source files: {e}"
54
 
55
- if not files:
56
- return "ℹ️ The source dataset contains no files."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- # -------- 2c. Copy each file sequentially ---------------------
59
- copied = 0
60
- failed = []
61
 
62
- for filename in files:
63
- try:
64
- # Download the file to a temporary local path (streaming).
65
- local_path = hf_hub_download(
66
- repo_id=source_repo_id,
67
- filename=filename,
68
- repo_type="dataset",
69
- token=HF_TOKEN,
70
- )
71
 
72
- # Upload the exact same file to the destination repo.
73
- api.upload_file(
74
- path_or_fileobj=local_path,
75
- path_in_repo=filename, # keep the original name/path
76
- repo_id=dest_repo_id,
77
- repo_type="dataset",
78
- commit_message=f"Copy {filename} from {source_repo_id}",
79
- token=HF_TOKEN,
80
- )
81
- copied += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  except Exception as e:
83
- failed.append(f"{filename}: {e}")
84
-
85
- # -------- 2d. Build result message ----------------------------
86
- msg = f"✅ Copied {copied} file(s) from '{source_repo_id}' to '{dest_repo_id}'."
87
- if failed:
88
- msg += "\n\n⚠️ The following files could not be copied:\n" + "\n".join(failed)
89
- return msg
90
-
91
-
92
- # ------------------------------------------------------------------
93
- # 3. Gradio interface
94
- # ------------------------------------------------------------------
95
- with gr.Blocks(title="Dataset File Copier") as demo:
96
- gr.Markdown(
97
- """
98
- # 📂 Dataset File Copier
99
- Copy **all files** from one Hugging Face dataset repository to another,
100
- preserving the original filename and relative path.
101
- """
 
 
 
 
 
 
 
 
 
 
 
 
102
  )
 
103
 
104
- with gr.Row():
105
- source_box = gr.Textbox(
106
- label="Source dataset repo ID",
107
- placeholder="e.g. username/source-dataset",
108
- )
109
- dest_box = gr.Textbox(
110
- label="Destination dataset repo ID",
111
- placeholder="e.g. username/destination-dataset",
112
- )
113
 
114
- copy_btn = gr.Button("🚀 Copy Files", variant="primary")
115
- output = gr.Textbox(label="Result", lines=8, interactive=False)
116
 
117
- copy_btn.click(
118
- fn=copy_dataset_files,
119
- inputs=[source_box, dest_box],
120
- outputs=output,
 
 
 
 
 
121
  )
122
 
123
- # ------------------------------------------------------------------
124
- # 4. Launch
125
- # ------------------------------------------------------------------
126
- if __name__ == "__main__":
127
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # STEP 0: Monkey-patch HfFolder BEFORE any other import
3
+ # ============================================================
4
+ import huggingface_hub
5
+ if not hasattr(huggingface_hub, "HfFolder"):
6
+ class _HfFolder:
7
+ @staticmethod
8
+ def get_token():
9
+ try:
10
+ return huggingface_hub.get_token()
11
+ except Exception:
12
+ return None
13
+ @staticmethod
14
+ def save_token(token):
15
+ huggingface_hub.login(token)
16
+ @staticmethod
17
+ def delete_token():
18
+ huggingface_hub.logout()
19
+ huggingface_hub.HfFolder = _HfFolder
20
+
21
+ # ============================================================
22
+ # STEP 1: Now safe to import everything else
23
+ # ============================================================
24
  import os
25
+ import time
26
+ import threading
27
+ import traceback
28
+ import urllib.request
29
+
30
+ import spaces
31
  import gradio as gr
32
+ from fastapi import Request
33
+ from fastapi.responses import JSONResponse
34
+ from starlette.routing import Route as StarletteRoute
35
  from huggingface_hub import HfApi, list_repo_files, hf_hub_download
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # ============================================================
38
+ # STEP 2: Config (env vars auto-populated by Space secrets)
39
+ # ============================================================
40
+ HF_TOKEN = os.environ.get("HF_TOKEN")
41
+ SOURCE_REPO = os.environ.get("SOURCE_REPO", "").strip()
42
+ DEST_REPO = os.environ.get("DEST_REPO", "").strip()
43
+ SPACE_HOST = os.environ.get("SPACE_HOST", "").strip() # e.g. "user-space.hf.space"
44
+ SPACE_URL = f"https://{SPACE_HOST}" if SPACE_HOST else ""
45
+
46
+ api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
47
+
48
+ # ============================================================
49
+ # STEP 3: Shared state
50
+ # ============================================================
51
+ STATE = {
52
+ "status": "idle", # idle | running | done | error
53
+ "total": 0,
54
+ "copied": 0,
55
+ "failed": [],
56
+ "current": "",
57
+ "started_at": None,
58
+ "finished_at": None,
59
+ "source": "",
60
+ "dest": "",
61
+ "log": [],
62
+ }
63
+ STATE_LOCK = threading.Lock()
64
+ WORKER_LOCK = threading.Lock()
65
+ WORKER_ALIVE = False
66
 
67
+ def _log(msg: str):
68
+ line = f"[{time.strftime('%H:%M:%S')}] {msg}"
69
+ print(line, flush=True)
70
+ with STATE_LOCK:
71
+ STATE["log"].append(line)
72
+ STATE["log"] = STATE["log"][-300:] # keep last 300 lines
 
 
 
 
 
73
 
74
+ def _with_retry(fn, *args, retries=3, backoff=5, **kwargs):
75
+ """Retry transient HF Hub errors."""
76
+ last = None
77
+ for attempt in range(retries):
78
+ try:
79
+ return fn(*args, **kwargs)
80
+ except Exception as e:
81
+ last = e
82
+ _log(f"retry {attempt + 1}/{retries} for {fn.__name__}: {e}")
83
+ time.sleep(backoff * (attempt + 1))
84
+ raise last
85
+
86
+ # ============================================================
87
+ # STEP 4: Background copy worker (runs one file at a time)
88
+ # ============================================================
89
+ def copy_worker(source_repo: str, dest_repo: str, delete_after: bool = False):
90
+ global WORKER_ALIVE
91
+ with WORKER_LOCK:
92
+ if WORKER_ALIVE:
93
+ return
94
+ WORKER_ALIVE = True
95
  try:
96
+ with STATE_LOCK:
97
+ STATE.update(
98
+ status="running", total=0, copied=0, failed=[], current="",
99
+ started_at=time.time(), finished_at=None,
100
+ source=source_repo, dest=dest_repo, log=[],
101
+ )
102
+ _log(f"START copy: {source_repo} -> {dest_repo}")
103
+
104
+ # 1. Ensure destination dataset exists
105
+ _with_retry(
106
+ api.create_repo,
107
+ repo_id=dest_repo, repo_type="dataset", exist_ok=True,
108
  )
109
+ _log("Destination repo ready")
 
110
 
111
+ # 2. List every file in the source
112
+ files = _with_retry(
113
+ list_repo_files,
114
+ repo_id=source_repo, repo_type="dataset", token=HF_TOKEN,
 
 
115
  )
116
+ with STATE_LOCK:
117
+ STATE["total"] = len(files)
118
+ _log(f"Found {len(files)} files in source")
 
119
 
120
+ # 3. Copy one by one — preserving filenames exactly
121
+ for i, filename in enumerate(files, 1):
122
+ with STATE_LOCK:
123
+ STATE["current"] = filename
124
+ try:
125
+ local_path = _with_retry(
126
+ hf_hub_download,
127
+ repo_id=source_repo, filename=filename,
128
+ repo_type="dataset", token=HF_TOKEN,
129
+ )
130
+ _with_retry(
131
+ api.upload_file,
132
+ path_or_fileobj=local_path,
133
+ path_in_repo=filename, # ← same name, same path
134
+ repo_id=dest_repo, repo_type="dataset",
135
+ commit_message=f"Copy {filename}",
136
+ token=HF_TOKEN,
137
+ )
138
+ with STATE_LOCK:
139
+ STATE["copied"] += 1
140
+ _log(f"[{i}/{len(files)}] OK {filename}")
141
+ if delete_after:
142
+ try:
143
+ os.remove(local_path)
144
+ except Exception:
145
+ pass
146
+ except Exception as e:
147
+ with STATE_LOCK:
148
+ STATE["failed"].append(f"{filename}: {e}")
149
+ _log(f"[{i}/{len(files)}] FAIL {filename}: {e}")
150
 
151
+ with STATE_LOCK:
152
+ STATE.update(status="done", finished_at=time.time())
153
+ _log("✅ COPY COMPLETE")
154
 
155
+ except Exception as e:
156
+ with STATE_LOCK:
157
+ STATE.update(status="error", finished_at=time.time())
158
+ _log(f"❌ FATAL: {e}\n{traceback.format_exc()}")
159
+ finally:
160
+ with WORKER_LOCK:
161
+ WORKER_ALIVE = False
 
 
162
 
163
+
164
+ def start_worker(source_repo: str, dest_repo: str, delete_after: bool = False):
165
+ if not source_repo or not dest_repo:
166
+ return "❌ Provide both source and destination repo IDs."
167
+ if not api:
168
+ return "❌ HF_TOKEN not set."
169
+ threading.Thread(
170
+ target=copy_worker,
171
+ args=(source_repo, dest_repo, delete_after),
172
+ daemon=True,
173
+ ).start()
174
+ return "🚀 Worker started"
175
+
176
+ # ============================================================
177
+ # STEP 5: Self-ping keep-alive (fires every 4 min)
178
+ # ============================================================
179
+ def _self_ping_loop():
180
+ if not SPACE_URL:
181
+ _log("⚠️ SPACE_HOST not set — self-ping disabled")
182
+ return
183
+ url = f"{SPACE_URL}/health"
184
+ _log(f"Self-ping loop → {url}")
185
+ while True:
186
+ try:
187
+ with urllib.request.urlopen(url, timeout=20) as r:
188
+ _log(f"self-ping {url} → {r.status}")
189
  except Exception as e:
190
+ _log(f"self-ping failed: {e}")
191
+ time.sleep(240) # 4 min < 5-min idle threshold
192
+
193
+ threading.Thread(target=_self_ping_loop, daemon=True).start()
194
+
195
+ # ============================================================
196
+ # STEP 6: ZeroGPU registration — REQUIRED for ZeroGPU Spaces
197
+ # ============================================================
198
+ @spaces.GPU(duration=10)
199
+ def _zerogpu_noop():
200
+ """Kept tiny; only exists so the ZeroGPU scanner finds a GPU fn."""
201
+ return "ok"
202
+
203
+ # ============================================================
204
+ # STEP 7: Gradio UI
205
+ # ============================================================
206
+ def _snapshot():
207
+ with STATE_LOCK:
208
+ return dict(STATE)
209
+
210
+
211
+ def _status_render():
212
+ s = _snapshot()
213
+ pct = f"{(s['copied'] / s['total'] * 100):.1f}%" if s["total"] else "—"
214
+ md = (
215
+ f"### Status: `{s['status']}`\n"
216
+ f"- **Source:** `{s['source'] or '—'}`\n"
217
+ f"- **Dest:** `{s['dest'] or '—'}`\n"
218
+ f"- **Progress:** {s['copied']} / {s['total']} ({pct})\n"
219
+ f"- **Failed:** {len(s['failed'])}\n"
220
+ f"- **Current:** `{s['current']}`"
221
  )
222
+ return md, "\n".join(s["log"])
223
 
 
 
 
 
 
 
 
 
 
224
 
225
+ with gr.Blocks(title="Dataset Copier — Infinite Worker") as demo:
226
+ gr.Markdown("# 📂 Dataset File Copier (ZeroGPU infinite worker)")
227
 
228
+ with gr.Row():
229
+ src = gr.Textbox(label="Source dataset repo", value=SOURCE_REPO,
230
+ placeholder="user/source-dataset")
231
+ dst = gr.Textbox(label="Destination dataset repo", value=DEST_REPO,
232
+ placeholder="user/dest-dataset")
233
+
234
+ delete_after = gr.Checkbox(
235
+ label="Delete local temp file after successful upload (recommended for large datasets)",
236
+ value=True,
237
  )
238
 
239
+ with gr.Row():
240
+ start_btn = gr.Button("🚀 Start Copy", variant="primary")
241
+ refresh_btn = gr.Button("🔄 Refresh Now")
242
+
243
+ status_md = gr.Markdown("Status: **idle**")
244
+ log_box = gr.Textbox(label="Log", lines=22, interactive=False)
245
+
246
+ # ---- ZeroGPU hidden button — must be WIRED to .click() ----
247
+ _gpu_btn = gr.Button("init-gpu", visible=False)
248
+ _gpu_btn.click(fn=_zerogpu_noop, inputs=None, outputs=None)
249
+
250
+ start_btn.click(start_worker, [src, dst, delete_after], log_box)
251
+ refresh_btn.click(_status_render, None, [status_md, log_box])
252
+
253
+ # Live refresh
254
+ gr.Timer(3).tick(_status_render, None, [status_md, log_box])
255
+ demo.load(_status_render, None, [status_md, log_box])
256
+
257
+ # ============================================================
258
+ # STEP 8: Launch — critical flags from your notes
259
+ # ============================================================
260
+ demo.launch(
261
+ server_name="0.0.0.0",
262
+ server_port=7860,
263
+ share=False,
264
+ ssr_mode=False, # disable Node proxy so our routes are reachable
265
+ prevent_thread_lock=True, # returns immediately → we inject routes below
266
+ )
267
+
268
+ # ============================================================
269
+ # STEP 9: Inject /health and /status at index 0
270
+ # ============================================================
271
+ async def _health(request: Request):
272
+ s = _snapshot()
273
+ return JSONResponse({
274
+ "status": s["status"],
275
+ "copied": s["copied"],
276
+ "total": s["total"],
277
+ "failed": len(s["failed"]),
278
+ "current": s["current"],
279
+ "alive": WORKER_ALIVE,
280
+ })
281
+
282
+ async def _status(request: Request):
283
+ return JSONResponse(_snapshot())
284
+
285
+ live_app = demo.app
286
+ live_app.router.routes.insert(0, StarletteRoute("/health", _health, methods=["GET"]))
287
+ live_app.router.routes.insert(0, StarletteRoute("/status", _status, methods=["GET"]))
288
+ live_app.build_middleware_stack()
289
+
290
+ # ============================================================
291
+ # STEP 10: Auto-start if env vars are provided
292
+ # ============================================================
293
+ if SOURCE_REPO and DEST_REPO and api:
294
+ _log("Env vars detected — auto-starting copy worker")
295
+ start_worker(SOURCE_REPO, DEST_REPO, delete_after=True)
296
+
297
+ # ============================================================
298
+ # STEP 11: Block main thread FOREVER — this is what keeps the
299
+ # Python process alive instead of exiting after launch()
300
+ # ============================================================
301
+ _log("Main thread blocking forever. Space stays up.")
302
+ while True:
303
+ time.sleep(60)