Cistern commited on
Commit
f6bc1fa
Β·
verified Β·
1 Parent(s): 5c46f02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -96
app.py CHANGED
@@ -49,38 +49,37 @@ HF_REPO_ID = os.environ.get("HF_REPO_ID", "").strip()
49
  HF_REPO_TYPE = "dataset"
50
 
51
  LOCAL_TEMP_DIR = Path("./hf_mirror_temp")
52
- LOG_FILE = "mirror_activity.log" # system logs (not shown in UI)
53
- UI_LOG_FILE = "mirror_ui.log" # mirror progress logs (shown in UI)
54
- PROGRESS_FILE = "mirror_progress.json" # file stored in the dataset
55
 
56
  BATCH_SIZE_MB = 100
57
  MAX_COMMITS_PER_HOUR = 124
58
  DOWNLOAD_WORKERS = 4
59
  TOR_SOCKS_PORT = 9050
 
 
60
 
61
- # Reset system log
62
  with open(LOG_FILE, "w") as f:
63
  f.write("System logs (not shown in UI)\n")
64
 
65
- # Initialize UI log with a startup message
66
  with open(UI_LOG_FILE, "w") as f:
67
  f.write("Mirror initializing...\n")
68
 
69
  def log_system(msg):
70
- """Write to console and system log only."""
71
  print(msg, flush=True)
72
  with open(LOG_FILE, "a") as f:
73
  f.write(msg + "\n")
74
 
75
  def log_mirror(msg):
76
- """Write to console and UI log (visible in web interface)."""
77
  print(msg, flush=True)
78
  with open(UI_LOG_FILE, "a") as f:
79
  f.write(msg + "\n")
80
 
81
  if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
82
- log_system("⚠️ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
83
- log_mirror("❌ Missing secrets! Please check Space Secrets.")
 
84
 
85
  # ----------------------------------------------------------------------
86
  # 4. START TOR MANUALLY
@@ -93,10 +92,8 @@ def start_tor():
93
  DataDirectory {tor_dir}
94
  Log notice file {tor_dir}/tor.log
95
  RunAsDaemon 1""")
96
-
97
- log_system("Starting Tor proxy in the background...")
98
  subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
99
-
100
  import socket
101
  for _ in range(30):
102
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -104,14 +101,14 @@ RunAsDaemon 1""")
104
  result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
105
  sock.close()
106
  if result == 0:
107
- log_system("βœ… Tor SOCKS proxy is ready.")
108
  log_mirror("βœ… Tor proxy ready.")
109
  return
110
  time.sleep(1)
111
- raise RuntimeError("❌ Tor failed to start.")
112
 
113
  # ----------------------------------------------------------------------
114
- # 5. IMPORTS & TOR SESSION SETUP
115
  # ----------------------------------------------------------------------
116
  from bs4 import BeautifulSoup
117
  import requests
@@ -121,43 +118,43 @@ from huggingface_hub import HfApi, login, CommitOperationAdd
121
 
122
  session = requests.Session()
123
  session.proxies = {
124
- 'http': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}',
125
  'https': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}'
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_system("Testing Tor proxy connection...")
133
  try:
134
  res = session.get("http://httpbin.org/ip", timeout=10)
135
  res.raise_for_status()
136
- log_system(f"Tor Active! Routed IP: {res.json()['origin']}")
137
- log_mirror("βœ… Tor proxy active.")
 
138
  return True
139
  except Exception as e:
140
- log_system(f"⚠️ Tor proxy test failed: {e}")
141
  log_mirror(f"⚠️ Tor proxy test failed: {e}")
142
  return False
143
 
144
  # ----------------------------------------------------------------------
145
- # 6. HUGGING FACE AUTH & API
146
  # ----------------------------------------------------------------------
147
  api = None
148
 
149
  def authenticate_hf():
150
  global api
151
  if not HF_TOKEN:
152
- raise ValueError("HF_TOKEN is missing.")
153
  login(token=HF_TOKEN)
