Cistern commited on
Commit
6ae3e2b
·
verified ·
1 Parent(s): ee13896

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +342 -261
app.py CHANGED
@@ -4,31 +4,45 @@ import time
4
  import json
5
  import subprocess
6
  import threading
7
- import importlib
 
8
  from pathlib import Path
9
  from urllib.parse import urlparse, urljoin, unquote
10
  from concurrent.futures import ThreadPoolExecutor
11
 
12
  # ----------------------------------------------------------------------
13
- # 1. ZEROGPU AND FASTAPI SETUP (MUST BE FAST & AT THE TOP)
14
  # ----------------------------------------------------------------------
15
- # These are pre-installed in standard Hugging Face Spaces
16
- import fastapi
17
- from fastapi import FastAPI
18
- from fastapi.responses import HTMLResponse, JSONResponse
19
- import uvicorn
20
  import spaces
21
 
22
- # The orchestrator will now detect this instantly
23
  @spaces.GPU(duration=10)
24
  def dummy_gpu():
25
  """Dummy function to keep the ZeroGPU orchestrator happy"""
26
  pass
27
 
28
- app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  # ----------------------------------------------------------------------
31
- # 2. CONFIGURATION & LOGGING
32
  # ----------------------------------------------------------------------
33
  ONION_URL = os.environ.get("ONION_URL", "")
34
  HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
@@ -47,14 +61,18 @@ with open(LOG_FILE, "w") as f:
47
  f.write("System initialized. Starting background mirror...\n")
48
 
49
  def log(msg, to_web=True):
50
- """Write logs to console (unmasked) and persistent file (masked)"""
 
51
  print(msg, flush=True)
 
 
52
  if to_web:
53
  safe_msg = msg
54
  if ONION_URL:
55
  domain = urlparse(ONION_URL).netloc
56
  if domain:
57
  safe_msg = safe_msg.replace(domain, "[HIDDEN.onion]")
 
58
  with open(LOG_FILE, "a") as f:
59
  f.write(safe_msg + "\n")
60
 
