Update app.py
Browse files
app.py
CHANGED
|
@@ -1,505 +1,325 @@
|
|
| 1 |
import os
|
| 2 |
-
import sys
|
| 3 |
-
import time
|
| 4 |
import json
|
| 5 |
-
import
|
| 6 |
import threading
|
| 7 |
-
import http.server
|
| 8 |
-
import socketserver
|
| 9 |
from pathlib import Path
|
| 10 |
-
from urllib.parse import
|
| 11 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
-
|
| 13 |
-
# ----------------------------------------------------------------------
|
| 14 |
-
# 1. ZEROGPU REQUIREMENT (MUST BE AT THE TOP)
|
| 15 |
-
# ----------------------------------------------------------------------
|
| 16 |
-
import spaces
|
| 17 |
-
|
| 18 |
-
@spaces.GPU(duration=10)
|
| 19 |
-
def dummy_gpu():
|
| 20 |
-
"""Dummy function to keep the ZeroGPU orchestrator happy"""
|
| 21 |
-
pass
|
| 22 |
-
|
| 23 |
-
# ----------------------------------------------------------------------
|
| 24 |
-
# 2. SYSTEM SETUP
|
| 25 |
-
# ----------------------------------------------------------------------
|
| 26 |
-
def run_cmd(cmd, desc=""):
|
| 27 |
-
print(f"\n[Setup] {desc}", flush=True)
|
| 28 |
-
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
| 29 |
-
if result.returncode != 0:
|
| 30 |
-
print(f"Warning: {result.stderr}", flush=True)
|
| 31 |
-
return result
|
| 32 |
-
|
| 33 |
-
run_cmd("echo 'exit 101' > /usr/sbin/policy-rc.d && chmod +x /usr/sbin/policy-rc.d", "Disabling service auto-start")
|
| 34 |
-
run_cmd("apt-get update -qq", "Updating package lists")
|
| 35 |
-
run_cmd("apt-get install -y tor aria2 -qq", "Installing Tor and aria2")
|
| 36 |
-
|
| 37 |
-
# Install missing Python packages (including lxml for faster HTML parsing)
|
| 38 |
-
run_cmd("pip install -q requests[socks] huggingface_hub beautifulsoup4 tqdm lxml", "Installing Python packages")
|
| 39 |
-
|
| 40 |
-
subprocess.run(["pkill", "tor"], capture_output=True, text=True)
|
| 41 |
-
time.sleep(1)
|
| 42 |
-
|
| 43 |
-
# ----------------------------------------------------------------------
|
| 44 |
-
# 3. CONFIGURATION & LOGGING
|
| 45 |
-
# ----------------------------------------------------------------------
|
| 46 |
-
ONION_URL = os.environ.get("ONION_URL", "")
|
| 47 |
-
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
|
| 48 |
-
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"
|
| 53 |
-
COMPLETED_DIRS_FILE = Path("./completed_dirs.txt") # Checkpoint file
|
| 54 |
-
BATCH_SIZE_MB = 100
|
| 55 |
-
MAX_COMMITS_PER_HOUR = 124
|
| 56 |
-
DOWNLOAD_WORKERS = 4
|
| 57 |
-
TOR_SOCKS_PORT = 9050
|
| 58 |
-
|
| 59 |
-
# Global set to hold directory paths that were fully mirrored in previous runs
|
| 60 |
-
completed_dirs = set()
|
| 61 |
-
uploaded_files_count = 0
|
| 62 |
-
uploaded_bytes_total = 0
|
| 63 |
-
|
| 64 |
-
# Reset log file on startup
|
| 65 |
-
with open(LOG_FILE, "w") as f:
|
| 66 |
-
f.write("System initialized. Starting background mirror...\n")
|
| 67 |
-
|
| 68 |
-
def log(msg, to_web=True):
|
| 69 |
-
"""Write logs to console (unmasked) and persistent file (masked) so they survive page reloads"""
|
| 70 |
-
# 1. Print real, unmasked message to the terminal console
|
| 71 |
-
print(msg, flush=True)
|
| 72 |
-
|
| 73 |
-
# 2. Mask the Onion address before saving to the Web UI log file
|
| 74 |
-
if to_web:
|
| 75 |
-
safe_msg = msg
|
| 76 |
-
if ONION_URL:
|
| 77 |
-
domain = urlparse(ONION_URL).netloc
|
| 78 |
-
if domain:
|
| 79 |
-
safe_msg = safe_msg.replace(domain, "[HIDDEN.onion]")
|
| 80 |
-
|
| 81 |
-
with open(LOG_FILE, "a") as f:
|
| 82 |
-
f.write(safe_msg + "\n")
|
| 83 |
-
|
| 84 |
-
if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
|
| 85 |
-
log("โ ๏ธ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
|
| 86 |
-
|
| 87 |
-
# ----------------------------------------------------------------------
|
| 88 |
-
# 4. START TOR MANUALLY
|
| 89 |
-
# ----------------------------------------------------------------------
|
| 90 |
-
def start_tor():
|
| 91 |
-
tor_dir = Path("/tmp/tor-data")
|
| 92 |
-
tor_dir.mkdir(exist_ok=True)
|
| 93 |
-
torrc = tor_dir / "torrc"
|
| 94 |
-
|
| 95 |
-
torrc.write_text(f"""SocksPort {TOR_SOCKS_PORT}
|
| 96 |
-
DataDirectory {tor_dir}
|
| 97 |
-
Log notice file {tor_dir}/tor.log
|
| 98 |
-
RunAsDaemon 1
|
| 99 |
-
""")
|
| 100 |
-
|
| 101 |
-
log("Starting Tor proxy in the background...")
|
| 102 |
-
subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
|
| 103 |
-
|
| 104 |
-
import socket
|
| 105 |
-
for _ in range(30):
|
| 106 |
-
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 107 |
-
sock.settimeout(1)
|
| 108 |
-
result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
|
| 109 |
-
sock.close()
|
| 110 |
-
if result == 0:
|
| 111 |
-
log("โ
Tor SOCKS proxy is ready.")
|
| 112 |
-
return
|
| 113 |
-
time.sleep(1)
|
| 114 |
-
|
| 115 |
-
raise RuntimeError("โ Tor failed to start.")
|
| 116 |
-
|
| 117 |
-
# ----------------------------------------------------------------------
|
| 118 |
-
# 5. IMPORTS & TOR SESSION SETUP
|
| 119 |
-
# ----------------------------------------------------------------------
|
| 120 |
from bs4 import BeautifulSoup
|
| 121 |
import requests
|
| 122 |
from requests.adapters import HTTPAdapter
|
| 123 |
from urllib3.util.retry import Retry
|
| 124 |
-
from huggingface_hub import HfApi, login, CommitOperationAdd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
}
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
def verify_tor():
|
| 137 |
-
|
| 138 |
try:
|
| 139 |
-
res = session.get("http://httpbin.org/ip", timeout=
|
| 140 |
-
res.
|
| 141 |
-
|
|
|
|
| 142 |
return True
|
| 143 |
except Exception as e:
|
| 144 |
-
|
|
|
|
| 145 |
return False
|
| 146 |
|
| 147 |
-
#
|
| 148 |
-
#
|
| 149 |
-
#
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
-
def check_rate_limit():
|
| 165 |
-
|
| 166 |
now = time.time()
|
| 167 |
-
commit_times = [t for t in commit_times if now - t < 3600]
|
| 168 |
-
if len(commit_times) >= MAX_COMMITS_PER_HOUR:
|
| 169 |
-
|
| 170 |
-
sleep_time = 3600 - (now -
|
| 171 |
if sleep_time > 0:
|
| 172 |
-
|
| 173 |
time.sleep(sleep_time)
|
| 174 |
now = time.time()
|
| 175 |
-
commit_times = [t for t in commit_times if now - t < 3600]
|
| 176 |
|
| 177 |
-
def upload_batch(batch_files):
|
| 178 |
-
|
| 179 |
if not batch_files:
|
| 180 |
return
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
operations = []
|
| 185 |
for rel_path, local_path in batch_files:
|
| 186 |
operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
|
| 187 |
-
|
| 188 |
-
try:
|
| 189 |
-
api.create_commit(
|
| 190 |
-
repo_id=HF_REPO_ID,
|
| 191 |
-
repo_type=HF_REPO_TYPE,
|
| 192 |
-
operations=operations,
|
| 193 |
-
commit_message=f"Sync: {len(batch_files)} files (Batch Upload)"
|
| 194 |
-
)
|
| 195 |
-
commit_times.append(time.time())
|
| 196 |
-
for rel_path, local_path in batch_files:
|
| 197 |
-
if local_path.exists():
|
| 198 |
-
file_size = local_path.stat().st_size
|
| 199 |
-
local_path.unlink()
|
| 200 |
-
uploaded_files_count += 1
|
| 201 |
-
uploaded_bytes_total += file_size
|
| 202 |
-
log(f"โ
Batch upload successful! Total uploaded so far: {uploaded_files_count} files, {uploaded_bytes_total/(1024*1024):.2f} MB")
|
| 203 |
-
except Exception as e:
|
| 204 |
-
log(f"โ Upload failed: {e}")
|
| 205 |
-
|
| 206 |
-
def download_with_aria2(url, dest_path):
|
| 207 |
-
dest_path = Path(dest_path)
|
| 208 |
-
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 209 |
-
|
| 210 |
-
cmd = [
|
| 211 |
-
"aria2c",
|
| 212 |
-
f"--all-proxy=socks5h://127.0.0.1:{TOR_SOCKS_PORT}",
|
| 213 |
-
"--max-connection-per-server=16",
|
| 214 |
-
"--split=16",
|
| 215 |
-
"--min-split-size=1M",
|
| 216 |
-
"--continue=true",
|
| 217 |
-
"--auto-file-renaming=false",
|
| 218 |
-
"--allow-overwrite=true",
|
| 219 |
-
f"--dir={dest_path.parent}",
|
| 220 |
-
f"--out={dest_path.name}",
|
| 221 |
-
url
|
| 222 |
-
]
|
| 223 |
-
|
| 224 |
-
try:
|
| 225 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
|
| 226 |
-
if result.returncode == 0:
|
| 227 |
-
return True
|
| 228 |
-
else:
|
| 229 |
-
log(f"aria2 error for {url}: {result.stderr[:100]}...")
|
| 230 |
-
return False
|
| 231 |
-
except subprocess.TimeoutExpired:
|
| 232 |
-
log(f"aria2 timeout for {url}")
|
| 233 |
-
return False
|
| 234 |
-
except Exception as e:
|
| 235 |
-
log(f"aria2 exception: {e}")
|
| 236 |
-
return False
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
if rel_path in completed_dirs:
|
| 247 |
-
log(f"โฉ Skipping already mirrored directory: /{rel_path}")
|
| 248 |
-
return
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
try:
|
| 255 |
-
r = session.get(url, timeout=120)
|
| 256 |
r.raise_for_status()
|
| 257 |
except Exception as e:
|
| 258 |
-
|
| 259 |
return
|
| 260 |
|
| 261 |
-
|
| 262 |
-
elapsed = time.time() - start_time
|
| 263 |
-
log(f" โ
Fetched listing in {elapsed:.2f}s ({len(html)} bytes)")
|
| 264 |
-
|
| 265 |
-
# Use lxml for faster parsing if available, else fallback to html.parser
|
| 266 |
-
try:
|
| 267 |
-
soup = BeautifulSoup(html, 'lxml')
|
| 268 |
-
except ImportError:
|
| 269 |
-
soup = BeautifulSoup(html, 'html.parser')
|
| 270 |
-
|
| 271 |
-
subdirectory_links = []
|
| 272 |
-
file_count = 0
|
| 273 |
-
|
| 274 |
-
# Iterate over links, yield files immediately, collect directories for later
|
| 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
|
| 279 |
-
|
| 280 |
clean_name = unquote(href)
|
| 281 |
full_url = urljoin(url, href)
|
| 282 |
-
new_rel_path =
|
| 283 |
-
|
| 284 |
if href.endswith('/'):
|
| 285 |
-
|
| 286 |
else:
|
| 287 |
-
file_count += 1
|
| 288 |
-
# Yield file immediately so download can start
|
| 289 |
yield (full_url, new_rel_path)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
success = True
|
| 295 |
-
for sub_url, sub_path in subdirectory_links:
|
| 296 |
-
try:
|
| 297 |
-
yield from crawl_onion_directory(sub_url, sub_path)
|
| 298 |
-
except Exception as e:
|
| 299 |
-
log(f"โ ๏ธ Error while processing subdirectory {sub_path}: {e}")
|
| 300 |
-
success = False
|
| 301 |
-
|
| 302 |
-
# Mark directory as completed only if all subdirectories were processed without fatal errors
|
| 303 |
-
if success:
|
| 304 |
-
completed_dirs.add(rel_path)
|
| 305 |
-
with open(COMPLETED_DIRS_FILE, "a") as f:
|
| 306 |
-
f.write(rel_path + "\n")
|
| 307 |
-
log(f"โ
Directory fully mirrored: /{rel_path}")
|
| 308 |
-
else:
|
| 309 |
-
log(f"โ ๏ธ Directory not marked as completed due to errors: /{rel_path}")
|
| 310 |
-
|
| 311 |
-
# ----------------------------------------------------------------------
|
| 312 |
-
# 8. MAIN MIRROR THREAD
|
| 313 |
-
# ----------------------------------------------------------------------
|
| 314 |
def run_mirror():
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
except Exception as e:
|
| 322 |
-
log(f"โ Initialization failed: {e}")
|
| 323 |
return
|
| 324 |
-
|
| 325 |
-
verify_tor()
|
| 326 |
LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
else:
|
| 334 |
-
completed_dirs = set()
|
| 335 |
-
log("No previous completed directories found. Starting fresh.")
|
| 336 |
-
|
| 337 |
-
log(f"Starting crawler at: {ONION_URL}")
|
| 338 |
-
|
| 339 |
batch_files = []
|
| 340 |
batch_size = 0
|
| 341 |
target_bytes = BATCH_SIZE_MB * 1024 * 1024
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
file_size = lpath.stat().st_size
|
| 352 |
-
batch_size += file_size
|
| 353 |
-
batch_files.append((rel, lpath))
|
| 354 |
-
processed_count += 1
|
| 355 |
-
log(f"Downloaded: {rel} | Size: {file_size/(1024*1024):.2f} MB | Batch: {batch_size/(1024*1024):.1f} MB")
|
| 356 |
-
else:
|
| 357 |
-
log(f"Failed: {rel}")
|
| 358 |
-
# Optionally delete partial file
|
| 359 |
-
if lpath.exists():
|
| 360 |
-
lpath.unlink()
|
| 361 |
-
|
| 362 |
-
for file_url, rel_path in crawl_onion_directory(ONION_URL):
|
| 363 |
-
local_path = LOCAL_TEMP_DIR / rel_path
|
| 364 |
-
future = executor.submit(download_with_aria2, file_url, local_path)
|
| 365 |
-
pending_futures.append((future, rel_path, local_path))
|
| 366 |
-
|
| 367 |
-
# When we have enough pending downloads, process them
|
| 368 |
-
if len(pending_futures) >= DOWNLOAD_WORKERS * 2:
|
| 369 |
-
for fut, rel, lpath in pending_futures:
|
| 370 |
-
process_future(fut, rel, lpath)
|
| 371 |
-
pending_futures.clear()
|
| 372 |
-
|
| 373 |
-
if batch_size >= target_bytes:
|
| 374 |
-
upload_batch(batch_files)
|
| 375 |
-
batch_files = []
|
| 376 |
-
batch_size = 0
|
| 377 |
-
|
| 378 |
-
# Process remaining futures
|
| 379 |
-
for fut, rel, lpath in pending_futures:
|
| 380 |
-
process_future(fut, rel, lpath)
|
| 381 |
-
|
| 382 |
-
if batch_files:
|
| 383 |
-
upload_batch(batch_files)
|
| 384 |
-
|
| 385 |
-
executor.shutdown(wait=True)
|
| 386 |
-
|
| 387 |
-
log("โ
MIRRORING COMPLETED SUCCESSFULLY!")
|
| 388 |
-
log(f" Total files uploaded: {uploaded_files_count}")
|
| 389 |
-
log(f" Total data uploaded: {uploaded_bytes_total/(1024*1024):.2f} MB")
|
| 390 |
-
|
| 391 |
-
# ----------------------------------------------------------------------
|
| 392 |
-
# 9. PURE HTML/CSS WEB SERVER
|
| 393 |
-
# ----------------------------------------------------------------------
|
| 394 |
-
HTML_PAGE = """<!DOCTYPE html>
|
| 395 |
-
<html lang="en">
|
| 396 |
-
<head>
|
| 397 |
-
<meta charset="UTF-8">
|
| 398 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 399 |
-
<title>Onion โ Hugging Face Mirror</title>
|
| 400 |
-
<style>
|
| 401 |
-
:root { --bg: #0f1117; --card: #1a1d24; --accent: #4f8cff; --text: #e0e0e0; }
|
| 402 |
-
body { background: var(--bg); color: var(--text); font-family: 'Segoe UI', system-ui, sans-serif; margin: 0; padding: 20px; display: flex; justify-content: center; }
|
| 403 |
-
.container { background: var(--card); border-radius: 12px; padding: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); width: 100%; max-width: 900px; }
|
| 404 |
-
h1 { color: var(--accent); text-align: center; margin-top: 0; }
|
| 405 |
-
p.subtitle { text-align: center; color: #888; margin-bottom: 20px; }
|
| 406 |
-
hr { border: 1px solid #333; margin-bottom: 20px; }
|
| 407 |
-
.status-box { background: #232730; padding: 10px; border-radius: 8px; text-align: center; font-weight: bold; margin-bottom: 20px; color: #4ade80; }
|
| 408 |
-
.log-container { display: flex; flex-direction: column; height: 500px; }
|
| 409 |
-
.log-header { font-weight: bold; margin-bottom: 10px; }
|
| 410 |
-
.log-box { background: #0a0c10; color: #4ade80; font-family: 'Courier New', monospace; padding: 15px; border-radius: 8px; flex-grow: 1; overflow-y: auto; white-space: pre-wrap; font-size: 14px; border: 1px solid #333; }
|
| 411 |
-
</style>
|
| 412 |
-
</head>
|
| 413 |
-
<body>
|
| 414 |
-
<div class="container">
|
| 415 |
-
<h1>๐ Onion Directory Mirror (ZeroGPU)</h1>
|
| 416 |
-
<p class="subtitle">Automatically downloading and pushing to Hugging Face in the background.</p>
|
| 417 |
-
<hr>
|
| 418 |
-
<div class="status-box">โ
Background Mirroring is Active (You can safely close this page)</div>
|
| 419 |
-
|
| 420 |
-
<div class="log-container">
|
| 421 |
-
<div class="log-header">Live Activity Logs:</div>
|
| 422 |
-
<div class="log-box" id="log-box">Initializing and waiting for logs...</div>
|
| 423 |
-
</div>
|
| 424 |
-
</div>
|
| 425 |
-
<script>
|
| 426 |
-
async function fetchLogs() {
|
| 427 |
-
try {
|
| 428 |
-
const response = await fetch('/api/logs');
|
| 429 |
-
const data = await response.json();
|
| 430 |
-
const logBox = document.getElementById('log-box');
|
| 431 |
-
|
| 432 |
-
// Only autoscroll if user is near the bottom
|
| 433 |
-
const isScrolledToBottom = logBox.scrollHeight - logBox.clientHeight <= logBox.scrollTop + 50;
|
| 434 |
-
|
| 435 |
-
logBox.textContent = data.logs;
|
| 436 |
-
|
| 437 |
-
if (isScrolledToBottom) {
|
| 438 |
-
logBox.scrollTop = logBox.scrollHeight;
|
| 439 |
-
}
|
| 440 |
-
} catch (err) {
|
| 441 |
-
console.error("Error fetching logs", err);
|
| 442 |
-
}
|
| 443 |
-
}
|
| 444 |
-
|
| 445 |
-
// Fetch logs every 2 seconds
|
| 446 |
-
setInterval(fetchLogs, 2000);
|
| 447 |
-
fetchLogs();
|
| 448 |
-
</script>
|
| 449 |
-
</body>
|
| 450 |
-
</html>"""
|
| 451 |
-
|
| 452 |
-
class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
| 453 |
-
def do_GET(self):
|
| 454 |
-
# Ignore query parameters like ?__theme=dark
|
| 455 |
-
parsed_path = urlparse(self.path).path
|
| 456 |
-
|
| 457 |
-
if parsed_path == "/" or parsed_path == "/index.html":
|
| 458 |
-
html = HTML_PAGE.encode("utf-8")
|
| 459 |
-
self.send_response(200)
|
| 460 |
-
self.send_header("Content-type", "text/html; charset=utf-8")
|
| 461 |
-
self.send_header("Content-Length", str(len(html)))
|
| 462 |
-
self.end_headers()
|
| 463 |
-
self.wfile.write(html)
|
| 464 |
-
|
| 465 |
-
elif parsed_path == "/api/logs":
|
| 466 |
try:
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
pass
|
| 487 |
-
|
| 488 |
-
def start_web_server():
|
| 489 |
-
port = 7860
|
| 490 |
-
handler = CustomHTTPRequestHandler
|
| 491 |
-
# Use ThreadingHTTPServer from http.server (not socketserver)
|
| 492 |
-
httpd = http.server.ThreadingHTTPServer(("0.0.0.0", port), handler)
|
| 493 |
-
httpd.allow_reuse_address = True
|
| 494 |
-
log(f"Web interface running on port {port}...")
|
| 495 |
-
httpd.serve_forever()
|
| 496 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
if __name__ == "__main__":
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
# Start the mirroring process in a background daemon thread
|
| 502 |
-
threading.Thread(target=run_mirror, daemon=True).start()
|
| 503 |
-
|
| 504 |
-
# Start the HTTP server to serve the HTML/CSS UI (blocks main thread)
|
| 505 |
-
start_web_server()
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
+
import time
|
| 4 |
import threading
|
|
|
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
+
from urllib.parse import urljoin, unquote
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from bs4 import BeautifulSoup
|
| 8 |
import requests
|
| 9 |
from requests.adapters import HTTPAdapter
|
| 10 |
from urllib3.util.retry import Retry
|
| 11 |
+
from huggingface_hub import HfApi, login, hf_hub_download, CommitOperationAdd
|
| 12 |
+
from huggingface_hub.utils import EntryNotFoundError
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
# Torpy imports
|
| 16 |
+
from torpy import TorClient
|
| 17 |
+
from torpy.http.requests import tor_requests_session
|
| 18 |
+
|
| 19 |
+
import gradio as gr
|
| 20 |
+
|
| 21 |
+
# ==========================================
|
| 22 |
+
# CONFIGURATION (from environment / secrets)
|
| 23 |
+
# ==========================================
|
| 24 |
+
ONION_URL = os.environ.get("ONION_URL", "http://6qqz6m3b6htudohg2mlf5gdcalonxy3sh5g4dix4mpyirjcgelqqufad.onion/bankofbaroda.bank.in/")
|
| 25 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 26 |
+
HF_REPO_ID = os.environ.get("HF_REPO_ID", "Nzvyu/Dark")
|
| 27 |
+
HF_REPO_TYPE = "dataset"
|
| 28 |
+
LOCAL_TEMP_DIR = Path("./hf_mirror_temp")
|
| 29 |
+
LOG_FILENAME = "transfer_log.json"
|
| 30 |
|
| 31 |
+
BATCH_SIZE_MB = 100
|
| 32 |
+
MAX_COMMITS_PER_HOUR = 124
|
| 33 |
+
|
| 34 |
+
# ==========================================
|
| 35 |
+
# GLOBAL STATE FOR UI
|
| 36 |
+
# ==========================================
|
| 37 |
+
mirror_status = {
|
| 38 |
+
"running": False,
|
| 39 |
+
"finished": False,
|
| 40 |
+
"current_file": "",
|
| 41 |
+
"files_completed": 0,
|
| 42 |
+
"total_files": 0,
|
| 43 |
+
"batch_size_mb": 0.0,
|
| 44 |
+
"logs": [],
|
| 45 |
+
"error": None
|
| 46 |
}
|
| 47 |
|
| 48 |
+
# ==========================================
|
| 49 |
+
# AUTHENTICATE HUGGING FACE
|
| 50 |
+
# ==========================================
|
| 51 |
+
if HF_TOKEN:
|
| 52 |
+
login(token=HF_TOKEN)
|
| 53 |
+
api = HfApi()
|
| 54 |
+
|
| 55 |
+
# ==========================================
|
| 56 |
+
# TOR SESSION USING TORPY
|
| 57 |
+
# ==========================================
|
| 58 |
+
def create_tor_session():
|
| 59 |
+
"""Create a requests session routed through Tor using torpy."""
|
| 60 |
+
session = tor_requests_session()
|
| 61 |
+
retries = Retry(total=5, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
|
| 62 |
+
adapter = HTTPAdapter(max_retries=retries)
|
| 63 |
+
session.mount("http://", adapter)
|
| 64 |
+
session.mount("https://", adapter)
|
| 65 |
+
return session
|
| 66 |
+
|
| 67 |
+
session = create_tor_session()
|
| 68 |
|
| 69 |
def verify_tor():
|
| 70 |
+
"""Quick check that Tor is working."""
|
| 71 |
try:
|
| 72 |
+
res = session.get("http://httpbin.org/ip", timeout=60)
|
| 73 |
+
ip = res.json()["origin"]
|
| 74 |
+
print(f"Tor Active! Routed IP: {ip}\n", flush=True)
|
| 75 |
+
mirror_status["logs"].append(f"Tor Active! Routed IP: {ip}")
|
| 76 |
return True
|
| 77 |
except Exception as e:
|
| 78 |
+
mirror_status["error"] = f"Tor proxy connection failed: {e}"
|
| 79 |
+
mirror_status["logs"].append(f"[FATAL] Tor proxy connection failed: {e}")
|
| 80 |
return False
|
| 81 |
|
| 82 |
+
# ==========================================
|
| 83 |
+
# RESUME LOG HANDLING
|
| 84 |
+
# ==========================================
|
| 85 |
+
def fetch_remote_log():
|
| 86 |
+
"""Fetch state file from Hugging Face, initialises commit_times for rate limiting."""
|
| 87 |
+
mirror_status["logs"].append("Fetching resume state from Hugging Face...")
|
| 88 |
+
default_log = {"completed_files": [], "commit_times": []}
|
| 89 |
+
try:
|
| 90 |
+
log_path = hf_hub_download(
|
| 91 |
+
repo_id=HF_REPO_ID,
|
| 92 |
+
repo_type=HF_REPO_TYPE,
|
| 93 |
+
filename=LOG_FILENAME,
|
| 94 |
+
force_download=True
|
| 95 |
+
)
|
| 96 |
+
with open(log_path, "r") as f:
|
| 97 |
+
data = json.load(f)
|
| 98 |
+
if "commit_times" not in data:
|
| 99 |
+
data["commit_times"] = []
|
| 100 |
+
return data
|
| 101 |
+
except EntryNotFoundError:
|
| 102 |
+
mirror_status["logs"].append("No remote log found. Starting fresh.")
|
| 103 |
+
return default_log
|
| 104 |
+
except Exception as e:
|
| 105 |
+
mirror_status["logs"].append(f"Warning: Failed to fetch remote log ({e}). Starting fresh.")
|
| 106 |
+
return default_log
|
| 107 |
|
| 108 |
+
def check_rate_limit(log_data):
|
| 109 |
+
"""Enforce max commits per hour by sleeping if limit reached."""
|
| 110 |
now = time.time()
|
| 111 |
+
log_data["commit_times"] = [t for t in log_data.get("commit_times", []) if now - t < 3600]
|
| 112 |
+
if len(log_data["commit_times"]) >= MAX_COMMITS_PER_HOUR:
|
| 113 |
+
oldest_commit = log_data["commit_times"][0]
|
| 114 |
+
sleep_time = 3600 - (now - oldest_commit) + 15
|
| 115 |
if sleep_time > 0:
|
| 116 |
+
mirror_status["logs"].append(f"\n[Rate Limit] 124 commits reached. Sleeping for {sleep_time/60:.2f} minutes...")
|
| 117 |
time.sleep(sleep_time)
|
| 118 |
now = time.time()
|
| 119 |
+
log_data["commit_times"] = [t for t in log_data["commit_times"] if now - t < 3600]
|
| 120 |
|
| 121 |
+
def upload_batch(batch_files, log_data):
|
| 122 |
+
"""Upload accumulated files and updated log as a single commit."""
|
| 123 |
if not batch_files:
|
| 124 |
return
|
| 125 |
+
|
| 126 |
+
check_rate_limit(log_data)
|
| 127 |
+
|
| 128 |
+
mirror_status["logs"].append(f"\nCommitting batch of {len(batch_files)} files...")
|
| 129 |
+
|
| 130 |
+
new_rel_paths = [rel_path for rel_path, _ in batch_files]
|
| 131 |
+
log_data["completed_files"].extend(new_rel_paths)
|
| 132 |
+
|
| 133 |
+
temp_log = LOCAL_TEMP_DIR / LOG_FILENAME
|
| 134 |
+
with open(temp_log, "w") as f:
|
| 135 |
+
json.dump(log_data, f, indent=2)
|
| 136 |
+
|
| 137 |
operations = []
|
| 138 |
for rel_path, local_path in batch_files:
|
| 139 |
operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
|
| 140 |
+
operations.append(CommitOperationAdd(path_in_repo=LOG_FILENAME, path_or_fileobj=str(temp_log)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
api.create_commit(
|
| 143 |
+
repo_id=HF_REPO_ID,
|
| 144 |
+
repo_type=HF_REPO_TYPE,
|
| 145 |
+
operations=operations,
|
| 146 |
+
commit_message=f"Sync: {len(batch_files)} files (Batch Upload)"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
log_data["commit_times"].append(time.time())
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
+
for _, local_path in batch_files:
|
| 152 |
+
if local_path.exists():
|
| 153 |
+
local_path.unlink()
|
| 154 |
+
if temp_log.exists():
|
| 155 |
+
temp_log.unlink()
|
| 156 |
+
|
| 157 |
+
mirror_status["logs"].append("Batch upload successful!")
|
| 158 |
+
|
| 159 |
+
# ==========================================
|
| 160 |
+
# CRAWLER
|
| 161 |
+
# ==========================================
|
| 162 |
+
def crawl_onion_directory(url, rel_path=""):
|
| 163 |
+
"""Recursively crawl directories on the onion site."""
|
| 164 |
try:
|
| 165 |
+
r = session.get(url, timeout=120)
|
| 166 |
r.raise_for_status()
|
| 167 |
except Exception as e:
|
| 168 |
+
mirror_status["logs"].append(f"Failed to access {url}: {e}")
|
| 169 |
return
|
| 170 |
|
| 171 |
+
soup = BeautifulSoup(r.text, 'html.parser')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
for link in soup.find_all('a'):
|
| 173 |
href = link.get('href')
|
| 174 |
+
|
| 175 |
if not href or href.startswith('?') or href == '../' or href.startswith('/'):
|
| 176 |
continue
|
| 177 |
+
|
| 178 |
clean_name = unquote(href)
|
| 179 |
full_url = urljoin(url, href)
|
| 180 |
+
new_rel_path = os.path.join(rel_path, clean_name)
|
| 181 |
+
|
| 182 |
if href.endswith('/'):
|
| 183 |
+
yield from crawl_onion_directory(full_url, new_rel_path)
|
| 184 |
else:
|
|
|
|
|
|
|
| 185 |
yield (full_url, new_rel_path)
|
| 186 |
+
|
| 187 |
+
# ==========================================
|
| 188 |
+
# MAIN MIRRORING FUNCTION (runs in background thread)
|
| 189 |
+
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
def run_mirror():
|
| 191 |
+
mirror_status["running"] = True
|
| 192 |
+
mirror_status["finished"] = False
|
| 193 |
+
mirror_status["error"] = None
|
| 194 |
+
|
| 195 |
+
if not verify_tor():
|
| 196 |
+
mirror_status["running"] = False
|
|
|
|
|
|
|
| 197 |
return
|
| 198 |
+
|
|
|
|
| 199 |
LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 200 |
+
|
| 201 |
+
log_data = fetch_remote_log()
|
| 202 |
+
mirror_status["files_completed"] = len(log_data["completed_files"])
|
| 203 |
+
mirror_status["logs"].append(f"Resuming with {mirror_status['files_completed']} previously completed files.")
|
| 204 |
+
mirror_status["logs"].append(f"Starting crawler at: {ONION_URL}\n")
|
| 205 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
batch_files = []
|
| 207 |
batch_size = 0
|
| 208 |
target_bytes = BATCH_SIZE_MB * 1024 * 1024
|
| 209 |
+
|
| 210 |
+
try:
|
| 211 |
+
for file_url, rel_path in crawl_onion_directory(ONION_URL):
|
| 212 |
+
if rel_path in log_data["completed_files"]:
|
| 213 |
+
continue
|
| 214 |
+
|
| 215 |
+
local_path = LOCAL_TEMP_DIR / rel_path
|
| 216 |
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 217 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
try:
|
| 219 |
+
mirror_status["current_file"] = rel_path
|
| 220 |
+
mirror_status["logs"].append(f"Downloading: {rel_path}")
|
| 221 |
+
|
| 222 |
+
with session.get(file_url, stream=True, timeout=300) as r:
|
| 223 |
+
r.raise_for_status()
|
| 224 |
+
total_size = int(r.headers.get('content-length', 0))
|
| 225 |
+
|
| 226 |
+
with open(local_path, 'wb') as f, tqdm(
|
| 227 |
+
desc=rel_path[-30:],
|
| 228 |
+
total=total_size,
|
| 229 |
+
unit='B',
|
| 230 |
+
unit_scale=True,
|
| 231 |
+
unit_divisor=1024,
|
| 232 |
+
leave=False
|
| 233 |
+
) as bar:
|
| 234 |
+
for chunk in r.iter_content(chunk_size=1024 * 1024):
|
| 235 |
+
if chunk:
|
| 236 |
+
f.write(chunk)
|
| 237 |
+
bar.update(len(chunk))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
file_size = local_path.stat().st_size
|
| 240 |
+
batch_size += file_size
|
| 241 |
+
batch_files.append((rel_path, local_path))
|
| 242 |
+
mirror_status["batch_size_mb"] = batch_size / (1024 * 1024)
|
| 243 |
+
mirror_status["logs"].append(f"Downloaded: {rel_path} | Batch: {mirror_status['batch_size_mb']:.1f} MB / {BATCH_SIZE_MB} MB")
|
| 244 |
+
|
| 245 |
+
if batch_size >= target_bytes:
|
| 246 |
+
upload_batch(batch_files, log_data)
|
| 247 |
+
batch_files = []
|
| 248 |
+
batch_size = 0
|
| 249 |
+
mirror_status["files_completed"] = len(log_data["completed_files"])
|
| 250 |
+
|
| 251 |
+
except Exception as e:
|
| 252 |
+
mirror_status["logs"].append(f"\n[Error] Download failed for {rel_path}: {e}")
|
| 253 |
+
if local_path.exists():
|
| 254 |
+
local_path.unlink()
|
| 255 |
+
|
| 256 |
+
if batch_files:
|
| 257 |
+
upload_batch(batch_files, log_data)
|
| 258 |
+
mirror_status["files_completed"] = len(log_data["completed_files"])
|
| 259 |
+
|
| 260 |
+
mirror_status["logs"].append("\nMIRRORING COMPLETELY FINISHED!")
|
| 261 |
+
|
| 262 |
+
except Exception as e:
|
| 263 |
+
mirror_status["error"] = f"Mirroring failed: {e}"
|
| 264 |
+
mirror_status["logs"].append(f"[FATAL] {e}")
|
| 265 |
+
finally:
|
| 266 |
+
mirror_status["running"] = False
|
| 267 |
+
mirror_status["finished"] = True
|
| 268 |
+
mirror_status["current_file"] = ""
|
| 269 |
+
|
| 270 |
+
# ==========================================
|
| 271 |
+
# DUMMY FUNCTION (for demonstration)
|
| 272 |
+
# ==========================================
|
| 273 |
+
def dummy_function(input_text: str) -> str:
|
| 274 |
+
"""A dummy function that echoes input, to show UI interactivity."""
|
| 275 |
+
return f"Dummy says: {input_text}"
|
| 276 |
+
|
| 277 |
+
# ==========================================
|
| 278 |
+
# GRADIO UI
|
| 279 |
+
# ==========================================
|
| 280 |
+
def update_ui():
|
| 281 |
+
"""Return current status for UI components."""
|
| 282 |
+
logs = "\n".join(mirror_status["logs"][-50:]) # show last 50 lines
|
| 283 |
+
status_text = f"""
|
| 284 |
+
**Status:** {'๐ข Running' if mirror_status['running'] else '๐ด Stopped'}
|
| 285 |
+
**Current File:** {mirror_status['current_file'] or 'N/A'}
|
| 286 |
+
**Files Completed:** {mirror_status['files_completed']}
|
| 287 |
+
**Batch Size:** {mirror_status['batch_size_mb']:.1f} MB / {BATCH_SIZE_MB} MB
|
| 288 |
+
**Error:** {mirror_status['error'] or 'None'}
|
| 289 |
+
"""
|
| 290 |
+
return status_text, logs
|
| 291 |
+
|
| 292 |
+
with gr.Blocks(css="""
|
| 293 |
+
.gradio-container {max-width: 900px; margin: auto;}
|
| 294 |
+
.status-box {border: 1px solid #ccc; border-radius: 8px; padding: 15px; background: #f9f9f9;}
|
| 295 |
+
.log-box {height: 400px; overflow-y: auto; font-family: monospace;}
|
| 296 |
+
""") as demo:
|
| 297 |
+
gr.HTML("""
|
| 298 |
+
<div style="text-align: center; margin-bottom: 20px;">
|
| 299 |
+
<h1>๐ Onion Mirror to Hugging Face</h1>
|
| 300 |
+
<p>Automatically mirrors an onion directory to a Hugging Face dataset.</p>
|
| 301 |
+
</div>
|
| 302 |
+
""")
|
| 303 |
+
with gr.Row():
|
| 304 |
+
with gr.Column(scale=1):
|
| 305 |
+
status_md = gr.Markdown("**Starting...**", elem_classes="status-box")
|
| 306 |
+
with gr.Column(scale=2):
|
| 307 |
+
logs_box = gr.Textbox(label="Live Logs", lines=20, max_lines=20, interactive=False, elem_classes="log-box")
|
| 308 |
+
|
| 309 |
+
# Dummy function demo
|
| 310 |
+
with gr.Row():
|
| 311 |
+
dummy_input = gr.Textbox(label="Dummy Input", placeholder="Type something...")
|
| 312 |
+
dummy_output = gr.Textbox(label="Dummy Output", interactive=False)
|
| 313 |
+
dummy_btn = gr.Button("Run Dummy")
|
| 314 |
+
dummy_btn.click(fn=dummy_function, inputs=dummy_input, outputs=dummy_output)
|
| 315 |
+
|
| 316 |
+
# Refresh status every 2 seconds
|
| 317 |
+
demo.load(fn=update_ui, outputs=[status_md, logs_box], every=2)
|
| 318 |
+
|
| 319 |
+
# ==========================================
|
| 320 |
+
# START MIRRORING THREAD ON APP START
|
| 321 |
+
# ==========================================
|
| 322 |
if __name__ == "__main__":
|
| 323 |
+
mirror_thread = threading.Thread(target=run_mirror, daemon=True)
|
| 324 |
+
mirror_thread.start()
|
| 325 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|