Update app.py
Browse files
app.py
CHANGED
|
@@ -49,26 +49,38 @@ 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 |
-
|
|
|
|
| 54 |
|
| 55 |
BATCH_SIZE_MB = 100
|
| 56 |
MAX_COMMITS_PER_HOUR = 124
|
| 57 |
DOWNLOAD_WORKERS = 4
|
| 58 |
TOR_SOCKS_PORT = 9050
|
| 59 |
|
| 60 |
-
# Reset
|
| 61 |
with open(LOG_FILE, "w") as f:
|
| 62 |
-
f.write("System
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
print(msg, flush=True)
|
| 67 |
with open(LOG_FILE, "a") as f:
|
| 68 |
f.write(msg + "\n")
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
if not HF_TOKEN or not HF_REPO_ID or not ONION_URL:
|
| 71 |
-
|
|
|
|
| 72 |
|
| 73 |
# ----------------------------------------------------------------------
|
| 74 |
# 4. START TOR MANUALLY
|
|
@@ -82,7 +94,7 @@ DataDirectory {tor_dir}
|
|
| 82 |
Log notice file {tor_dir}/tor.log
|
| 83 |
RunAsDaemon 1""")
|
| 84 |
|
| 85 |
-
|
| 86 |
subprocess.run(["tor", "-f", str(torrc)], capture_output=True, text=True)
|
| 87 |
|
| 88 |
import socket
|
|
@@ -92,7 +104,8 @@ RunAsDaemon 1""")
|
|
| 92 |
result = sock.connect_ex(("127.0.0.1", TOR_SOCKS_PORT))
|
| 93 |
sock.close()
|
| 94 |
if result == 0:
|
| 95 |
-
|
|
|
|
| 96 |
return
|
| 97 |
time.sleep(1)
|
| 98 |
raise RuntimeError("❌ Tor failed to start.")
|
|
@@ -116,14 +129,16 @@ session.mount("http://", HTTPAdapter(max_retries=retries))
|
|
| 116 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
| 117 |
|
| 118 |
def verify_tor():
|
| 119 |
-
|
| 120 |
try:
|
| 121 |
res = session.get("http://httpbin.org/ip", timeout=10)
|
| 122 |
res.raise_for_status()
|
| 123 |
-
|
|
|
|
| 124 |
return True
|
| 125 |
except Exception as e:
|
| 126 |
-
|
|
|
|
| 127 |
return False
|
| 128 |
|
| 129 |
# ----------------------------------------------------------------------
|
|
@@ -143,22 +158,21 @@ def authenticate_hf():
|
|
| 143 |
# ----------------------------------------------------------------------
|
| 144 |
def download_progress_from_hf():
|
| 145 |
"""Try to download the progress file from the dataset. Returns set of completed rel paths."""
|
| 146 |
-
|
| 147 |
try:
|
| 148 |
-
# Use requests to fetch the raw file
|
| 149 |
url = f"https://huggingface.co/datasets/{HF_REPO_ID}/resolve/main/{PROGRESS_FILE}"
|
| 150 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 151 |
r = requests.get(url, headers=headers, timeout=30)
|
| 152 |
if r.status_code == 200:
|
| 153 |
data = json.loads(r.text)
|
| 154 |
completed = set(data.get("completed_files", []))
|
| 155 |
-
|
| 156 |
return completed
|
| 157 |
else:
|
| 158 |
-
|
| 159 |
return set()
|
| 160 |
except Exception as e:
|
| 161 |
-
|
| 162 |
return set()
|
| 163 |
|
| 164 |
def save_progress_local(completed_set):
|
|
@@ -182,7 +196,7 @@ def check_rate_limit():
|
|
| 182 |
oldest = commit_times[0]
|
| 183 |
sleep_time = 3600 - (now - oldest) + 15
|
| 184 |
if sleep_time > 0:
|
| 185 |
-
|
| 186 |
time.sleep(sleep_time)
|
| 187 |
now = time.time()
|
| 188 |
commit_times = [t for t in commit_times if now - t < 3600]
|
|
@@ -192,9 +206,9 @@ def upload_batch(batch_files, completed_set):
|
|
| 192 |
if not batch_files:
|
| 193 |
return
|
| 194 |
check_rate_limit()
|
| 195 |
-
|
| 196 |
|
| 197 |
-
# Update
|
| 198 |
for rel_path, _ in batch_files:
|
| 199 |
completed_set.add(rel_path)
|
| 200 |
progress_path = save_progress_local(completed_set)
|
|
@@ -202,7 +216,6 @@ def upload_batch(batch_files, completed_set):
|
|
| 202 |
operations = []
|
| 203 |
for rel_path, local_path in batch_files:
|
| 204 |
operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
|
| 205 |
-
# Include the progress file in the same commit
|
| 206 |
operations.append(CommitOperationAdd(path_in_repo=PROGRESS_FILE, path_or_fileobj=str(progress_path)))
|
| 207 |
|
| 208 |
try:
|
|
@@ -213,13 +226,12 @@ def upload_batch(batch_files, completed_set):
|
|
| 213 |
commit_message=f"Sync: {len(batch_files)} files + progress update"
|
| 214 |
)
|
| 215 |
commit_times.append(time.time())
|
| 216 |
-
# Delete the local batch files after successful upload
|
| 217 |
for _, local_path in batch_files:
|
| 218 |
if local_path.exists():
|
| 219 |
local_path.unlink()
|
| 220 |
-
|
| 221 |
except Exception as e:
|
| 222 |
-
|
| 223 |
|
| 224 |
def download_with_aria2(url, dest_path):
|
| 225 |
dest_path = Path(dest_path)
|
|
@@ -242,13 +254,13 @@ def download_with_aria2(url, dest_path):
|
|
| 242 |
if result.returncode == 0:
|
| 243 |
return True
|
| 244 |
else:
|
| 245 |
-
|
| 246 |
return False
|
| 247 |
except subprocess.TimeoutExpired:
|
| 248 |
-
|
| 249 |
return False
|
| 250 |
except Exception as e:
|
| 251 |
-
|
| 252 |
return False
|
| 253 |
|
| 254 |
def crawl_onion_directory(url, rel_path=""):
|
|
@@ -256,7 +268,7 @@ def crawl_onion_directory(url, rel_path=""):
|
|
| 256 |
r = session.get(url, timeout=90)
|
| 257 |
r.raise_for_status()
|
| 258 |
except Exception as e:
|
| 259 |
-
|
| 260 |
return
|
| 261 |
|
| 262 |
soup = BeautifulSoup(r.text, 'html.parser')
|
|
@@ -278,30 +290,31 @@ def crawl_onion_directory(url, rel_path=""):
|
|
| 278 |
# ----------------------------------------------------------------------
|
| 279 |
def run_mirror():
|
| 280 |
try:
|
| 281 |
-
dummy_gpu()
|
| 282 |
start_tor()
|
| 283 |
authenticate_hf()
|
| 284 |
-
|
| 285 |
except Exception as e:
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
return
|
| 288 |
|
| 289 |
-
verify_tor()
|
| 290 |
LOCAL_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 291 |
|
| 292 |
-
# Load progress from
|
| 293 |
completed_files = download_progress_from_hf()
|
| 294 |
-
# If download failed, try reading local progress file (if exists)
|
| 295 |
if not completed_files:
|
| 296 |
local_progress = LOCAL_TEMP_DIR / PROGRESS_FILE
|
| 297 |
if local_progress.exists():
|
| 298 |
with open(local_progress, "r") as f:
|
| 299 |
data = json.load(f)
|
| 300 |
completed_files = set(data.get("completed_files", []))
|
| 301 |
-
|
| 302 |
|
| 303 |
-
|
| 304 |
-
log(f"Starting crawler at: {ONION_URL}")
|
| 305 |
|
| 306 |
batch_files = []
|
| 307 |
batch_size = 0
|
|
@@ -325,9 +338,9 @@ def run_mirror():
|
|
| 325 |
file_size = lpath.stat().st_size
|
| 326 |
batch_size += file_size
|
| 327 |
batch_files.append((rel, lpath))
|
| 328 |
-
|
| 329 |
else:
|
| 330 |
-
|
| 331 |
pending_futures.clear()
|
| 332 |
|
| 333 |
if batch_size >= target_bytes:
|
|
@@ -335,7 +348,7 @@ def run_mirror():
|
|
| 335 |
batch_files = []
|
| 336 |
batch_size = 0
|
| 337 |
|
| 338 |
-
# Process
|
| 339 |
for fut, rel, lpath in pending_futures:
|
| 340 |
success = fut.result()
|
| 341 |
if success and lpath.exists():
|
|
@@ -343,15 +356,14 @@ def run_mirror():
|
|
| 343 |
batch_size += file_size
|
| 344 |
batch_files.append((rel, lpath))
|
| 345 |
|
| 346 |
-
# Upload any final batch
|
| 347 |
if batch_files:
|
| 348 |
upload_batch(batch_files, completed_files)
|
| 349 |
|
| 350 |
executor.shutdown(wait=True)
|
| 351 |
-
|
| 352 |
|
| 353 |
# ----------------------------------------------------------------------
|
| 354 |
-
# 10. PURE HTML/CSS WEB SERVER (
|
| 355 |
# ----------------------------------------------------------------------
|
| 356 |
HTML_PAGE = """
|
| 357 |
<!DOCTYPE html>
|
|
@@ -382,7 +394,7 @@ HTML_PAGE = """
|
|
| 382 |
|
| 383 |
<div class="log-container">
|
| 384 |
<div class="log-header">Live Activity Logs:</div>
|
| 385 |
-
<div class="log-box" id="log-box">
|
| 386 |
</div>
|
| 387 |
</div>
|
| 388 |
<script>
|
|
@@ -423,7 +435,7 @@ class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
|
| 423 |
|
| 424 |
elif parsed_path == "/api/logs":
|
| 425 |
try:
|
| 426 |
-
with open(
|
| 427 |
lines = f.readlines()[-200:]
|
| 428 |
logs_str = "".join(lines)
|
| 429 |
except Exception:
|
|
@@ -448,7 +460,7 @@ def start_web_server():
|
|
| 448 |
handler = CustomHTTPRequestHandler
|
| 449 |
httpd = http.server.ThreadingHTTPServer(("0.0.0.0", port), handler)
|
| 450 |
httpd.allow_reuse_address = True
|
| 451 |
-
|
| 452 |
httpd.serve_forever()
|
| 453 |
|
| 454 |
if __name__ == "__main__":
|
|
|
|
| 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
|
|
|
|
| 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
|
|
|
|
| 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.")
|
|
|
|
| 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 |
# ----------------------------------------------------------------------
|
|
|
|
| 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}"
|
| 164 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 165 |
r = requests.get(url, headers=headers, timeout=30)
|
| 166 |
if r.status_code == 200:
|
| 167 |
data = json.loads(r.text)
|
| 168 |
completed = set(data.get("completed_files", []))
|
| 169 |
+
log_mirror(f"Resuming from {len(completed)} files.")
|
| 170 |
return completed
|
| 171 |
else:
|
| 172 |
+
log_mirror("No previous progress found. Starting fresh.")
|
| 173 |
return set()
|
| 174 |
except Exception as e:
|
| 175 |
+
log_mirror(f"Could not fetch progress: {e}. Starting fresh.")
|
| 176 |
return set()
|
| 177 |
|
| 178 |
def save_progress_local(completed_set):
|
|
|
|
| 196 |
oldest = commit_times[0]
|
| 197 |
sleep_time = 3600 - (now - oldest) + 15
|
| 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]
|
|
|
|
| 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)
|
|
|
|
| 216 |
operations = []
|
| 217 |
for rel_path, local_path in batch_files:
|
| 218 |
operations.append(CommitOperationAdd(path_in_repo=rel_path, path_or_fileobj=str(local_path)))
|
|
|
|
| 219 |
operations.append(CommitOperationAdd(path_in_repo=PROGRESS_FILE, path_or_fileobj=str(progress_path)))
|
| 220 |
|
| 221 |
try:
|
|
|
|
| 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:
|
| 230 |
if local_path.exists():
|
| 231 |
local_path.unlink()
|
| 232 |
+
log_mirror("✅ Batch upload successful.")
|
| 233 |
except Exception as e:
|
| 234 |
+
log_mirror(f"❌ Upload failed: {e}")
|
| 235 |
|
| 236 |
def download_with_aria2(url, dest_path):
|
| 237 |
dest_path = Path(dest_path)
|
|
|
|
| 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=""):
|
|
|
|
| 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')
|
|
|
|
| 290 |
# ----------------------------------------------------------------------
|
| 291 |
def run_mirror():
|
| 292 |
try:
|
| 293 |
+
dummy_gpu()
|
| 294 |
start_tor()
|
| 295 |
authenticate_hf()
|
| 296 |
+
log_mirror("✅ Hugging Face auth successful.")
|
| 297 |
except Exception as e:
|
| 298 |
+
log_mirror(f"❌ Initialization failed: {e}")
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
if not verify_tor():
|
| 302 |
+
log_mirror("❌ Tor verification failed. Exiting mirror.")
|
| 303 |
return
|
| 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
|
| 311 |
if local_progress.exists():
|
| 312 |
with open(local_progress, "r") as f:
|
| 313 |
data = json.load(f)
|
| 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
|
|
|
|
| 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:
|
|
|
|
| 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():
|
|
|
|
| 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>
|
|
|
|
| 394 |
|
| 395 |
<div class="log-container">
|
| 396 |
<div class="log-header">Live Activity Logs:</div>
|
| 397 |
+
<div class="log-box" id="log-box">Waiting for logs...</div>
|
| 398 |
</div>
|
| 399 |
</div>
|
| 400 |
<script>
|
|
|
|
| 435 |
|
| 436 |
elif parsed_path == "/api/logs":
|
| 437 |
try:
|
| 438 |
+
with open(UI_LOG_FILE, "r") as f:
|
| 439 |
lines = f.readlines()[-200:]
|
| 440 |
logs_str = "".join(lines)
|
| 441 |
except Exception:
|
|
|
|
| 460 |
handler = CustomHTTPRequestHandler
|
| 461 |
httpd = http.server.ThreadingHTTPServer(("0.0.0.0", port), handler)
|
| 462 |
httpd.allow_reuse_address = True
|
| 463 |
+
log_system(f"Web interface running on port {port}...")
|
| 464 |
httpd.serve_forever()
|
| 465 |
|
| 466 |
if __name__ == "__main__":
|