154
  api = HfApi()
155
 
156
  # ----------------------------------------------------------------------
157
- # 7. PROGRESS FILE HANDLING
158
  # ----------------------------------------------------------------------
159
  def download_progress_from_hf():
160
- """Try to download the progress file from the dataset. Returns set of completed rel paths."""
161
  log_mirror("Checking previous progress...")
162
  try:
163
  url = f"https://huggingface.co/datasets/{HF_REPO_ID}/resolve/main/{PROGRESS_FILE}"
@@ -176,7 +173,6 @@ def download_progress_from_hf():
176
  return set()
177
 
178
  def save_progress_local(completed_set):
179
- """Save the current set of completed relative paths to a local JSON file."""
180
  progress_path = LOCAL_TEMP_DIR / PROGRESS_FILE
181
  progress_path.parent.mkdir(parents=True, exist_ok=True)
182
  with open(progress_path, "w") as f:
@@ -184,7 +180,7 @@ def save_progress_local(completed_set):
184
  return progress_path
185
 
186
  # ----------------------------------------------------------------------
187
- # 8. CORE LOGIC (RATE LIMIT, BATCH UPLOAD, ARIA2, CRAWLER)
188
  # ----------------------------------------------------------------------
189
  commit_times = []
190
 
@@ -198,17 +194,13 @@ def check_rate_limit():
198
  if sleep_time > 0:
199
  log_mirror(f"[Rate Limit] Sleeping {sleep_time/60:.2f} min...")
200
  time.sleep(sleep_time)
201
- now = time.time()
202
  commit_times = [t for t in commit_times if now - t < 3600]
203
 
204
  def upload_batch(batch_files, completed_set):
205
- """Upload a batch of files plus the updated progress file in a single commit."""
206
  if not batch_files:
207
  return
208
  check_rate_limit()
209
  log_mirror(f"Uploading {len(batch_files)} files...")
210
-
211
- # Update completed set and save progress
212
  for rel_path, _ in batch_files:
213
  completed_set.add(rel_path)
214
  progress_path = save_progress_local(completed_set)
@@ -223,7 +215,7 @@ def upload_batch(batch_files, completed_set):
223
  repo_id=HF_REPO_ID,
224
  repo_type=HF_REPO_TYPE,
225
  operations=operations,
226
- commit_message=f"Sync: {len(batch_files)} files + progress update"
227
  )
228
  commit_times.append(time.time())
229
  for _, local_path in batch_files:
@@ -251,28 +243,36 @@ def download_with_aria2(url, dest_path):
251
  ]
252
  try:
253
  result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
254
- if result.returncode == 0:
255
- return True
256
- else:
257
- log_mirror(f"⚠️ Download error: {dest_path.name}")
258
- return False
259
  except subprocess.TimeoutExpired:
260
  log_mirror(f"⚠️ Timeout: {dest_path.name}")
261
  return False
262
  except Exception as e:
263
- log_mirror(f"⚠️ Exception: {e}")
264
  return False
265
 
266
  def crawl_onion_directory(url, rel_path=""):
267
- try:
268
- r = session.get(url, timeout=90)
269
- r.raise_for_status()
270
- except Exception as e:
271
- log_mirror(f"⚠️ Failed to access directory '{rel_path or 'root'}': {e}")
 
 
 
 
 
 
 
 
 
272
  return
273
-
274
  soup = BeautifulSoup(r.text, 'html.parser')
275
- for link in soup.find_all('a'):
 
 
 
276
  href = link.get('href')
277
  if not href or href.startswith('?') or href == '../' or href.startswith('/'):
278
  continue
@@ -304,7 +304,6 @@ def run_mirror():
304
 
305
  LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
306
 
307
- # Load progress (from dataset or local fallback)
308
  completed_files = download_progress_from_hf()
309
  if not completed_files:
310
  local_progress = LOCAL_TEMP_DIR / PROGRESS_FILE
@@ -314,56 +313,63 @@ def run_mirror():
314
  completed_files = set(data.get("completed_files", []))