@@ -62,7 +80,267 @@ if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
62
  log("⚠️ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
63
 
64
  # ----------------------------------------------------------------------
65
- # 3. WEB SERVER ROUTES
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  # ----------------------------------------------------------------------
67
  HTML_PAGE = """<!DOCTYPE html>
68
  <html lang="en">
@@ -96,16 +374,17 @@ HTML_PAGE = """<!DOCTYPE html>
96
  </div>
97
  </div>
98
  <script>
99
- // Ping the GPU API once to register activity with the ZeroGPU Orchestrator
100
- fetch('/api/gpu').catch(err => console.error(err));
101
-
102
  async function fetchLogs() {
103
  try {
104
  const response = await fetch('/api/logs');
105
  const data = await response.json();
106
  const logBox = document.getElementById('log-box');
 
 
107
  const isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 50;
 
108
  logBox.textContent = data.logs;
 
109
  if (isScrolledToBottom) {
110
  logBox.scrollTop = logBox.scrollHeight;
111
  }
@@ -113,264 +392,66 @@ HTML_PAGE = """<!DOCTYPE html>
113
  console.error("Error fetching logs", err);
114
  }
115
  }
 
 
116
  setInterval(fetchLogs, 2000);
117
  fetchLogs();
118
  </script>
119
  </body>
120
  </html>"""
121
 
122
- @app.get("/")
123
- def read_root():
124
- return HTMLResponse(content=HTML_PAGE)
125
-
126
- @app.get("/api/logs")
127
- def read_logs():
128
- try:
129
- with open(LOG_FILE, "r") as f:
130
- lines = f.readlines()[-200:]
131
- logs_str = "".join(lines)
132
- except Exception:
133
- logs_str = "Loading logs..."
134
- return JSONResponse(content={"logs": logs_str})
135
-
136
- @app.get("/api/gpu")
137
- def trigger_gpu():
138
- try:
139
- dummy_gpu()
140
- return {"status": "GPU Acquired and ZeroGPU Orchestrator satisfied!"}
141
- except Exception as e:
142
- return {"status": f"Error: {e}"}
143
-
144
- # ----------------------------------------------------------------------
145
- # 4. BACKGROUND SETUP & MIRROR LOGIC
146
- # ----------------------------------------------------------------------
147
- commit_times = []
148
-
149
- def install_system_dependencies():
150
- """Run apt-get and pip install in the background without blocking startup"""
151
- log("🔧 [Setup] Disabling service auto-start...")
152
- subprocess.run("echo 'exit 101' > /usr/sbin/policy-rc.d && chmod +x /usr/sbin/policy-rc.d", shell=True)
153
-
154
- log("🔧 [Setup] Installing Tor and aria2...")
155
- subprocess.run("apt-get update -qq && apt-get install -y tor aria2 -qq", shell=True)
156
-
157
- log("🔧 [Setup] Installing Python packages...")
158
- subprocess.run([sys.executable, "-m", "pip", "install", "-q", "requests[socks]", "huggingface_hub", "beautifulsoup4"], check=False)
159
-
160
- subprocess.run(["pkill", "tor"], capture_output=True)
161
- time.sleep(1)
162
-
163
- # Force Python to recognize newly installed packages
164
- importlib.invalidate_caches()
165
-
166
- def start_tor():
167
- tor_dir = Path("/tmp/tor-data")
168
- tor_dir.mkdir(exist_ok=True)
169
- torrc = tor_dir / "torrc"
170
-
171
- torrc.write_text(f"""SocksPort {TOR_SOCKS_PORT}
172
- DataDirectory {tor_dir}
173
- Log notice file {tor_dir}/tor.log
174
- RunAsDaemon 1
175
- """)
176
-
177
- log("Starting Tor proxy in the background...")
178
- subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
179
-
180
- import socket
181
- for _ in range(30):
182
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
183
- sock.settimeout(1)
184
- result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
185
- sock.close()
186
- if result == 0:
187
- log("✅ Tor SOCKS proxy is ready.")
188
- return
189
- time.sleep(1)
190
-
191
- raise RuntimeError("❌ Tor failed to start.")
192
-
193
- def background_worker():
194
- """This function is executed in a daemon thread so Uvicorn can start instantly"""
195
- try:
196
- # 1. Install dependencies
197
- install_system_dependencies()
198
- start_tor()
199
-
200
- # 2. Safely import modules now that they are installed
201
- import requests
202
- from requests.adapters import HTTPAdapter
203
- from urllib3.util.retry import Retry
204
- from huggingface_hub import HfApi, login, CommitOperationAdd
205
- from bs4 import BeautifulSoup
206
-
207
- # 3. Setup Session
208
- session = requests.Session()
209
- session.proxies = {
210
- 'http': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}',
211
- 'https': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}'
212
- }
213
- retries = Retry(total=10, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
214
- session.mount("http://", HTTPAdapter(max_retries=retries))
215
- session.mount("https://", HTTPAdapter(max_retries=retries))
216
 
217
- # 4. Helper Functions mapped to the local imports
218
- def verify_tor():
219
- log("Testing Tor proxy connection...")
220
- try:
221
- res = session.get("http://httpbin.org/ip", timeout=10)
222
- res.raise_for_status()
223
- log(f"Tor Active! Routed IP: {res.json()['origin']}")
224
- except Exception as e:
225
- log(f"⚠️ Tor proxy test failed: {e}")
226
-
227
- def get_remote_files(api):
228
- log("Fetching list of already uploaded files from Hugging Face...")
229
- try:
230
- files = api.list_repo_files(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE)
231
- remote_set = set(files)
232
- log(f"Found {len(remote_set)} files already in repo.")
233
- return remote_set
234
- except Exception as e:
235
- log(f"Warning: Could not fetch remote file list ({e}). Treating as empty.")
236
- return set()
237
-
238
- def crawl_onion_directory(url, rel_path=""):
239
- log(f"📂 Scanning directory index: /{rel_path}")
240
- try:
241
- r = session.get(url, timeout=90)
242
- r.raise_for_status()
243
- except Exception as e:
244
- log(f"Failed to access {url}: {e}")
245
- return
246
-
247
- soup = BeautifulSoup(r.text, 'html.parser')
248
- for link in soup.find_all('a'):
249
- href = link.get('href')
250
- if not href or href.startswith('?') or href == '../' or href.startswith('/'):
251
- continue
252
-
253
- clean_name = unquote(href)
254
- full_url = urljoin(url, href)
255
- new_rel_path = f"{rel_path}/{clean_name}".strip("/")
256
-
257
- if href.endswith('/'):
258
- yield from crawl_onion_directory(full_url, new_rel_path)
259
- else:
260
- yield (full_url, new_rel_path)
261
-
262
- def download_with_aria2(url, dest_path):
263
- dest_path = Path(dest_path)
264
- dest_path.parent.mkdir(parents=True, exist_ok=True)
265
- cmd = [
266
- "aria2c", f"--all-proxy=socks5h://127.0.0.1:{TOR_SOCKS_PORT}",
267
- "--max-connection-per-server=16", "--split=16", "--min-split-size=1M",
268
- "--continue=true", "--auto-file-renaming=false", "--allow-overwrite=true",
269
- f"--dir={dest_path.parent}", f"--out={dest_path.name}", url
270
- ]
271
  try:
272
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
273
- return result.returncode == 0
 
274
  except Exception:
275
- return False
276
-
277
- def check_rate_limit():
278
- global commit_times
279
- now = time.time()
280
- commit_times = [t for t in commit_times if now - t < 3600]
281
- if len(commit_times) >= MAX_COMMITS_PER_HOUR:
282
- oldest = commit_times[0]
283
- sleep_time = 3600 - (now - oldest) + 15
284
- if sleep_time > 0:
285
- log(f"[Rate Limit] Sleeping {sleep_time/60:.2f} min to respect Hugging Face limits...")
286
- time.sleep(sleep_time)
287
- commit_times = [t for t in commit_times if time.time() - t < 3600]
288
-
289
- def upload_batch(api, batch_files):
290
- if not batch_files: return
291
- check_rate_limit()
292
- log(f"Committing {len(batch_files)} files to Hugging Face...")
293
- operations = [CommitOperationAdd(path_in_repo=rel, path_or_fileobj=str(loc)) for rel, loc in batch_files]
294
- try:
295
- api.create_commit(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, operations=operations, commit_message=f"Sync: {len(batch_files)} files")
296
- commit_times.append(time.time())
297
- for _, local_path in batch_files:
298
- if local_path.exists(): local_path.unlink()
299
- log("✅ Batch upload successful!")
300
- except Exception as e:
301
- log(f"❌ Upload failed: {e}")
302
-
303
- # 5. Core Execution Engine
304
- if not HF_TOKEN:
305
- return
306
-
307
- login(token=HF_TOKEN)
308
- api = HfApi()
309
- log("✅ Hugging Face authentication successful.")
310
- verify_tor()
311
-
312
- LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
313
- completed_files = get_remote_files(api)
314
-
315
- log(f"Resuming: {len(completed_files)} files already present.")
316
- log(f"Starting crawler at: {ONION_URL}")
317
-
318
- batch_files = []
319
- batch_size = 0
320
- target_bytes = BATCH_SIZE_MB * 1024 * 1024
321
- skipped_count = 0
322
-
323
- executor = ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS)
324
- pending_futures = []
325
-
326
- for file_url, rel_path in crawl_onion_directory(ONION_URL):
327
- if rel_path in completed_files:
328
- skipped_count += 1
329
- if skipped_count % 100 == 0:
330
- log(f"⏩ Fast-forwarding: Skipped {skipped_count} files already on HF...")
331
- continue
332
-
333
- local_path = LOCAL_TEMP_DIR / rel_path
334
- future = executor.submit(download_with_aria2, file_url, local_path)
335
- pending_futures.append((future, rel_path, local_path))
336
-
337
- if len(pending_futures) >= DOWNLOAD_WORKERS * 2:
338
- for fut, rel, lpath in pending_futures:
339
- success = fut.result()
340
- if success and lpath.exists():
341
- batch_size += lpath.stat().st_size
342
- batch_files.append((rel, lpath))
343
- log(f"Downloaded: {rel} | Batch: {batch_size/(1024*1024):.1f} MB")
344
- else:
345
- log(f"Failed: {rel}")
346
- pending_futures.clear()
347
 
348
- if batch_size >= target_bytes:
349
- upload_batch(api, batch_files)
350
- batch_files = []
351
- batch_size = 0
352
-
353
- for fut, rel, lpath in pending_futures:
354
- success = fut.result()
355
- if success and lpath.exists():
356
- batch_size += lpath.stat().st_size
357
- batch_files.append((rel, lpath))
358
-
359
- if batch_files:
360
- upload_batch(api, batch_files)
361
 
362
- executor.shutdown(wait=True)
363
- log("✅ MIRRORING COMPLETED SUCCESSFULLY!")
364
-
365
- except Exception as e:
366
- log(f"❌ Background Mirror Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
367
 
368
- # ----------------------------------------------------------------------
369
- # 5. EXECUTION ENTRY POINT
370
- # ----------------------------------------------------------------------
371
  if __name__ == "__main__":
 
 
 
372
  # 1. Start the mirroring process in a background daemon thread
373
- threading.Thread(target=background_worker, daemon=True).start()
374
 
375
- # 2. Start the FastAPI server to keep the port alive
376
- uvicorn.run(app, host="0.0.0.0", port=7860, log_level="error")
 
 
4
  import json
5
  import subprocess
6
  import threading
7
+ import http.server
8
+ import socketserver
9
  from pathlib import Path
10
  from urllib.parse import urlparse, urljoin, unquote
11
  from concurrent.futures import ThreadPoolExecutor
12
 
13
  # ----------------------------------------------------------------------
14
+ # 1. ZEROGPU REQUIREMENT (MUST BE AT THE TOP)
15
  # ----------------------------------------------------------------------
16
+ # ZeroGPU's AST scanner requires this to be declared early in the file
 
 
 
 
17
  import spaces
18
 
 
19
  @spaces.GPU(duration=10)
20
  def dummy_gpu():
21
  """Dummy function to keep the ZeroGPU orchestrator happy"""
22
  pass
23
 
24
+ # ----------------------------------------------------------------------
25
+ # 2. SYSTEM SETUP
26
+ # ----------------------------------------------------------------------
27
+ def run_cmd(cmd, desc=""):
28
+ print(f"\n[Setup] {desc}", flush=True)
29
+ result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
30
+ if result.returncode != 0:
31
+ print(f"Warning: {result.stderr}", flush=True)
32
+ return result
33
+
34
+ run_cmd("echo 'exit 101' > /usr/sbin/policy-rc.d && chmod +x /usr/sbin/policy-rc.d", "Disabling service auto-start")
35
+ run_cmd("apt-get update -qq", "Updating package lists")
36
+ run_cmd("apt-get install -y tor aria2 -qq", "Installing Tor and aria2")
37
+
38
+ # Install missing Python packages
39
+ run_cmd("pip install -q requests[socks] huggingface_hub beautifulsoup4 tqdm", "Installing Python packages")
40
+
41
+ subprocess.run(["pkill", "tor"], capture_output=True, text=True)
42
+ time.sleep(1)
43
 
44
  # ----------------------------------------------------------------------
45
+ # 3. CONFIGURATION & LOGGING
46
  # ----------------------------------------------------------------------
47
  ONION_URL = os.environ.get("ONION_URL", "")
48
  HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
 
61
  f.write("System initialized. Starting background mirror...\n")
62
 
63
  def log(msg, to_web=True):
64
+ """Write logs to console (unmasked) and persistent file (masked) so they survive page reloads"""
65
+ # 1. Print real, unmasked message to the terminal console
66
  print(msg, flush=True)
67
+
68
+ # 2. Mask the Onion address before saving to the Web UI log file
69
  if to_web:
70
  safe_msg = msg
71
  if ONION_URL:
72
  domain = urlparse(ONION_URL).netloc
73
  if domain:
74
  safe_msg = safe_msg.replace(domain, "[HIDDEN.onion]")
75
+
76
  with open(LOG_FILE, "a") as f:
77
  f.write(safe_msg + "\n")
78
 
 
80
  log("⚠️ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
81
 
82
  # ----------------------------------------------------------------------
83
+ # 4. START TOR MANUALLY
84
+ # ----------------------------------------------------------------------
85
+ def start_tor():
86
+ tor_dir = Path("/tmp/tor-data")
87
+ tor_dir.mkdir(exist_ok=True)
88
+ torrc = tor_dir / "torrc"
89
+
90
+ torrc.write_text(f"""SocksPort {TOR_SOCKS_PORT}
91
+ DataDirectory {tor_dir}
92
+ Log notice file {tor_dir}/tor.log
93
+ RunAsDaemon 1
94
+ """)
95
+
96
+ log("Starting Tor proxy in the background...")
97
+ subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
98
+
99
+ import socket
100
+ for _ in range(30):
101
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
102
+ sock.settimeout(1)
103
+ result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
104
+ sock.close()
105
+ if result == 0:
106
+ log("✅ Tor SOCKS proxy is ready.")
107
+ return
108
+ time.sleep(1)
109
+
110
+ raise RuntimeError("❌ Tor failed to start.")
111
+
112
+ # ----------------------------------------------------------------------
113
+ # 5. IMPORTS & TOR SESSION SETUP
114
+ # ----------------------------------------------------------------------
115
+ from bs4 import BeautifulSoup
116
+ import requests
117
+ from requests.adapters import HTTPAdapter
118
+ from urllib3.util.retry import Retry
119
+ from huggingface_hub import HfApi, login, CommitOperationAdd
120
+
121
+ session = requests.Session()
122
+ session.proxies = {
123
+ 'http': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}',
124
+ 'https': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}'
125
+ }
126
+
127
+ retries = Retry(total=10, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
128
+ session.mount("http://", HTTPAdapter(max_retries=retries))
129
+ session.mount("https://", HTTPAdapter(max_retries=retries))
130
+
131
+ def verify_tor():
132
+ log("Testing Tor proxy connection...")
133
+ try:
134
+ res = session.get("http://httpbin.org/ip", timeout=10)
135
+ res.raise_for_status()
136
+ log(f"Tor Active! Routed IP: {res.json()['origin']}")
137
+ return True
138
+ except Exception as e:
139
+ log(f"⚠️ Tor proxy test failed: {e}")
140
+ return False
141
+
142
+ # ----------------------------------------------------------------------
143
+ # 6. HUGGING FACE AUTH & API
144
+ # ----------------------------------------------------------------------
145
+ api = None
146
+
147
+ def authenticate_hf():
148
+ global api
149
+ if not HF_TOKEN:
150
+ raise ValueError("HF_TOKEN is missing.")
151
+ login(token=HF_TOKEN)
152
+ api = HfApi()
153
+
154
+ def get_remote_files():
155
+ if api is None:
156
+ raise RuntimeError("Hugging Face API not authenticated.")
157
+ log("Fetching list of already uploaded files from Hugging Face...")
158
+ try:
159
+ files = api.list_repo_files(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE)
160
+ remote_set = set(files)
161
+ log(f"Found {len(remote_set)} files already in repo.")
162
+ return remote_set
163
+ except Exception as e:
164
+ log(f"Warning: Could not fetch remote file list ({e}). Treating as empty.")
165
+ return set()
166
+
167
+ # ----------------------------------------------------------------------
168
+ # 7. CORE LOGIC (RATE LIMIT, BATCH UPLOAD, ARIA2, CRAWLER)
169
+ # ----------------------------------------------------------------------
170
+ commit_times = []
171
+
172
+ def check_rate_limit():
173
+ global commit_times
174
+ now = time.time()
175
+ commit_times = [t for t in commit_times if now - t < 3600]
176
+ if len(commit_times) >= MAX_COMMITS_PER_HOUR:
177
+ oldest = commit_times[0]
178
+ sleep_time = 3600 - (now - oldest) + 15
179
+ if sleep_time > 0:
180
+ log(f"[Rate Limit] Sleeping {sleep_time/60:.2f} min to respect Hugging Face limits...")
181
+ time.sleep(sleep_time)
182
+ now = time.time()
183
+ commit_times = [t for t in commit_times if now - t < 3600]
184
+
185
+ def upload_batch(batch_files):
186
+ if not batch_files:
187
+ return
188
+ check_rate_limit()
189
+ log(f"Committing {len(batch_files)} files to Hugging Face...")
190
+
191
+ operations = []
192
+ for rel_path, local_path in batch_files:
193
+ operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
194
+
195
+ try:
196
+ api.create_commit(
197
+ repo_id=HF_REPO_ID,
198
+ repo_type=HF_REPO_TYPE,
199
+ operations=operations,
200
+ commit_message=f"Sync: {len(batch_files)} files (Batch Upload)"
201
+ )
202
+ commit_times.append(time.time())
203
+ for _, local_path in batch_files:
204
+ if local_path.exists():
205
+ local_path.unlink()
206
+ log("✅ Batch upload successful!")
207
+ except Exception as e:
208
+ log(f"❌ Upload failed: {e}")
209
+
210
+ def download_with_aria2(url, dest_path):
211
+ dest_path = Path(dest_path)
212
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
213
+
214
+ cmd = [
215
+ "aria2c",
216
+ f"--all-proxy=socks5h://127.0.0.1:{TOR_SOCKS_PORT}",
217
+ "--max-connection-per-server=16",
218
+ "--split=16",
219
+ "--min-split-size=1M",
220
+ "--continue=true",
221
+ "--auto-file-renaming=false",
222
+ "--allow-overwrite=true",
223
+ f"--dir={dest_path.parent}",
224
+ f"--out={dest_path.name}",
225
+ url
226
+ ]
227
+
228
+ try:
229
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
230
+ if result.returncode == 0:
231
+ return True
232
+ else:
233
+ log(f"aria2 error for {url}: {result.stderr[:100]}...")
234
+ return False
235
+ except subprocess.TimeoutExpired:
236
+ log(f"aria2 timeout for {url}")
237
+ return False
238
+ except Exception as e:
239
+ log(f"aria2 exception: {e}")
240
+ return False
241
+
242
+ def crawl_onion_directory(url, rel_path=""):
243
+ # Give the user feedback so it doesn't look like it's stuck during deep crawls
244
+ log(f"📂 Scanning directory index: /{rel_path}")
245
+
246
+ try:
247
+ r = session.get(url, timeout=90)
248
+ r.raise_for_status()
249
+ except Exception as e:
250
+ log(f"Failed to access {url}: {e}")
251
+ return
252
+
253
+ soup = BeautifulSoup(r.text, 'html.parser')
254
+ for link in soup.find_all('a'):
255
+ href = link.get('href')
256
+
257
+ if not href or href.startswith('?') or href == '../' or href.startswith('/'):
258
+ continue
259
+
260
+ clean_name = unquote(href)
261
+ full_url = urljoin(url, href)
262
+
263
+ # Ensure we always use forward slash paths for Hugging Face
264
+ new_rel_path = f"{rel_path}/{clean_name}".strip("/")
265
+
266
+ if href.endswith('/'):
267
+ yield from crawl_onion_directory(full_url, new_rel_path)
268
+ else:
269
+ yield (full_url, new_rel_path)
270
+
271
+ # ----------------------------------------------------------------------
272
+ # 8. MAIN MIRROR THREAD
273
+ # ----------------------------------------------------------------------
274
+ def run_mirror():
275
+ try:
276
+ dummy_gpu() # Execute once just in case the interceptor requires usage
277
+ start_tor()
278
+ authenticate_hf()
279
+ log("✅ Hugging Face authentication successful.")
280
+ except Exception as e:
281
+ log(f"❌ Initialization failed: {e}")
282
+ return
283
+
284
+ verify_tor()
285
+ LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
286
+
287
+ completed_files = get_remote_files()
288
+ log(f"Resuming: {len(completed_files)} files already present.")
289
+ log(f"Starting crawler at: {ONION_URL}")
290
+
291
+ batch_files = []
292
+ batch_size = 0
293
+ target_bytes = BATCH_SIZE_MB * 1024 * 1024
294
+ skipped_count = 0
295
+
296
+ executor = ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS)
297
+ pending_futures = []
298
+
299
+ for file_url, rel_path in crawl_onion_directory(ONION_URL):
300
+ if rel_path in completed_files:
301
+ skipped_count += 1
302
+ # Periodically log skipping so the user knows it's actively working
303
+ if skipped_count % 100 == 0:
304
+ log(f"⏩ Fast-forwarding: Skipped {skipped_count} files already on HF...")
305
+ continue
306
+
307
+ local_path = LOCAL_TEMP_DIR / rel_path
308
+ future = executor.submit(download_with_aria2, file_url, local_path)
309
+ pending_futures.append((future, rel_path, local_path))
310
+
311
+ if len(pending_futures) >= DOWNLOAD_WORKERS * 2:
312
+ for fut, rel, lpath in pending_futures:
313
+ success = fut.result()
314
+ if success and lpath.exists():
315
+ file_size = lpath.stat().st_size
316
+ batch_size += file_size
317
+ batch_files.append((rel, lpath))
318
+ log(f"Downloaded: {rel} | Batch: {batch_size/(1024*1024):.1f} MB")
319
+ else:
320
+ log(f"Failed: {rel}")
321
+ pending_futures.clear()
322
+
323
+ if batch_size >= target_bytes:
324
+ upload_batch(batch_files)
325
+ batch_files = []
326
+ batch_size = 0
327
+
328
+ # Process remaining futures
329
+ for fut, rel, lpath in pending_futures:
330
+ success = fut.result()
331
+ if success and lpath.exists():
332
+ file_size = lpath.stat().st_size
333
+ batch_size += file_size
334
+ batch_files.append((rel, lpath))
335
+
336
+ if batch_files:
337
+ upload_batch(batch_files)
338
+
339
+ executor.shutdown(wait=True)
340
+ log("✅ MIRRORING COMPLETED SUCCESSFULLY!")
341
+
342
+ # ----------------------------------------------------------------------
343
+ # 9. PURE HTML/CSS WEB SERVER
344
  # ----------------------------------------------------------------------
345
  HTML_PAGE = """<!DOCTYPE html>
346
  <html lang="en">
 
374
  </div>
375
  </div>
376
  <script>
 
 
 
377
  async function fetchLogs() {
378
  try {
379
  const response = await fetch('/api/logs');
380
  const data = await response.json();
381
  const logBox = document.getElementById('log-box');
382
+
383
+ // Only autoscroll if user is near the bottom
384
  const isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 50;
385
+
386
  logBox.textContent = data.logs;
387
+
388
  if (isScrolledToBottom) {
389
  logBox.scrollTop = logBox.scrollHeight;
390
  }
 
392
  console.error("Error fetching logs", err);
393
  }
394
  }
395
+
396
+ // Fetch logs every 2 seconds
397
  setInterval(fetchLogs, 2000);
398
  fetchLogs();
399
  </script>
400
  </body>
401
  </html>"""
402
 
403
+ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
404
+ def do_GET(self):
405
+ # Ignore query parameters like ?__theme=dark
406
+ parsed_path = urlparse(self.path).path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
+ if parsed_path == "/" or parsed_path == "/index.html":
409
+ html = HTML_PAGE.encode("utf-8")
410
+ self.send_response(200)
411
+ self.send_header("Content-type", "text/html; charset=utf-8")
412
+ self.send_header("Content-Length", str(len(html)))
413
+ self.end_headers()
414
+ self.wfile.write(html)
415
+
416
+ elif parsed_path == "/api/logs":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  try:
418
+ with open(LOG_FILE, "r") as f:
419
+ lines = f.readlines()[-200:]
420
+ logs_str = "".join(lines)
421
  except Exception:
422
+ logs_str = "Loading logs..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
+ body = json.dumps({"logs": logs_str}).encode("utf-8")
425
+ self.send_response(200)
426
+ self.send_header("Content-type", "application/json")
427
+ self.send_header("Content-Length", str(len(body)))
428
+ self.end_headers()
429
+ self.wfile.write(body)
 
 
 
 
 
 
 
430
 
431
+ else:
432
+ self.send_response(404)
433
+ self.end_headers()
434
+
435
+ # Disable default HTTP logging so console stays clean
436
+ def log_message(self, format, *args):
437
+ pass
438
+
439
+ def start_web_server():
440
+ port = 7860
441
+ handler = CustomHTTPRequestHandler
442
+ # Use ThreadingHTTPServer from http.server (not socketserver)
443
+ httpd = http.server.ThreadingHTTPServer(("0.0.0.0", port), handler)
444
+ httpd.allow_reuse_address = True
445
+ log(f"Web interface running on port {port}...")
446
+ httpd.serve_forever()
447
 
 
 
 
448
  if __name__ == "__main__":
449
+ # 🚀 FIX: Call the dummy GPU function immediately to satisfy ZeroGPU's startup scanner
450
+ dummy_gpu()
451
+
452
  # 1. Start the mirroring process in a background daemon thread
453
+ threading.Thread(target=run_mirror, daemon=True).start()
454
 
455
+ # 2. Start the HTTP server to serve the HTML/CSS UI
456
+ # This blocks the main thread, keeping the Hugging Face Space alive
457
+ start_web_server()