wuhp commited on
Commit
abae4cb
·
verified ·
1 Parent(s): dbb4b45

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +521 -0
app.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import io
4
+ import sys
5
+ import json
6
+ import time
7
+ import math
8
+ import hashlib
9
+ import pathlib
10
+ from typing import Dict, Any, List, Tuple, Optional
11
+ from urllib.parse import urlparse, parse_qs, unquote
12
+
13
+ import requests
14
+ import pandas as pd
15
+ import gradio as gr
16
+ import bencodepy
17
+
18
+ # =========================
19
+ # Utilities
20
+ # =========================
21
+
22
+ def human_bytes(n: int) -> str:
23
+ if n is None:
24
+ return "—"
25
+ f = float(n)
26
+ for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]:
27
+ if f < 1024.0:
28
+ return f"{f:.2f} {unit}"
29
+ f /= 1024.0
30
+ return f"{f:.2f} EiB"
31
+
32
+ def is_magnet(s: str) -> bool:
33
+ return s.strip().lower().startswith("magnet:")
34
+
35
+ def is_http_url(s: str) -> bool:
36
+ s = s.strip().lower()
37
+ return s.startswith("http://") or s.startswith("https://")
38
+
39
+ def parse_magnet(magnet: str) -> Dict[str, Any]:
40
+ out: Dict[str, Any] = {"ok": False, "error": None}
41
+ try:
42
+ magnet = magnet.strip()
43
+ if not is_magnet(magnet):
44
+ raise ValueError("Not a magnet URI.")
45
+ parsed = urlparse(magnet)
46
+ qs = parse_qs(parsed.query)
47
+
48
+ xt_vals = qs.get("xt", [])
49
+ ih_hex = None
50
+ if xt_vals:
51
+ for xt in xt_vals:
52
+ if xt.lower().startswith("urn:btih:"):
53
+ ih = xt.split(":", 2)[-1]
54
+ if re.fullmatch(r"[0-9a-fA-F]{40}", ih):
55
+ ih_hex = ih.lower()
56
+ else:
57
+ # base32 → hex
58
+ try:
59
+ import base64
60
+ raw = base64.b32decode(ih.upper())
61
+ ih_hex = raw.hex()
62
+ except Exception:
63
+ pass
64
+ break
65
+
66
+ dn = None
67
+ if "dn" in qs and qs["dn"]:
68
+ dn = unquote(qs["dn"][0])
69
+
70
+ trackers = [unquote(t) for t in qs.get("tr", [])]
71
+ out.update({"ok": True, "infohash_hex": ih_hex, "display_name": dn or "—", "trackers": trackers})
72
+ return out
73
+ except Exception as e:
74
+ out["error"] = f"{type(e).__name__}: {e}"
75
+ return out
76
+
77
+ def fetch_bytes(url: str, timeout: int = 45) -> bytes:
78
+ r = requests.get(url, timeout=timeout)
79
+ r.raise_for_status()
80
+ return r.content
81
+
82
+ def parse_torrent(raw: bytes) -> Dict[str, Any]:
83
+ dec = bencodepy.Bencode(encoding=None)
84
+ data = dec.decode(raw)
85
+ if not isinstance(data, dict) or b"info" not in data:
86
+ raise ValueError("Invalid .torrent: missing 'info' dictionary.")
87
+ info = data[b"info"]
88
+ info_bencoded = bencodepy.encode(info)
89
+ infohash_v1 = hashlib.sha1(info_bencoded).hexdigest()
90
+
91
+ name = info.get(b"name")
92
+ if isinstance(name, (bytes, bytearray)):
93
+ name = name.decode("utf-8", errors="replace")
94
+
95
+ piece_length = info.get(b"piece length")
96
+ pieces = info.get(b"pieces")
97
+ num_pieces = (len(pieces) // 20) if isinstance(pieces, (bytes, bytearray)) else "—"
98
+
99
+ announce = data.get(b"announce")
100
+ if isinstance(announce, (bytes, bytearray)):
101
+ announce = announce.decode("utf-8", errors="replace")
102
+
103
+ announce_list = []
104
+ if b"announce-list" in data and isinstance(data[b"announce-list"], list):
105
+ for tier in data[b"announce-list"]:
106
+ if isinstance(tier, list):
107
+ for tr in tier:
108
+ if isinstance(tr, (bytes, bytearray)):
109
+ announce_list.append(tr.decode("utf-8", errors="replace"))
110
+
111
+ # Web seeds (BEP-19)
112
+ web_seeds: List[str] = []
113
+ if b"url-list" in data:
114
+ url_list = data[b"url-list"]
115
+ if isinstance(url_list, (bytes, bytearray)):
116
+ web_seeds = [url_list.decode("utf-8", errors="replace")]
117
+ elif isinstance(url_list, list):
118
+ for u in url_list:
119
+ if isinstance(u, (bytes, bytearray)):
120
+ web_seeds.append(u.decode("utf-8", errors="replace"))
121
+
122
+ # Files
123
+ rows: List[Dict[str, Any]] = []
124
+ total_len = 0
125
+ if b"files" in info and isinstance(info[b"files"], list):
126
+ for f in info[b"files"]:
127
+ if not isinstance(f, dict):
128
+ continue
129
+ length = int(f.get(b"length", 0))
130
+ total_len += length
131
+ parts = []
132
+ for pe in f.get(b"path", []):
133
+ if isinstance(pe, (bytes, bytearray)):
134
+ parts.append(pe.decode("utf-8", errors="replace"))
135
+ else:
136
+ parts.append(str(pe))
137
+ rel_path = "/".join(parts) if parts else "(unknown)"
138
+ rows.append({"Path": rel_path, "Length (bytes)": length, "Length (HR)": human_bytes(length)})
139
+ else:
140
+ length = int(info.get(b"length", 0))
141
+ total_len = length
142
+ rows.append({"Path": name or "(unnamed)", "Length (bytes)": length, "Length (HR)": human_bytes(length)})
143
+
144
+ df = pd.DataFrame(rows)
145
+ if not df.empty:
146
+ df.sort_values(by=["Path"], inplace=True, ignore_index=True)
147
+
148
+ created_by = data.get(b"created by")
149
+ if isinstance(created_by, (bytes, bytearray)):
150
+ created_by = created_by.decode("utf-8", errors="replace")
151
+ creation_date = data.get(b"creation date")
152
+ creation_date = int(creation_date) if isinstance(creation_date, int) else "—"
153
+ comment = data.get(b"comment")
154
+ if isinstance(comment, (bytes, bytearray)):
155
+ comment = comment.decode("utf-8", errors="replace")
156
+
157
+ summary = {
158
+ "Name": name or "(unknown)",
159
+ "Infohash (v1)": infohash_v1,
160
+ "Total size (bytes)": total_len,
161
+ "Total size": human_bytes(total_len),
162
+ "Files count": int(df.shape[0]),
163
+ "Piece length": piece_length if isinstance(piece_length, int) else "—",
164
+ "Pieces (count)": num_pieces,
165
+ "Primary announce": announce or "—",
166
+ "Trackers": announce_list,
167
+ "Web seeds": web_seeds,
168
+ "Created by": created_by or "—",
169
+ "Creation date (unix)": creation_date,
170
+ "Comment": comment or "—",
171
+ "Private": bool(info.get(b"private", 0)),
172
+ }
173
+ return {"summary": summary, "files_df": df, "raw": data, "info": info}
174
+
175
+ def summary_md(summary: Dict[str, Any]) -> str:
176
+ md = []
177
+ md.append(f"### {summary.get('Name','(unknown)')}")
178
+ md.append(f"- **Infohash (v1):** `{summary.get('Infohash (v1)')}`")
179
+ md.append(f"- **Total size:** {summary.get('Total size')} ({summary.get('Total size (bytes)')} bytes)")
180
+ md.append(f"- **Files:** {summary.get('Files count')}")
181
+ md.append(f"- **Piece length:** {summary.get('Piece length')}")
182
+ md.append(f"- **Pieces (count):** {summary.get('Pieces (count)')}")
183
+ md.append(f"- **Primary announce:** {summary.get('Primary announce')}")
184
+ trs = summary.get("Trackers") or []
185
+ if trs:
186
+ md.append(f"- **Additional trackers ({len(trs)}):**")
187
+ for t in trs:
188
+ md.append(f" - {t}")
189
+ seeds = summary.get("Web seeds") or []
190
+ if seeds:
191
+ md.append("- **Web seeds (BEP-19):**")
192
+ for s in seeds:
193
+ md.append(f" - {s}")
194
+ md.append(f"- **Created by:** {summary.get('Created by')}")
195
+ md.append(f"- **Creation date (unix):** {summary.get('Creation date (unix)')}")
196
+ md.append(f"- **Comment:** {summary.get('Comment')}")
197
+ md.append(f"- **Private:** {summary.get('Private')}")
198
+ return "\n".join(md)
199
+
200
+ # =========================
201
+ # Inspect handlers
202
+ # =========================
203
+
204
+ def handle_input(input_text: str, uploaded_file) -> Tuple[str, pd.DataFrame, str, str]:
205
+ """
206
+ Accept: magnet, .torrent URL, or uploaded .torrent.
207
+ Returns: (markdown_summary, files_df, csv_path, json_state_for_download_tab)
208
+ """
209
+ if uploaded_file is not None:
210
+ raw = uploaded_file.read()
211
+ parsed = parse_torrent(raw)
212
+ else:
213
+ if not input_text or not input_text.strip():
214
+ raise gr.Error("Provide a magnet link, a direct .torrent URL, or upload a .torrent.")
215
+ text = input_text.strip()
216
+ if is_magnet(text):
217
+ mag = parse_magnet(text)
218
+ if not mag.get("ok"):
219
+ raise gr.Error(f"Could not parse magnet: {mag.get('error')}")
220
+ # Magnet on Spaces → no file list (no DHT)
221
+ empty = pd.DataFrame(columns=["Path", "Length (bytes)", "Length (HR)"])
222
+ csvp = f"/mnt/data/files_{int(time.time())}.csv"; empty.to_csv(csvp, index=False)
223
+ state = {"summary": {"Name": mag.get("display_name") or "(magnet)",
224
+ "Infohash (v1)": mag.get("infohash_hex") or "—",
225
+ "Web seeds": []},
226
+ "files_df": empty.to_dict(orient="list"),
227
+ "magnet": mag}
228
+ md = "\n".join([
229
+ "### Magnet Metadata (no DHT on Spaces)",
230
+ f"- **Display name:** {mag.get('display_name')}",
231
+ f"- **Infohash (hex):** `{mag.get('infohash_hex') or '—'}`",
232
+ f"- **Trackers:** {len(mag.get('trackers') or [])}",
233
+ "",
234
+ "ℹ️ Use a corresponding **.torrent URL** (or upload it) for the full file list."
235
+ ])
236
+ return md, empty, csvp, json.dumps(state)
237
+ elif is_http_url(text):
238
+ raw = fetch_bytes(text)
239
+ parsed = parse_torrent(raw)
240
+ else:
241
+ raise gr.Error("Unrecognized input. Paste a **magnet:** link or a direct **.torrent** URL, or upload a .torrent.")
242
+
243
+ # For .torrent path:
244
+ csv_path = f"/mnt/data/files_{int(time.time())}.csv"
245
+ parsed["files_df"].to_csv(csv_path, index=False)
246
+ # pack state (DataFrame → records) to reuse in Download tab
247
+ state = {"summary": parsed["summary"], "files_df": parsed["files_df"].to_dict(orient="list")}
248
+ return summary_md(parsed["summary"]), parsed["files_df"], csv_path, json.dumps(state)
249
+
250
+ # =========================
251
+ # Download over HTTP
252
+ # =========================
253
+
254
+ def _join_url(base: str, *segs: str) -> str:
255
+ parts = [base.rstrip("/")]
256
+ for s in segs:
257
+ enc = "/".join([requests.utils.quote(p) for p in s.split("/")])
258
+ parts.append(enc)
259
+ return "/".join(parts)
260
+
261
+ def _sha256_file(path: pathlib.Path, bufsize: int = 1024 * 1024) -> str:
262
+ h = hashlib.sha256()
263
+ with open(path, "rb") as f:
264
+ while True:
265
+ b = f.read(bufsize)
266
+ if not b:
267
+ break
268
+ h.update(b)
269
+ return h.hexdigest()
270
+
271
+ def _supports_range(url: str, timeout: int = 30) -> Tuple[bool, Optional[int]]:
272
+ # HEAD to learn size and Accept-Ranges
273
+ r = requests.head(url, timeout=timeout, allow_redirects=True)
274
+ if r.status_code >= 400:
275
+ # Some servers don't allow HEAD; try GET without download
276
+ r = requests.get(url, stream=True, timeout=timeout, allow_redirects=True)
277
+ r.raise_for_status()
278
+ size = int(r.headers.get("Content-Length", "0") or 0)
279
+ accept_ranges = r.headers.get("Accept-Ranges", "")
280
+ try:
281
+ r.close()
282
+ except Exception:
283
+ pass
284
+ return ("bytes" in accept_ranges.lower() or size > 0, size if size > 0 else None)
285
+ size = int(r.headers.get("Content-Length", "0") or 0)
286
+ accept_ranges = r.headers.get("Accept-Ranges", "")
287
+ return ("bytes" in accept_ranges.lower() or size > 0, size if size > 0 else None)
288
+
289
+ def _download_with_resume(url: str, dest_path: pathlib.Path, timeout: int = 120) -> Tuple[int, Optional[int]]:
290
+ """
291
+ Download URL to dest_path with simple resume (HTTP Range).
292
+ Returns (bytes_written, total_expected or None).
293
+ """
294
+ dest_path.parent.mkdir(parents=True, exist_ok=True)
295
+ tmp_path = dest_path.with_suffix(dest_path.suffix + ".part")
296
+
297
+ existing = tmp_path.stat().st_size if tmp_path.exists() else 0
298
+ supports, total_size = _supports_range(url)
299
+ headers = {}
300
+ if supports and existing > 0:
301
+ headers["Range"] = f"bytes={existing}-"
302
+
303
+ mode = "ab" if headers.get("Range") else "wb"
304
+ bytes_written = 0
305
+
306
+ with requests.get(url, stream=True, timeout=timeout, headers=headers) as r:
307
+ r.raise_for_status()
308
+ with open(tmp_path, mode) as f:
309
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
310
+ if chunk:
311
+ f.write(chunk)
312
+ bytes_written += len(chunk)
313
+
314
+ # finalize
315
+ final_size = (existing + bytes_written)
316
+ # If we know total_size and match or server returned 200 with complete payload, rename
317
+ if total_size is None or final_size >= (total_size or 0):
318
+ tmp_path.rename(dest_path)
319
+ else:
320
+ # Keep .part if incomplete
321
+ pass
322
+ return bytes_written, total_size
323
+
324
+ def prepare_download(parsed_json: str, base_url_override: str) -> Tuple[str, List[str], List[str], str]:
325
+ """
326
+ Build seed list and file choices.
327
+ - If torrent has web seeds → use them.
328
+ - Else if base_url_override provided → use that as a 'seed'.
329
+ """
330
+ if not parsed_json:
331
+ return "Parse something in Inspect first.", [], [], ""
332
+ parsed = json.loads(parsed_json)
333
+ summary = parsed.get("summary") or {}
334
+ seeds = list(summary.get("Web seeds") or [])
335
+ root = summary.get("Name") or ""
336
+ if (not seeds) and base_url_override.strip():
337
+ seeds = [base_url_override.strip().rstrip("/")]
338
+ files_df = pd.DataFrame(parsed.get("files_df", {}))
339
+ file_list = files_df["Path"].astype(str).tolist() if not files_df.empty else []
340
+ if not seeds:
341
+ return ("No web seeds in torrent and no Base URL override supplied. "
342
+ "For Spaces downloads you need HTTP access to the files."), [], [], ""
343
+ msg = f"Ready. Root folder assumed: `{root}`. Select a seed and file(s) to download."
344
+ return msg, seeds, file_list, root
345
+
346
+ def download_selected(parsed_json: str, seed_url: str, root_dir: str, selected_files: List[str]) -> Tuple[str, List[str]]:
347
+ """
348
+ Download selected files into /mnt/data/downloads/<infohash>/...
349
+ Create .sha256 sidecar after successful completion.
350
+ """
351
+ if not parsed_json:
352
+ raise gr.Error("Parse a torrent first.")
353
+ if not seed_url:
354
+ raise gr.Error("Choose a web seed or set a Base URL override.")
355
+ if not selected_files:
356
+ raise gr.Error("Select at least one file.")
357
+
358
+ parsed = json.loads(parsed_json)
359
+ summary = parsed.get("summary") or {}
360
+ infohash = summary.get("Infohash (v1)") or "unknown"
361
+ out_root = pathlib.Path("/mnt/data/downloads") / infohash
362
+ out_root.mkdir(parents=True, exist_ok=True)
363
+
364
+ logs = []
365
+ saved = []
366
+
367
+ for rel in selected_files:
368
+ try:
369
+ url = _join_url(seed_url, root_dir, rel)
370
+ dest_path = out_root / rel
371
+ bytes_written, total_expected = _download_with_resume(url, dest_path)
372
+ # Verify size if server told us
373
+ if total_expected is not None and dest_path.exists() and dest_path.stat().st_size != total_expected:
374
+ logs.append(f"⚠️ Size mismatch for {rel} (got {dest_path.stat().st_size}, expected {total_expected}). Kept .part if incomplete.")
375
+ # SHA256
376
+ if dest_path.exists():
377
+ sha = _sha256_file(dest_path)
378
+ with open(str(dest_path) + ".sha256", "w") as f:
379
+ f.write(f"{sha} {dest_path.name}\n")
380
+ logs.append(f"✅ {rel} — saved {human_bytes(dest_path.stat().st_size)} → {dest_path}")
381
+ saved.append(str(dest_path))
382
+ else:
383
+ logs.append(f"❌ {rel} — download incomplete.")
384
+ except Exception as e:
385
+ logs.append(f"❌ {rel} — {type(e).__name__}: {e}")
386
+
387
+ return "\n".join(logs), saved
388
+
389
+ def preview_file(path_str: str, max_bytes: int = 300_000) -> Tuple[str, Optional[pd.DataFrame], Optional[str]]:
390
+ if not path_str:
391
+ raise gr.Error("Provide a path in /mnt/data.")
392
+ p = pathlib.Path(path_str)
393
+ if not p.exists():
394
+ raise gr.Error("File not found.")
395
+ suffix = p.suffix.lower()
396
+ try:
397
+ if suffix in [".csv", ".tsv"]:
398
+ sep = "," if suffix == ".csv" else "\t"
399
+ df = pd.read_csv(p, sep=sep, nrows=2000, on_bad_lines="skip")
400
+ return f"Previewing {p.name} (first rows):", df, None
401
+ elif suffix in [".json", ".ndjson"]:
402
+ raw = open(p, "rb").read(max_bytes)
403
+ try:
404
+ obj = json.loads(raw.decode("utf-8", errors="replace"))
405
+ pretty = json.dumps(obj, indent=2)[:max_bytes]
406
+ except Exception:
407
+ pretty = raw.decode("utf-8", errors="replace")
408
+ return f"Previewing {p.name}:", None, f"```\n{pretty}\n```"
409
+ elif suffix in [".txt", ".log", ".md"]:
410
+ raw = open(p, "rb").read(max_bytes)
411
+ text = raw.decode("utf-8", errors="replace")
412
+ return f"Previewing {p.name}:", None, f"```\n{text}\n```"
413
+ else:
414
+ st = p.stat()
415
+ return (f"File: **{p.name}**\nSize: {human_bytes(st.st_size)}\nPath: `{p}`",
416
+ None, None)
417
+ except Exception as e:
418
+ return f"Error previewing file: {type(e).__name__}: {e}", None, None
419
+
420
+ # =========================
421
+ # UI
422
+ # =========================
423
+
424
+ CSS = """
425
+ #top-note {font-size: 0.95rem; opacity: 0.9;}
426
+ """
427
+
428
+ with gr.Blocks(css=CSS, title="Torrent Inspector + Full HTTP Downloader") as demo:
429
+ gr.Markdown(
430
+ """
431
+ # 🧭 Torrent Inspector + Full HTTP Downloader (no P2P)
432
+
433
+ - Paste a **magnet** or a **.torrent URL**, or upload a `.torrent`.
434
+ - Full file lists come from **.torrent** metadata.
435
+ - **Downloads use HTTPS only**: either BEP-19 **web seeds** from the torrent or a **Base URL override** you supply (e.g., `https://data.ddosecrets.com/<collection>`).
436
+ - Supports **large files (e.g., 7 GB)** with **resume (HTTP Range)** and **SHA-256** sidecar files.
437
+
438
+ > BitTorrent/DHT is not used here (Spaces networking limits). If your torrent doesn’t include web seeds, set the base URL to a mirror that serves the same paths.
439
+ """,
440
+ elem_id="top-note"
441
+ )
442
+
443
+ with gr.Tab("Inspect"):
444
+ with gr.Row():
445
+ input_text = gr.Textbox(
446
+ label="Magnet or .torrent URL",
447
+ placeholder="magnet:?xt=urn:btih:... OR https://.../something.torrent",
448
+ )
449
+ upload_torrent = gr.File(label="Or upload .torrent", file_types=[".torrent"])
450
+ inspect_btn = gr.Button("Parse")
451
+ out_summary = gr.Markdown(label="Summary")
452
+ out_df = gr.Dataframe(label="Files in Torrent", interactive=False)
453
+ out_csv = gr.File(label="Export file list (CSV)")
454
+ parsed_state = gr.State()
455
+
456
+ def _wrap_handle(inp, upl):
457
+ md, df, csvp, state_json = handle_input(inp, upl)
458
+ return md, df, csvp, state_json
459
+
460
+ inspect_btn.click(
461
+ fn=_wrap_handle,
462
+ inputs=[input_text, upload_torrent],
463
+ outputs=[out_summary, out_df, out_csv, parsed_state]
464
+ )
465
+
466
+ with gr.Tab("Download"):
467
+ gr.Markdown(
468
+ "Choose HTTP source: torrent **web seed** (if present) or specify a **Base URL override** (e.g., `https://data.ddosecrets.com/Gabi%20Ashkenazi%20emails`)."
469
+ )
470
+ base_url_override = gr.Textbox(
471
+ label="Base URL override (optional)",
472
+ placeholder="https://data.ddosecrets.com/<collection>",
473
+ )
474
+ prep_btn = gr.Button("Prepare")
475
+ status_md = gr.Markdown()
476
+ seed_dropdown = gr.Dropdown(label="Choose HTTP source", choices=[])
477
+ root_dir_box = gr.Textbox(label="Assumed root folder name", interactive=False)
478
+ files_checkbox = gr.CheckboxGroup(label="Select files to download", choices=[])
479
+ dl_btn = gr.Button("Download selected")
480
+ logs_md = gr.Markdown()
481
+ saved_files = gr.Gallery(label="Saved paths", show_label=True, columns=1, height=220)
482
+ saved_files.style(grid=[1])
483
+
484
+ def _prep(state_json, base_override):
485
+ msg, seeds, files, root = prepare_download(state_json, base_override or "")
486
+ return msg, gr.update(choices=seeds, value=(seeds[0] if seeds else None)), root, gr.update(choices=files)
487
+
488
+ prep_btn.click(fn=_prep, inputs=[parsed_state, base_url_override], outputs=[status_md, seed_dropdown, root_dir_box, files_checkbox])
489
+
490
+ def _dl(state_json, seed, root, files):
491
+ logs, paths = download_selected(state_json, seed, root, files)
492
+ return logs, paths
493
+
494
+ dl_btn.click(fn=_dl, inputs=[parsed_state, seed_dropdown, root_dir_box, files_checkbox], outputs=[logs_md, saved_files])
495
+
496
+ gr.Markdown("**Preview a saved file (optional):**")
497
+ with gr.Row():
498
+ path_in = gr.Textbox(label="Path under /mnt/data", placeholder="/mnt/data/downloads/<infohash>/subdir/file.txt")
499
+ preview_btn = gr.Button("Preview")
500
+ prev_status = gr.Markdown()
501
+ prev_df = gr.Dataframe(visible=False)
502
+ prev_md = gr.Markdown(visible=True)
503
+
504
+ def _preview(p):
505
+ status, df, md = preview_file(p)
506
+ return status, (df if df is not None else gr.update(visible=False)), (md if md is not None else gr.update(visible=False))
507
+
508
+ preview_btn.click(fn=_preview, inputs=[path_in], outputs=[prev_status, prev_df, prev_md])
509
+
510
+ gr.Markdown(
511
+ """
512
+ **Tips / Limits**
513
+
514
+ - If you know the dataset lives at `https://data.ddosecrets.com/<CollectionName>/`, put that in **Base URL override**.
515
+ - The downloader writes to `/mnt/data/downloads/<infohash>/...` with resuming and `.sha256` checksums.
516
+ - Some hosts may not allow `HEAD` or `Range`; the app falls back to plain GET when possible.
517
+ """
518
+ )
519
+
520
+ if __name__ == "__main__":
521
+ demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))