315
  log_mirror(f"Loaded local progress: {len(completed_files)} files.")
316
 
317
- log_mirror("Starting crawler on onion directory...")
318
 
319
  batch_files = []
320
  batch_size = 0
321
  target_bytes = BATCH_SIZE_MB * 1024 * 1024
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
- continue
329
-
330
- local_path = LOCAL_TEMP_DIR / rel_path
331
- future = executor.submit(download_with_aria2, file_url, local_path)
332
- pending_futures.append((future, rel_path, local_path))
333
-
334
- if len(pending_futures) >= DOWNLOAD_WORKERS * 2:
335
- for fut, rel, lpath in pending_futures:
336
- success = fut.result()
337
- if success and lpath.exists():
338
- file_size = lpath.stat().st_size
339
- batch_size += file_size
340
- batch_files.append((rel, lpath))
341
- log_mirror(f"Downloaded: {rel} | Batch: {batch_size/(1024*1024):.1f} MB")
342
- else:
343
- log_mirror(f"Failed: {rel}")
344
- pending_futures.clear()
345
-
346
- if batch_size >= target_bytes:
347
- upload_batch(batch_files, completed_files)
348
- batch_files = []
349
- batch_size = 0
350
-
351
- # Process remaining futures
352
- for fut, rel, lpath in pending_futures:
353
- success = fut.result()
354
- if success and lpath.exists():
355
- file_size = lpath.stat().st_size
356
- batch_size += file_size
357
- batch_files.append((rel, lpath))
358
 
