Update app.py
Browse files
app.py
CHANGED
|
@@ -51,7 +51,6 @@ HF_REPO_TYPE = "dataset"
|
|
| 51 |
|
| 52 |
LOCAL_TEMP_DIR = Path("./hf_mirror_temp")
|
| 53 |
LOG_FILE = "mirror_activity.log"
|
| 54 |
-
|
| 55 |
BATCH_SIZE_MB = 100
|
| 56 |
MAX_COMMITS_PER_HOUR = 124
|
| 57 |
DOWNLOAD_WORKERS = 4
|
|
@@ -61,11 +60,21 @@ TOR_SOCKS_PORT = 9050
|
|
| 61 |
with open(LOG_FILE, "w") as f:
|
| 62 |
f.write("System initialized. Starting background mirror...\n")
|
| 63 |
|
| 64 |
-
def log(msg):
|
| 65 |
-
"""Write logs to
|
|
|
|
| 66 |
print(msg, flush=True)
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
|
| 71 |
log("β οΈ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
|
|
@@ -77,10 +86,12 @@ def start_tor():
|
|
| 77 |
tor_dir = Path("/tmp/tor-data")
|
| 78 |
tor_dir.mkdir(exist_ok=True)
|
| 79 |
torrc = tor_dir / "torrc"
|
|
|
|
| 80 |
torrc.write_text(f"""SocksPort {TOR_SOCKS_PORT}
|
| 81 |
DataDirectory {tor_dir}
|
| 82 |
Log notice file {tor_dir}/tor.log
|
| 83 |
-
RunAsDaemon 1
|
|
|
|
| 84 |
|
| 85 |
log("Starting Tor proxy in the background...")
|
| 86 |
subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
|
|
@@ -95,6 +106,7 @@ RunAsDaemon 1""")
|
|
| 95 |
log("β
Tor SOCKS proxy is ready.")
|
| 96 |
return
|
| 97 |
time.sleep(1)
|
|
|
|
| 98 |
raise RuntimeError("β Tor failed to start.")
|
| 99 |
|
| 100 |
# ----------------------------------------------------------------------
|
|
@@ -108,9 +120,10 @@ from huggingface_hub import HfApi, login, CommitOperationAdd
|
|
| 108 |
|
| 109 |
session = requests.Session()
|
| 110 |
session.proxies = {
|
| 111 |
-
'http':
|
| 112 |
'https': f'socks5h://127.0.0.1:{TOR_SOCKS_PORT}'
|
| 113 |
}
|
|
|
|
| 114 |
retries = Retry(total=10, backoff_factor=2, status_forcelist=[500, 502, 503, 504])
|
| 115 |
session.mount("http://", HTTPAdapter(max_retries=retries))
|
| 116 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
|
@@ -174,10 +187,11 @@ def upload_batch(batch_files):
|
|
| 174 |
return
|
| 175 |
check_rate_limit()
|
| 176 |
log(f"Committing {len(batch_files)} files to Hugging Face...")
|
|
|
|
| 177 |
operations = []
|
| 178 |
for rel_path, local_path in batch_files:
|
| 179 |
operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
|
| 180 |
-
|
| 181 |
try:
|
| 182 |
api.create_commit(
|
| 183 |
repo_id=HF_REPO_ID,
|
|
@@ -196,6 +210,7 @@ def upload_batch(batch_files):
|
|
| 196 |
def download_with_aria2(url, dest_path):
|
| 197 |
dest_path = Path(dest_path)
|
| 198 |
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 199 |
cmd = [
|
| 200 |
"aria2c",
|
| 201 |
f"--all-proxy=socks5h://127.0.0.1:{TOR_SOCKS_PORT}",
|
|
@@ -209,6 +224,7 @@ def download_with_aria2(url, dest_path):
|
|
| 209 |
f"--out={dest_path.name}",
|
| 210 |
url
|
| 211 |
]
|
|
|
|
| 212 |
try:
|
| 213 |
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
|
| 214 |
if result.returncode == 0:
|
|
@@ -224,21 +240,28 @@ def download_with_aria2(url, dest_path):
|
|
| 224 |
return False
|
| 225 |
|
| 226 |
def crawl_onion_directory(url, rel_path=""):
|
|
|
|
|
|
|
|
|
|
| 227 |
try:
|
| 228 |
r = session.get(url, timeout=90)
|
| 229 |
r.raise_for_status()
|
| 230 |
except Exception as e:
|
| 231 |
log(f"Failed to access {url}: {e}")
|
| 232 |
return
|
| 233 |
-
|
| 234 |
soup = BeautifulSoup(r.text, 'html.parser')
|
| 235 |
for link in soup.find_all('a'):
|
| 236 |
href = link.get('href')
|
|
|
|
| 237 |
if not href or href.startswith('?') or href == '../' or href.startswith('/'):
|
| 238 |
continue
|
|
|
|
| 239 |
clean_name = unquote(href)
|
| 240 |
full_url = urljoin(url, href)
|
| 241 |
-
|
|
|
|
|
|
|
| 242 |
|
| 243 |
if href.endswith('/'):
|
| 244 |
yield from crawl_onion_directory(full_url, new_rel_path)
|
|
@@ -257,23 +280,28 @@ def run_mirror():
|
|
| 257 |
except Exception as e:
|
| 258 |
log(f"β Initialization failed: {e}")
|
| 259 |
return
|
| 260 |
-
|
| 261 |
verify_tor()
|
| 262 |
LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 263 |
-
completed_files = get_remote_files()
|
| 264 |
|
|
|
|
| 265 |
log(f"Resuming: {len(completed_files)} files already present.")
|
| 266 |
log(f"Starting crawler at: {ONION_URL}")
|
| 267 |
|
| 268 |
batch_files = []
|
| 269 |
batch_size = 0
|
| 270 |
target_bytes = BATCH_SIZE_MB * 1024 * 1024
|
|
|
|
| 271 |
|
| 272 |
executor = ThreadPoolExecutor(max_workers=DOWNLOAD_WORKERS)
|
| 273 |
pending_futures = []
|
| 274 |
-
|
| 275 |
for file_url, rel_path in crawl_onion_directory(ONION_URL):
|
| 276 |
if rel_path in completed_files:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
continue
|
| 278 |
|
| 279 |
local_path = LOCAL_TEMP_DIR / rel_path
|
|
@@ -297,6 +325,7 @@ def run_mirror():
|
|
| 297 |
batch_files = []
|
| 298 |
batch_size = 0
|
| 299 |
|
|
|
|
| 300 |
for fut, rel, lpath in pending_futures:
|
| 301 |
success = fut.result()
|
| 302 |
if success and lpath.exists():
|
|
@@ -310,12 +339,10 @@ def run_mirror():
|
|
| 310 |
executor.shutdown(wait=True)
|
| 311 |
log("β
MIRRORING COMPLETED SUCCESSFULLY!")
|
| 312 |
|
| 313 |
-
|
| 314 |
# ----------------------------------------------------------------------
|
| 315 |
# 9. PURE HTML/CSS WEB SERVER
|
| 316 |
# ----------------------------------------------------------------------
|
| 317 |
-
HTML_PAGE = """
|
| 318 |
-
<!DOCTYPE html>
|
| 319 |
<html lang="en">
|
| 320 |
<head>
|
| 321 |
<meta charset="UTF-8">
|
|
@@ -371,14 +398,13 @@ HTML_PAGE = """
|
|
| 371 |
fetchLogs();
|
| 372 |
</script>
|
| 373 |
</body>
|
| 374 |
-
</html>
|
| 375 |
-
"""
|
| 376 |
|
| 377 |
class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
| 378 |
def do_GET(self):
|
| 379 |
# Ignore query parameters like ?__theme=dark
|
| 380 |
parsed_path = urlparse(self.path).path
|
| 381 |
-
|
| 382 |
if parsed_path == "/" or parsed_path == "/index.html":
|
| 383 |
html = HTML_PAGE.encode("utf-8")
|
| 384 |
self.send_response(200)
|
|
@@ -386,7 +412,7 @@ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
|
| 386 |
self.send_header("Content-Length", str(len(html)))
|
| 387 |
self.end_headers()
|
| 388 |
self.wfile.write(html)
|
| 389 |
-
|
| 390 |
elif parsed_path == "/api/logs":
|
| 391 |
try:
|
| 392 |
with open(LOG_FILE, "r") as f:
|
|
@@ -394,14 +420,14 @@ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
|
| 394 |
logs_str = "".join(lines)
|
| 395 |
except Exception:
|
| 396 |
logs_str = "Loading logs..."
|
| 397 |
-
|
| 398 |
body = json.dumps({"logs": logs_str}).encode("utf-8")
|
| 399 |
self.send_response(200)
|
| 400 |
self.send_header("Content-type", "application/json")
|
| 401 |
self.send_header("Content-Length", str(len(body)))
|
| 402 |
self.end_headers()
|
| 403 |
self.wfile.write(body)
|
| 404 |
-
|
| 405 |
else:
|
| 406 |
self.send_response(404)
|
| 407 |
self.end_headers()
|
|
|
|
| 51 |
|
| 52 |
LOCAL_TEMP_DIR = Path("./hf_mirror_temp")
|
| 53 |
LOG_FILE = "mirror_activity.log"
|
|
|
|
| 54 |
BATCH_SIZE_MB = 100
|
| 55 |
MAX_COMMITS_PER_HOUR = 124
|
| 56 |
DOWNLOAD_WORKERS = 4
|
|
|
|
| 60 |
with open(LOG_FILE, "w") as f:
|
| 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 |
|
| 79 |
if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
|
| 80 |
log("β οΈ Missing secrets! Set HF_TOKEN, HF_REPO_ID, ONION_URL in Space Secrets.")
|
|
|
|
| 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)
|
|
|
|
| 106 |
log("β
Tor SOCKS proxy is ready.")
|
| 107 |
return
|
| 108 |
time.sleep(1)
|
| 109 |
+
|
| 110 |
raise RuntimeError("β Tor failed to start.")
|
| 111 |
|
| 112 |
# ----------------------------------------------------------------------
|
|
|
|
| 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))
|
|
|
|
| 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,
|
|
|
|
| 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}",
|
|
|
|
| 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:
|
|
|
|
| 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)
|
|
|
|
| 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
|
|
|
|
| 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():
|
|
|
|
| 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">
|
| 347 |
<head>
|
| 348 |
<meta charset="UTF-8">
|
|
|
|
| 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)
|
|
|
|
| 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:
|
|
|
|
| 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()
|