359
- if batch_files:
360
- upload_batch(batch_files, completed_files)
361
-
362
- executor.shutdown(wait=True)
363
- log_mirror("βœ… MIRRORING COMPLETED SUCCESSFULLY!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
 
365
  # ----------------------------------------------------------------------
366
- # 10. PURE HTML/CSS WEB SERVER (reads UI_LOG_FILE)
367
  # ----------------------------------------------------------------------
368
  HTML_PAGE = """
369
  <!DOCTYPE html>
@@ -403,7 +409,6 @@ HTML_PAGE = """
403
  const response = await fetch('/api/logs');
404
  const data = await response.json();
405
  const logBox = document.getElementById('log-box');
406
-
407
  const isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 50;
408
  logBox.textContent = data.logs;
409
  if (isScrolledToBottom) {
@@ -413,7 +418,6 @@ HTML_PAGE = """
413
  console.error("Error fetching logs", err);
414
  }
415
  }
416
-
417
  setInterval(fetchLogs, 2000);
418
  fetchLogs();
419
  </script>
@@ -424,7 +428,6 @@ HTML_PAGE = """
424
  class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
425
  def do_GET(self):
426
  parsed_path = urlparse(self.path).path
427
-
428
  if parsed_path == "/" or parsed_path == "/index.html":
429
  html = HTML_PAGE.encode("utf-8")
430
  self.send_response(200)
@@ -432,7 +435,6 @@ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
432
  self.send_header("Content-Length", str(len(html)))
433
  self.end_headers()
434
  self.wfile.write(html)
435
-
436
  elif parsed_path == "/api/logs":
437
  try:
438
  with open(UI_LOG_FILE, "r") as f:
@@ -440,18 +442,15 @@ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
440
  logs_str = "".join(lines)
441
  except Exception:
442
  logs_str = "Loading logs..."
443
-
444
  body = json.dumps({"logs": logs_str}).encode("utf-8")
445
  self.send_response(200)
446
  self.send_header("Content-type", "application/json")
447
  self.send_header("Content-Length", str(len(body)))
448
  self.end_headers()
449
  self.wfile.write(body)
450
-
451
  else:
452
  self.send_response(404)
453
  self.end_headers()
454
-
455
  def log_message(self, format, *args):
456
  pass
457
 
@@ -464,8 +463,5 @@ def start_web_server():
464
  httpd.serve_forever()
465
 
466
  if __name__ == "__main__":
467
- # Start mirroring in background daemon thread
468
  threading.Thread(target=run_mirror, daemon=True).start()
469
-
470
- # Start HTTP server (blocks main thread)
471
  start_web_server()
 
49
  HF_REPO_TYPE = "dataset"
50
 
51
  LOCAL_TEMP_DIR = Path("./hf_mirror_temp")
52
+ LOG_FILE = "mirror_activity.log"
53
+ UI_LOG_FILE = "mirror_ui.log"
54
+ PROGRESS_FILE = "mirror_progress.json"
55
 
56
  BATCH_SIZE_MB = 100
57
  MAX_COMMITS_PER_HOUR = 124
58
  DOWNLOAD_WORKERS = 4
59
  TOR_SOCKS_PORT = 9050
60
+ DIR_TIMEOUT = 30 # seconds for directory listing requests
61
+ MAX_RETRIES = 3
62
 
 
63
  with open(LOG_FILE, "w") as f:
64
  f.write("System logs (not shown in UI)\n")
65
 
 
66
  with open(UI_LOG_FILE, "w") as f:
67
  f.write("Mirror initializing...\n")
68
 
69
  def log_system(msg):
 
70
  print(msg, flush=True)
71
  with open(LOG_FILE, "a") as f:
72
  f.write(msg + "\n")
73
 
74
  def log_mirror(msg):
 
75
  print(msg, flush=True)
76
  with open(UI_LOG_FILE, "a") as f:
77
  f.write(msg + "\n")
78
 
79
  if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
80
+ log_system("⚠️ Missing secrets!")
81
+ log_mirror("❌ Missing secrets! Check Space Secrets.")
82
+ # Do not exit here; web server must still start
83
 
84
  # ----------------------------------------------------------------------
85
  # 4. START TOR MANUALLY
 
92
  DataDirectory {tor_dir}
93
  Log notice file {tor_dir}/tor.log
94
  RunAsDaemon 1""")
95
+ log_system("Starting Tor proxy...")
 
96
  subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
 
97
  import socket
98
  for _ in range(30):
99
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
101
  result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
102
  sock.close()
103
  if result == 0:
104
+ log_system("βœ… Tor ready.")
105
  log_mirror("βœ… Tor proxy ready.")
106
  return
107
  time.sleep(1)
108
+ raise RuntimeError("Tor failed to start.")
109
 
110
  # ----------------------------------------------------------------------
111
+ # 5. IMPORTS & TOR SESSION
112
  # ----------------------------------------------------------------------
113
  from bs4 import BeautifulSoup
114
  import requests
 
118
 
119
  session = requests.Session()
120
  session.proxies = {
121
+ 'http': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}',
122
  'https': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}'
123
  }
124
+ retries = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
125
  session.mount("http://", HTTPAdapter(max_retries=retries))
126
  session.mount("https://", HTTPAdapter(max_retries=retries))
127
 
128
  def verify_tor():
129
+ log_system("Testing Tor connection...")
130
  try:
131
  res = session.get("http://httpbin.org/ip", timeout=10)
132
  res.raise_for_status()
133
+ ip = res.json()['origin']
134
+ log_system(f"Tor Active! IP: {ip}")
135
+ log_mirror(f"βœ… Tor proxy active (IP: {ip})")
136
  return True
137
  except Exception as e:
138
+ log_system(f"Tor test failed: {e}")
139
  log_mirror(f"⚠️ Tor proxy test failed: {e}")
140
  return False
141
 
142
  # ----------------------------------------------------------------------
143
+ # 6. HUGGING FACE AUTH
144
  # ----------------------------------------------------------------------
145
  api = None
146
 
147
  def authenticate_hf():
148
  global api
149
  if not HF_TOKEN:
150
+ raise ValueError("HF_TOKEN missing")
151
  login(token=HF_TOKEN)
152
  api = HfApi()
153
 
154
  # ----------------------------------------------------------------------
155
+ # 7. PROGRESS FILE
156
  # ----------------------------------------------------------------------
157
  def download_progress_from_hf():
 
158
  log_mirror("Checking previous progress...")
159
  try:
160
  url = f"https://huggingface.co/datasets/{HF_REPO_ID}/resolve/main/{PROGRESS_FILE}"
 
173
  return set()
174
 
175
  def save_progress_local(completed_set):
 
176
  progress_path = LOCAL_TEMP_DIR / PROGRESS_FILE
177
  progress_path.parent.mkdir(parents=True, exist_ok=True)
178
  with open(progress_path, "w") as f:
 
180
  return progress_path
181
 
182
  # ----------------------------------------------------------------------
183
+ # 8. CORE LOGIC
184
  # ----------------------------------------------------------------------
185
  commit_times = []
186
 
 
194
  if sleep_time > 0:
195
  log_mirror(f"[Rate Limit] Sleeping {sleep_time/60:.2f} min...")
196
  time.sleep(sleep_time)
 
197
  commit_times = [t for t in commit_times if now - t < 3600]
198
 
199
  def upload_batch(batch_files, completed_set):
 
200
  if not batch_files:
201
  return
202
  check_rate_limit()
203
  log_mirror(f"Uploading {len(batch_files)} files...")
 
 
204
  for rel_path, _ in batch_files:
205
  completed_set.add(rel_path)
206
  progress_path = save_progress_local(completed_set)
 
215
  repo_id=HF_REPO_ID,
216
  repo_type=HF_REPO_TYPE,
217
  operations=operations,
218
+ commit_message=f"Sync: {len(batch_files)} files + progress"
219
  )
220
  commit_times.append(time.time())
221
  for _, local_path in batch_files:
 
243
  ]
244
  try:
245
  result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
246
+ return result.returncode == 0
 
 
 
 
247
  except subprocess.TimeoutExpired:
248
  log_mirror(f"⚠️ Timeout: {dest_path.name}")
249
  return False
250
  except Exception as e:
251
+ log_mirror(f"⚠️ Download exception: {e}")
252
  return False
253
 
254
  def crawl_onion_directory(url, rel_path=""):
255
+ """Recursive generator that yields (file_url, relative_path) with retries."""
256
+ for attempt in range(MAX_RETRIES):
257
+ try:
258
+ log_mirror(f"πŸ“ Exploring directory: {rel_path or '/'} (attempt {attempt+1})")
259
+ r = session.get(url, timeout=DIR_TIMEOUT)
260
+ r.raise_for_status()
261
+ break
262
+ except Exception as e:
263
+ if attempt == MAX_RETRIES - 1:
264
+ log_mirror(f"⚠️ Failed to access directory '{rel_path or '/'}': {e}")
265
+ return
266
+ log_mirror(f"⚠️ Retry {attempt+1}/{MAX_RETRIES} for directory '{rel_path or '/'}'")
267
+ time.sleep(5 * (attempt + 1))
268
+ else:
269
  return
270
+
271
  soup = BeautifulSoup(r.text, 'html.parser')
272
+ links = soup.find_all('a')
273
+ log_mirror(f" Found {len(links)} links in {rel_path or '/'}")
274
+
275
+ for link in links:
276
  href = link.get('href')
277
  if not href or href.startswith('?') or href == '../' or href.startswith('/'):
278
  continue
 
304
 
305
  LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
306
 
 
307
  completed_files = download_progress_from_hf()
308
  if not completed_files:
309
  local_progress = LOCAL_TEMP_DIR / PROGRESS_FILE
 
313
  completed_files = set(data.get("completed_files", []))
314
  log_mirror(f"Loaded local progress: {len(completed_files)} files.")
315
 
316
+ log_mirror("πŸš€ Starting crawler...")
317
 
318
  batch_files = []
319
  batch_size = 0
320
  target_bytes = BATCH_SIZE_MB * 1024 * 1024
 
321
  executor = ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS)
322
  pending_futures = []
323
 
324
+ try:
325
+ for file_url, rel_path in crawl_onion_directory(ONION_URL):
326
+ if rel_path in completed_files:
327
+ log_mirror(f"⏭️ Skipping already done: {rel_path}")
328
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
 
330
+ local_path = LOCAL_TEMP_DIR / rel_path
331
+ future = executor.submit(download_with_aria2, file_url, local_path)
332
+ pending_futures.append((future, rel_path, local_path))
333
+ log_mirror(f"⬇️ Download queued: {rel_path}")
334
+
335
+ if len(pending_futures) >= DOWNLOAD_WORKERS * 2:
336
+ for fut, rel, lpath in pending_futures:
337
+ success = fut.result()
338
+ if success and lpath.exists():
339
+ file_size = lpath.stat().st_size
340
+ batch_size += file_size
341
+ batch_files.append((rel, lpath))
342
+ log_mirror(f"βœ… Downloaded: {rel} | Batch: {batch_size/(1024*1024):.1f} MB")
343
+ else:
344
+ log_mirror(f"❌ Failed: {rel}")
345
+ pending_futures.clear()
346
+
347
+ if batch_size >= target_bytes:
348
+ upload_batch(batch_files, completed_files)
349
+ batch_files = []
350
+ batch_size = 0
351
+
352
+ # Process remaining
353
+ for fut, rel, lpath in pending_futures:
354
+ success = fut.result()
355
+ if success and lpath.exists():
356
+ file_size = lpath.stat().st_size
357
+ batch_size += file_size
358
+ batch_files.append((rel, lpath))
359
+ log_mirror(f"βœ… Downloaded: {rel} | Batch: {batch_size/(1024*1024):.1f} MB")
360
+ else:
361
+ log_mirror(f"❌ Failed: {rel}")
362
+
363
+ if batch_files:
364
+ upload_batch(batch_files, completed_files)
365
+
366
+ executor.shutdown(wait=True)
367
+ log_mirror("πŸŽ‰ MIRRORING COMPLETED SUCCESSFULLY!")
368
+ except Exception as e:
369
+ log_mirror(f"❌ Unexpected error in mirror loop: {e}")
370
 
371
  # ----------------------------------------------------------------------
372
+ # 10. WEB SERVER
373
  # ----------------------------------------------------------------------
374
  HTML_PAGE = """
375
  <!DOCTYPE html>
 
409
  const response = await fetch('/api/logs');
410
  const data = await response.json();
411
  const logBox = document.getElementById('log-box');
 
412
  const isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 50;
413
  logBox.textContent = data.logs;
414
  if (isScrolledToBottom) {
 
418
  console.error("Error fetching logs", err);
419
  }
420
  }
 
421
  setInterval(fetchLogs, 2000);
422
  fetchLogs();
423
  </script>
 
428
  class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
429
  def do_GET(self):
430
  parsed_path = urlparse(self.path).path
 
431
  if parsed_path == "/" or parsed_path == "/index.html":
432
  html = HTML_PAGE.encode("utf-8")
433
  self.send_response(200)
 
435
  self.send_header("Content-Length", str(len(html)))
436
  self.end_headers()
437
  self.wfile.write(html)
 
438
  elif parsed_path == "/api/logs":
439
  try:
440
  with open(UI_LOG_FILE, "r") as f:
 
442
  logs_str = "".join(lines)
443
  except Exception:
444
  logs_str = "Loading logs..."
 
445
  body = json.dumps({"logs": logs_str}).encode("utf-8")
446
  self.send_response(200)
447
  self.send_header("Content-type", "application/json")
448
  self.send_header("Content-Length", str(len(body)))
449
  self.end_headers()
450
  self.wfile.write(body)
 
451
  else:
452
  self.send_response(404)
453
  self.end_headers()
 
454
  def log_message(self, format, *args):
455
  pass
456
 
 
463
  httpd.serve_forever()
464
 
465
  if __name__ == "__main__":
 
466
  threading.Thread(target=run_mirror, daemon=True).start()
 
 
467
  start_web_server()