Roman190928 commited on
Commit
83d2ebb
·
verified ·
1 Parent(s): f1fd68b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -943
app.py DELETED
@@ -1,943 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import asyncio
5
- import threading
6
- import traceback
7
- from collections import deque
8
- from dataclasses import dataclass
9
- from datetime import datetime, timezone
10
- from html import escape
11
- from pathlib import Path
12
- from typing import Any
13
- from urllib.parse import urlsplit
14
-
15
- import huggingface_hub as hf_hub
16
-
17
- if not hasattr(hf_hub, "HfFolder"):
18
- class _CompatHfFolder:
19
- @staticmethod
20
- def get_token() -> str | None:
21
- return None
22
-
23
- @staticmethod
24
- def save_token(token: str) -> None:
25
- del token
26
- return None
27
-
28
- @staticmethod
29
- def delete_token() -> None:
30
- return None
31
-
32
- hf_hub.HfFolder = _CompatHfFolder # type: ignore[attr-defined]
33
-
34
- import gradio as gr
35
-
36
- from crawler import (
37
- MAX_SHARD_ROWS,
38
- NORMAL_TOTAL_WORKERS,
39
- SUPER_TOTAL_WORKERS,
40
- AsyncCrawler,
41
- CrawlerConfig,
42
- )
43
-
44
- APP_CSS = """
45
- :root {
46
- --bg-main: #0a0d12;
47
- --bg-surface: #151a22;
48
- --bg-panel: #1b2230;
49
- --text-main: #f0f4fb;
50
- --text-muted: #9aa4b6;
51
- --accent: #3bd9ff;
52
- --accent-2: #4cffb1;
53
- --border: #2f3a50;
54
- --shadow: 0 18px 36px rgba(0, 0, 0, 0.45);
55
- }
56
-
57
- :root[data-crawler-theme="red"] {
58
- --bg-main: #17080c;
59
- --bg-surface: #250d15;
60
- --bg-panel: #341322;
61
- --text-main: #f8e8ee;
62
- --text-muted: #d5b0c0;
63
- --accent: #7a0018;
64
- --accent-2: #8e3ff5;
65
- --border: #5a2035;
66
- }
67
-
68
- :root[data-crawler-theme="blue"] {
69
- --bg-main: #021116;
70
- --bg-surface: #08222c;
71
- --bg-panel: #0e2f3b;
72
- --text-main: #eaffff;
73
- --text-muted: #8fbcc7;
74
- --accent: #2fff9d;
75
- --accent-2: #13e5ff;
76
- --border: #1e5662;
77
- }
78
-
79
- :root[data-crawler-theme="light"] {
80
- --bg-main: #f6f7f9;
81
- --bg-surface: #ffffff;
82
- --bg-panel: #eceff2;
83
- --text-main: #111317;
84
- --text-muted: #60666f;
85
- --accent: #2a2f37;
86
- --accent-2: #868b95;
87
- --border: #d0d4db;
88
- --shadow: 0 10px 25px rgba(35, 42, 52, 0.16);
89
- }
90
-
91
- :root[data-crawler-theme="dark"] {
92
- --bg-main: #090909;
93
- --bg-surface: #141414;
94
- --bg-panel: #1d1d1d;
95
- --text-main: #f0f0f0;
96
- --text-muted: #a8a8a8;
97
- --accent: #444444;
98
- --accent-2: #686868;
99
- --border: #2b2b2b;
100
- }
101
-
102
- :root[data-crawler-theme="green"] {
103
- --bg-main: #08110b;
104
- --bg-surface: #0f1d14;
105
- --bg-panel: #17301e;
106
- --text-main: #e8f8ed;
107
- --text-muted: #97bc9f;
108
- --accent: #2ea84b;
109
- --accent-2: #185f2a;
110
- --border: #2a5d36;
111
- }
112
-
113
- .gradio-container {
114
- background:
115
- radial-gradient(1200px 550px at 8% 0%, color-mix(in srgb, var(--accent) 18%, transparent), transparent),
116
- radial-gradient(900px 600px at 100% 0%, color-mix(in srgb, var(--accent-2) 14%, transparent), transparent),
117
- var(--bg-main);
118
- color: var(--text-main);
119
- }
120
-
121
- .gradio-container .block,
122
- .gradio-container .form,
123
- .gradio-container .gr-box,
124
- .gradio-container .panel-wrap {
125
- background: color-mix(in srgb, var(--bg-surface) 92%, transparent) !important;
126
- border: 1px solid var(--border) !important;
127
- box-shadow: var(--shadow);
128
- }
129
-
130
- .gradio-container h1,
131
- .gradio-container h2,
132
- .gradio-container h3,
133
- .gradio-container p,
134
- .gradio-container label,
135
- .gradio-container .prose,
136
- .gradio-container .prose * {
137
- color: var(--text-main) !important;
138
- }
139
-
140
- .gradio-container input,
141
- .gradio-container textarea,
142
- .gradio-container select {
143
- background: var(--bg-panel) !important;
144
- color: var(--text-main) !important;
145
- border: 1px solid var(--border) !important;
146
- }
147
-
148
- .gradio-container button {
149
- border: 1px solid var(--border) !important;
150
- }
151
-
152
- .gradio-container button.primary {
153
- background: linear-gradient(135deg, var(--accent), var(--accent-2)) !important;
154
- color: #0b0e13 !important;
155
- font-weight: 700;
156
- }
157
-
158
- .seed-widget,
159
- .token-widget {
160
- display: flex;
161
- flex-direction: column;
162
- gap: 0.75rem;
163
- border: 1px solid var(--border);
164
- border-radius: 0.9rem;
165
- padding: 0.85rem;
166
- background: color-mix(in srgb, var(--bg-panel) 86%, transparent);
167
- }
168
-
169
- .seed-stats,
170
- .token-stats {
171
- display: grid;
172
- grid-template-columns: repeat(3, minmax(0, 1fr));
173
- gap: 0.6rem;
174
- }
175
-
176
- .seed-stats > span,
177
- .token-stats > span {
178
- display: block;
179
- padding: 0.55rem;
180
- border: 1px solid var(--border);
181
- border-radius: 0.6rem;
182
- background: color-mix(in srgb, var(--bg-surface) 90%, transparent);
183
- color: var(--text-main);
184
- font-size: 0.9rem;
185
- }
186
-
187
- .seed-chip-wrap {
188
- display: flex;
189
- flex-wrap: wrap;
190
- gap: 0.45rem;
191
- }
192
-
193
- .seed-chip {
194
- border: 1px solid var(--border);
195
- border-radius: 999px;
196
- padding: 0.24rem 0.7rem;
197
- color: var(--text-main);
198
- background: linear-gradient(
199
- 145deg,
200
- color-mix(in srgb, var(--accent) 20%, transparent),
201
- color-mix(in srgb, var(--accent-2) 15%, transparent)
202
- );
203
- font-size: 0.83rem;
204
- }
205
-
206
- .seed-empty,
207
- .seed-overflow,
208
- .token-note {
209
- color: var(--text-muted);
210
- font-size: 0.83rem;
211
- padding: 0.24rem 0.3rem;
212
- }
213
- """
214
-
215
- THEME_JS = """
216
- (theme_name) => {
217
- const theme = theme_name || "dark";
218
- document.documentElement.setAttribute("data-crawler-theme", theme);
219
- return [];
220
- }
221
- """
222
-
223
- SEED_WIDGET_JS = """
224
- (seed_rows) => {
225
- const parseRows = (rows) => {
226
- if (!Array.isArray(rows)) return [];
227
- const out = [];
228
- for (const row of rows) {
229
- let value = "";
230
- if (Array.isArray(row)) {
231
- value = String(row[0] ?? "").trim();
232
- } else if (row && typeof row === "object") {
233
- value = String(Object.values(row)[0] ?? "").trim();
234
- } else if (row !== null && row !== undefined) {
235
- value = String(row).trim();
236
- }
237
- if (value) out.push(value);
238
- }
239
- return out;
240
- };
241
- const dedupe = (values) => {
242
- const seen = new Set();
243
- const out = [];
244
- for (const value of values) {
245
- if (!seen.has(value)) {
246
- seen.add(value);
247
- out.push(value);
248
- }
249
- }
250
- return out;
251
- };
252
- const domainOf = (value) => {
253
- try {
254
- return new URL(value).hostname || "";
255
- } catch {
256
- return "";
257
- }
258
- };
259
- const escapeHtml = (value) => String(value)
260
- .replaceAll("&", "&")
261
- .replaceAll("<", "&lt;")
262
- .replaceAll(">", "&gt;")
263
- .replaceAll('"', "&quot;")
264
- .replaceAll("'", "&#39;");
265
-
266
- const seeds = dedupe(parseRows(seed_rows));
267
- const domainSet = new Set(seeds.map(domainOf).filter(Boolean));
268
- const chips = seeds.length
269
- ? seeds.slice(0, 12).map((url) => `<span class=\"seed-chip\">${escapeHtml(url)}</span>`).join("")
270
- : '<span class=\"seed-empty\">No seed URLs configured yet.</span>';
271
- const overflow = seeds.length > 12
272
- ? `<span class=\"seed-overflow\">+${seeds.length - 12} more</span>`
273
- : "";
274
-
275
- return `<div class=\"seed-widget\"><div class=\"seed-stats\"><span><strong>${seeds.length}</strong> seeds</span><span><strong>${domainSet.size}</strong> domains</span><span><strong>${seeds.slice(0, 1).join("").length || 0}</strong> first-url chars</span></div><div class=\"seed-chip-wrap\">${chips}${overflow}</div></div>`;
276
- }
277
- """
278
-
279
-
280
- def utc_now_iso() -> str:
281
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
282
-
283
-
284
- def safe_queue_size(queue: Any) -> int:
285
- try:
286
- return int(queue.qsize())
287
- except Exception:
288
- return -1
289
-
290
-
291
- def parse_seed_url_rows(rows: Any) -> list[str]:
292
- items: list[str] = []
293
- if not rows:
294
- return items
295
-
296
- for row in rows:
297
- value = ""
298
- if isinstance(row, dict):
299
- first_value = next(iter(row.values()), "")
300
- value = str(first_value or "").strip()
301
- elif isinstance(row, (list, tuple)):
302
- first_value = row[0] if row else ""
303
- value = str(first_value or "").strip()
304
- elif row is not None:
305
- value = str(row).strip()
306
-
307
- if value:
308
- items.append(value)
309
- return items
310
-
311
-
312
- def unique_preserve_order(values: list[str]) -> list[str]:
313
- seen: set[str] = set()
314
- out: list[str] = []
315
- for value in values:
316
- if value in seen:
317
- continue
318
- seen.add(value)
319
- out.append(value)
320
- return out
321
-
322
-
323
- def collect_seed_urls(seed_urls_table: Any) -> list[str]:
324
- return unique_preserve_order(parse_seed_url_rows(seed_urls_table))
325
-
326
-
327
- def render_seed_widget_html(seed_urls_table: Any) -> str:
328
- seeds = collect_seed_urls(seed_urls_table)
329
- domains = {(urlsplit(u).hostname or "").lower().strip(".") for u in seeds}
330
- domains = {d for d in domains if d}
331
-
332
- chips: list[str] = []
333
- for url in seeds[:12]:
334
- chips.append(f'<span class="seed-chip">{escape(url)}</span>')
335
-
336
- chips_html = "".join(chips) if chips else '<span class="seed-empty">No seed URLs configured yet.</span>'
337
- overflow_html = f'<span class="seed-overflow">+{len(seeds) - 12} more</span>' if len(seeds) > 12 else ""
338
-
339
- return (
340
- '<div class="seed-widget">'
341
- '<div class="seed-stats">'
342
- f"<span><strong>{len(seeds)}</strong> seeds</span>"
343
- f"<span><strong>{len(domains)}</strong> domains</span>"
344
- f"<span><strong>{len(seeds[0]) if seeds else 0}</strong> first-url chars</span>"
345
- "</div>"
346
- f'<div class="seed-chip-wrap">{chips_html}{overflow_html}</div>'
347
- "</div>"
348
- )
349
-
350
-
351
- def render_tokenization_widget_html(snapshot: dict[str, Any]) -> str:
352
- tokenized_shards = int(snapshot.get("tokenized_shards", 0) or 0)
353
- tokenized_rows = int(snapshot.get("tokenized_rows", 0) or 0)
354
- tokenized_tokens = int(snapshot.get("tokenized_tokens", 0) or 0)
355
- written_shards = int(snapshot.get("written_shards", 0) or 0)
356
-
357
- return (
358
- '<div class="token-widget">'
359
- '<div class="token-stats">'
360
- f"<span><strong>{tokenized_tokens}</strong> text tokens</span>"
361
- f"<span><strong>{tokenized_rows}</strong> tokenized rows</span>"
362
- f"<span><strong>{tokenized_shards}/{written_shards}</strong> tokenized shards</span>"
363
- "</div>"
364
- '<div class="token-note">Live shard tokenization uses tiktoken on the parquet <code>text</code> column.</div>'
365
- "</div>"
366
- )
367
-
368
-
369
- def render_qvp_widget_md(snapshot: dict[str, Any]) -> str:
370
- queue_count = int(snapshot.get("fetch_queue", 0) or 0)
371
- visited_count = int(snapshot.get("fetch_succeeded", 0) or 0)
372
- parsed_count = int(snapshot.get("parsed_pages", 0) or 0)
373
- return (
374
- "### Live Metrics\n"
375
- f"- Queue: `{queue_count}`\n"
376
- f"- Visited: `{visited_count}`\n"
377
- f"- Parsed: `{parsed_count}`"
378
- )
379
-
380
-
381
- def validate_hf_requirements(enable_hf_upload: bool, hf_repo_id: str, hf_token: str) -> None:
382
- if not enable_hf_upload:
383
- return
384
- if not hf_repo_id.strip():
385
- raise ValueError("HF repo is required when upload is enabled.")
386
- if not hf_token.strip():
387
- raise ValueError("HF token is required when upload is enabled.")
388
-
389
-
390
- def build_crawler_config(
391
- *,
392
- seed_urls_table: Any,
393
- max_links_per_page: int,
394
- request_timeout_seconds: float,
395
- max_response_bytes: int,
396
- shard_size_rows: int,
397
- enable_hf_upload: bool,
398
- hf_repo_id: str,
399
- hf_token: str,
400
- hf_private_repo: bool,
401
- hf_path_prefix: str,
402
- total_workers: int,
403
- ) -> CrawlerConfig:
404
- validate_hf_requirements(enable_hf_upload, hf_repo_id, hf_token)
405
-
406
- seed_urls = collect_seed_urls(seed_urls_table)
407
-
408
- return CrawlerConfig(
409
- seed_urls=seed_urls,
410
- max_links_per_page=int(max_links_per_page),
411
- request_timeout_seconds=float(request_timeout_seconds),
412
- max_response_bytes=int(max_response_bytes),
413
- shard_size_rows=int(shard_size_rows),
414
- output_dir=Path(__file__).resolve().parent / "shards",
415
- enable_hf_upload=bool(enable_hf_upload),
416
- hf_repo_id=hf_repo_id.strip(),
417
- hf_token=hf_token.strip(),
418
- hf_private_repo=bool(hf_private_repo),
419
- hf_path_prefix=hf_path_prefix.strip() or "crawl_shards",
420
- total_workers=int(total_workers),
421
- )
422
-
423
-
424
- @dataclass
425
- class RunState:
426
- run_id: int = 0
427
- running: bool = False
428
- started_at: str = ""
429
- finished_at: str = ""
430
- stop_requested: bool = False
431
- last_error: str = ""
432
-
433
-
434
- class CrawlerRunManager:
435
- def __init__(self) -> None:
436
- self._lock = threading.Lock()
437
- self._thread: threading.Thread | None = None
438
- self._loop: asyncio.AbstractEventLoop | None = None
439
- self._crawler: AsyncCrawler | None = None
440
- self._state = RunState()
441
- self._history: deque[dict[str, Any]] = deque(maxlen=1200)
442
- self._logs: deque[str] = deque(maxlen=600)
443
- self._last_snapshot: dict[str, Any] | None = None
444
-
445
- def start(self, config: CrawlerConfig) -> str:
446
- with self._lock:
447
- if self._thread is not None and self._thread.is_alive():
448
- return "A crawl is already running. Stop it before starting another one."
449
-
450
- self._state.run_id += 1
451
- self._state.running = True
452
- self._state.started_at = utc_now_iso()
453
- self._state.finished_at = ""
454
- self._state.stop_requested = False
455
- self._state.last_error = ""
456
- self._history.clear()
457
- self._last_snapshot = None
458
- self._logs.clear()
459
-
460
- run_id = self._state.run_id
461
- self._logs.append(
462
- f"[{utc_now_iso()}] Started run #{run_id} with {config.total_workers} workers "
463
- f"({config.fetch_workers} fetch / {config.parser_workers} parser)."
464
- )
465
-
466
- self._thread = threading.Thread(
467
- target=self._run_crawler,
468
- args=(run_id, config),
469
- daemon=True,
470
- name=f"crawler-run-{run_id}",
471
- )
472
- self._thread.start()
473
-
474
- return f"Run #{run_id} started."
475
-
476
- def stop(self) -> str:
477
- with self._lock:
478
- if self._thread is None or not self._thread.is_alive():
479
- return "No active crawl to stop."
480
-
481
- self._state.stop_requested = True
482
- crawler = self._crawler
483
- loop = self._loop
484
- run_id = self._state.run_id
485
- self._logs.append(f"[{utc_now_iso()}] Stop requested for run #{run_id}")
486
-
487
- if crawler is not None and loop is not None and loop.is_running():
488
- loop.call_soon_threadsafe(crawler.request_stop, "user_requested_stop")
489
- elif crawler is not None:
490
- crawler.request_stop("user_requested_stop")
491
-
492
- return f"Stop signal sent to run #{run_id}."
493
-
494
- def _run_crawler(self, run_id: int, config: CrawlerConfig) -> None:
495
- loop = asyncio.new_event_loop()
496
- asyncio.set_event_loop(loop)
497
- try:
498
- crawler = AsyncCrawler(config)
499
- with self._lock:
500
- if self._state.run_id == run_id:
501
- self._crawler = crawler
502
- self._loop = loop
503
-
504
- loop.run_until_complete(crawler.run())
505
- final_snapshot = self._snapshot_from_crawler(crawler)
506
- with self._lock:
507
- if self._state.run_id == run_id:
508
- self._last_snapshot = final_snapshot
509
- self._history.append(final_snapshot)
510
- self._logs.append(f"[{utc_now_iso()}] Run #{run_id} completed")
511
- except Exception:
512
- error_text = traceback.format_exc(limit=20)
513
- with self._lock:
514
- self._state.last_error = error_text
515
- self._logs.append(f"[{utc_now_iso()}] Run #{run_id} crashed")
516
- finally:
517
- with self._lock:
518
- if self._state.run_id == run_id:
519
- self._state.running = False
520
- self._state.finished_at = utc_now_iso()
521
- self._crawler = None
522
- self._loop = None
523
- loop.close()
524
- asyncio.set_event_loop(None)
525
-
526
- def _snapshot_from_crawler(self, crawler: AsyncCrawler) -> dict[str, Any]:
527
- stats = crawler.stats
528
- return {
529
- "timestamp": utc_now_iso(),
530
- "workers_total": crawler.config.total_workers,
531
- "workers_split": f"{crawler.config.fetch_workers}/{crawler.config.parser_workers}",
532
- "stop_reason": crawler.stop_reason or "-",
533
- "queued_urls": stats.queued_urls,
534
- "fetch_reserved": stats.fetch_reserved,
535
- "fetch_succeeded": stats.fetch_succeeded,
536
- "fetch_failed": stats.fetch_failed,
537
- "parsed_pages": stats.parsed_pages,
538
- "parse_failed": stats.parse_failed,
539
- "extracted_links": stats.extracted_links,
540
- "dropped_urls": stats.dropped_urls,
541
- "robots_blocked": stats.robots_blocked,
542
- "stored_rows": stats.stored_rows,
543
- "written_shards": stats.written_shards,
544
- "uploaded_shards": stats.uploaded_shards,
545
- "tokenized_shards": stats.tokenized_shards,
546
- "tokenized_rows": stats.tokenized_rows,
547
- "tokenized_tokens": stats.tokenized_tokens,
548
- "active_fetchers": crawler.active_fetchers,
549
- "active_parsers": crawler.active_parsers,
550
- "fetch_queue": safe_queue_size(crawler.fetch_queue),
551
- "parse_queue": safe_queue_size(crawler.parse_queue),
552
- "record_queue": safe_queue_size(crawler.record_queue),
553
- "stop_event": crawler.stop_event.is_set(),
554
- }
555
-
556
- def poll(self) -> tuple[str, dict[str, Any], list[list[Any]], str]:
557
- with self._lock:
558
- crawler = self._crawler
559
- state = RunState(
560
- run_id=self._state.run_id,
561
- running=self._state.running,
562
- started_at=self._state.started_at,
563
- finished_at=self._state.finished_at,
564
- stop_requested=self._state.stop_requested,
565
- last_error=self._state.last_error,
566
- )
567
-
568
- if crawler is not None:
569
- snapshot = self._snapshot_from_crawler(crawler)
570
- with self._lock:
571
- self._last_snapshot = snapshot
572
- if not self._history or self._history[-1]["timestamp"] != snapshot["timestamp"]:
573
- self._history.append(snapshot)
574
-
575
- with self._lock:
576
- latest = self._last_snapshot or {
577
- "timestamp": utc_now_iso(),
578
- "workers_total": 0,
579
- "workers_split": "-",
580
- "stop_reason": "-",
581
- "queued_urls": 0,
582
- "fetch_reserved": 0,
583
- "fetch_succeeded": 0,
584
- "fetch_failed": 0,
585
- "parsed_pages": 0,
586
- "parse_failed": 0,
587
- "extracted_links": 0,
588
- "dropped_urls": 0,
589
- "robots_blocked": 0,
590
- "stored_rows": 0,
591
- "written_shards": 0,
592
- "uploaded_shards": 0,
593
- "tokenized_shards": 0,
594
- "tokenized_rows": 0,
595
- "tokenized_tokens": 0,
596
- "active_fetchers": 0,
597
- "active_parsers": 0,
598
- "fetch_queue": 0,
599
- "parse_queue": 0,
600
- "record_queue": 0,
601
- "stop_event": False,
602
- }
603
- history_copy = list(self._history)
604
- logs_text = "\n".join(self._logs)
605
-
606
- history_rows: list[list[Any]] = []
607
- for item in reversed(history_copy[-180:]):
608
- history_rows.append(
609
- [
610
- item["timestamp"],
611
- item["workers_total"],
612
- item["workers_split"],
613
- item["fetch_reserved"],
614
- item["fetch_succeeded"],
615
- item["parsed_pages"],
616
- item["stored_rows"],
617
- item["written_shards"],
618
- item["uploaded_shards"],
619
- item["tokenized_tokens"],
620
- item["fetch_queue"],
621
- item["parse_queue"],
622
- item["record_queue"],
623
- item["stop_reason"],
624
- ]
625
- )
626
-
627
- status_lines = [
628
- "### Crawler Status",
629
- f"- Run ID: `{state.run_id}`",
630
- f"- Running: `{state.running}`",
631
- f"- Stop requested: `{state.stop_requested}`",
632
- f"- Started at (UTC): `{state.started_at or '-'}`",
633
- f"- Finished at (UTC): `{state.finished_at or '-'}`",
634
- ]
635
- if state.last_error:
636
- status_lines.append("- Last error:")
637
- status_lines.append("```text")
638
- status_lines.append(state.last_error.strip())
639
- status_lines.append("```")
640
-
641
- return "\n".join(status_lines), latest, history_rows, logs_text
642
-
643
-
644
- RUN_MANAGER = CrawlerRunManager()
645
-
646
-
647
- def _format_dashboard_response(
648
- payload: tuple[str, dict[str, Any], list[list[Any]], str]
649
- ) -> tuple[str, str, str, str]:
650
- status, snapshot, history, logs = payload
651
- del history
652
- return (
653
- status,
654
- render_qvp_widget_md(snapshot),
655
- logs,
656
- render_tokenization_widget_html(snapshot),
657
- )
658
-
659
-
660
- def _start_crawl(
661
- *,
662
- total_workers: int,
663
- seed_urls_table: Any,
664
- max_links_per_page: int,
665
- request_timeout_seconds: float,
666
- max_response_bytes: int,
667
- shard_size_rows: int,
668
- enable_hf_upload: bool,
669
- hf_repo_id: str,
670
- hf_token: str,
671
- hf_private_repo: bool,
672
- hf_path_prefix: str,
673
- ) -> tuple[str, str, str, str]:
674
- try:
675
- config = build_crawler_config(
676
- seed_urls_table=seed_urls_table,
677
- max_links_per_page=max_links_per_page,
678
- request_timeout_seconds=request_timeout_seconds,
679
- max_response_bytes=max_response_bytes,
680
- shard_size_rows=shard_size_rows,
681
- enable_hf_upload=enable_hf_upload,
682
- hf_repo_id=hf_repo_id,
683
- hf_token=hf_token,
684
- hf_private_repo=hf_private_repo,
685
- hf_path_prefix=hf_path_prefix,
686
- total_workers=total_workers,
687
- )
688
- except ValueError as exc:
689
- raise gr.Error(str(exc)) from exc
690
-
691
- message = RUN_MANAGER.start(config)
692
- status, snapshot, history, logs = RUN_MANAGER.poll()
693
- return _format_dashboard_response((f"{status}\n\n{message}", snapshot, history, logs))
694
-
695
-
696
- def start_crawl_standard(
697
- seed_urls_table: Any,
698
- max_links_per_page: int,
699
- request_timeout_seconds: float,
700
- max_response_bytes: int,
701
- shard_size_rows: int,
702
- enable_hf_upload: bool,
703
- hf_repo_id: str,
704
- hf_token: str,
705
- hf_private_repo: bool,
706
- hf_path_prefix: str,
707
- ) -> tuple[str, str, str, str]:
708
- return _start_crawl(
709
- total_workers=NORMAL_TOTAL_WORKERS,
710
- seed_urls_table=seed_urls_table,
711
- max_links_per_page=max_links_per_page,
712
- request_timeout_seconds=request_timeout_seconds,
713
- max_response_bytes=max_response_bytes,
714
- shard_size_rows=shard_size_rows,
715
- enable_hf_upload=enable_hf_upload,
716
- hf_repo_id=hf_repo_id,
717
- hf_token=hf_token,
718
- hf_private_repo=hf_private_repo,
719
- hf_path_prefix=hf_path_prefix,
720
- )
721
-
722
-
723
- def start_crawl_super(
724
- seed_urls_table: Any,
725
- max_links_per_page: int,
726
- request_timeout_seconds: float,
727
- max_response_bytes: int,
728
- shard_size_rows: int,
729
- enable_hf_upload: bool,
730
- hf_repo_id: str,
731
- hf_token: str,
732
- hf_private_repo: bool,
733
- hf_path_prefix: str,
734
- ) -> tuple[str, str, str, str]:
735
- return _start_crawl(
736
- total_workers=SUPER_TOTAL_WORKERS,
737
- seed_urls_table=seed_urls_table,
738
- max_links_per_page=max_links_per_page,
739
- request_timeout_seconds=request_timeout_seconds,
740
- max_response_bytes=max_response_bytes,
741
- shard_size_rows=shard_size_rows,
742
- enable_hf_upload=enable_hf_upload,
743
- hf_repo_id=hf_repo_id,
744
- hf_token=hf_token,
745
- hf_private_repo=hf_private_repo,
746
- hf_path_prefix=hf_path_prefix,
747
- )
748
-
749
-
750
- def stop_crawl() -> tuple[str, str, str, str]:
751
- message = RUN_MANAGER.stop()
752
- status, snapshot, history, logs = RUN_MANAGER.poll()
753
- return _format_dashboard_response((f"{status}\n\n{message}", snapshot, history, logs))
754
-
755
-
756
- def poll_dashboard() -> tuple[str, str, str, str]:
757
- return _format_dashboard_response(RUN_MANAGER.poll())
758
-
759
-
760
- def toggle_hf_fields(enable_hf_upload: bool) -> tuple[Any, Any, Any, Any]:
761
- update = gr.update(visible=enable_hf_upload)
762
- return update, update, update, update
763
-
764
-
765
- def build_ui() -> gr.Blocks:
766
- defaults = CrawlerConfig(
767
- seed_urls=[
768
- "https://en.wikipedia.org/wiki/Main_Page",
769
- "https://docs.python.org/3/",
770
- "https://developer.mozilla.org/en-US/",
771
- "https://www.nasa.gov/",
772
- ]
773
- )
774
- default_seed_rows = [[url] for url in defaults.seed_urls]
775
-
776
- with gr.Blocks(
777
- title="DataMuncherLabs AutoWS",
778
- css=APP_CSS,
779
- theme=gr.themes.Default(primary_hue="green"),
780
- ) as demo:
781
- gr.Markdown("# DataMuncherLabs AutoWS")
782
- gr.Markdown("Async web crawler dashboard with live parquet text tokenization.")
783
-
784
- with gr.Row():
785
- theme_name = gr.Dropdown(
786
- choices=["red", "blue", "light", "dark", "green"],
787
- value="dark",
788
- label="Theme",
789
- interactive=True,
790
- )
791
- gr.Markdown(
792
- "- Standard mode: **12 threads** (`10 fetch`, `2 parse`)\n"
793
- "- Super mode: **24 threads** (`20 fetch`, `4 parse`)"
794
- )
795
-
796
- with gr.Row():
797
- with gr.Column(scale=2):
798
- seed_urls_table = gr.Dataframe(
799
- headers=["seed_url"],
800
- datatype=["str"],
801
- row_count=(8, "dynamic"),
802
- value=default_seed_rows,
803
- interactive=True,
804
- label="Seed URL List (editable)",
805
- )
806
- seed_widget_html = gr.HTML(
807
- label="Seed URL Summary",
808
- value=render_seed_widget_html(default_seed_rows),
809
- )
810
- token_widget_html = gr.HTML(
811
- label="Live Tokenization",
812
- value=render_tokenization_widget_html({}),
813
- )
814
-
815
- with gr.Column(scale=1):
816
- shard_size_rows = gr.Slider(
817
- label=f"Shard Size Rows (max {MAX_SHARD_ROWS})",
818
- minimum=100,
819
- maximum=MAX_SHARD_ROWS,
820
- step=100,
821
- value=min(defaults.shard_size_rows, MAX_SHARD_ROWS),
822
- )
823
- max_links_per_page = gr.Slider(
824
- label="Max Links Per Page",
825
- minimum=10,
826
- maximum=1000,
827
- step=10,
828
- value=defaults.max_links_per_page,
829
- )
830
- request_timeout_seconds = gr.Slider(
831
- label="Request Timeout (seconds)",
832
- minimum=3,
833
- maximum=60,
834
- step=1,
835
- value=defaults.request_timeout_seconds,
836
- )
837
- max_response_bytes = gr.Slider(
838
- label="Max Response Bytes",
839
- minimum=500_000,
840
- maximum=8_000_000,
841
- step=100_000,
842
- value=defaults.max_response_bytes,
843
- )
844
-
845
- with gr.Accordion("Hugging Face Upload", open=False):
846
- enable_hf_upload = gr.Checkbox(
847
- label="Upload shards to my HF repo",
848
- value=False,
849
- )
850
- hf_repo_id = gr.Textbox(
851
- label="HF Repo ID",
852
- placeholder="username/dataset-name",
853
- visible=False,
854
- )
855
- hf_token = gr.Textbox(
856
- label="HF Token (write permissions)",
857
- type="password",
858
- placeholder="hf_xxx",
859
- visible=False,
860
- )
861
- hf_private_repo = gr.Checkbox(
862
- label="Private HF Repo",
863
- value=False,
864
- visible=False,
865
- )
866
- hf_path_prefix = gr.Textbox(
867
- label="HF Path Prefix",
868
- value="crawl_shards",
869
- visible=False,
870
- )
871
-
872
- with gr.Row():
873
- start_button = gr.Button("Start Crawl (12 Threads)", variant="primary")
874
- super_button = gr.Button("Super Mode (24 Threads)", variant="primary")
875
- stop_button = gr.Button("Stop Crawl", variant="stop")
876
- refresh_button = gr.Button("Refresh")
877
-
878
- status_md = gr.Markdown("### Crawler Status\n- Run ID: `0`\n- Running: `False`")
879
- qvp_md = gr.Markdown("### Live Metrics\n- Queue: `0`\n- Visited: `0`\n- Parsed: `0`")
880
- logs_box = gr.Textbox(label="Run Log", lines=12, interactive=False)
881
-
882
- start_inputs = [
883
- seed_urls_table,
884
- max_links_per_page,
885
- request_timeout_seconds,
886
- max_response_bytes,
887
- shard_size_rows,
888
- enable_hf_upload,
889
- hf_repo_id,
890
- hf_token,
891
- hf_private_repo,
892
- hf_path_prefix,
893
- ]
894
- outputs = [status_md, qvp_md, logs_box, token_widget_html]
895
-
896
- start_button.click(start_crawl_standard, inputs=start_inputs, outputs=outputs)
897
- super_button.click(start_crawl_super, inputs=start_inputs, outputs=outputs)
898
- stop_button.click(stop_crawl, inputs=[], outputs=outputs)
899
- refresh_button.click(poll_dashboard, inputs=[], outputs=outputs)
900
-
901
- enable_hf_upload.change(
902
- toggle_hf_fields,
903
- inputs=enable_hf_upload,
904
- outputs=[hf_repo_id, hf_token, hf_private_repo, hf_path_prefix],
905
- )
906
-
907
- seed_urls_table.change(
908
- fn=None,
909
- inputs=[seed_urls_table],
910
- outputs=[seed_widget_html],
911
- js=SEED_WIDGET_JS,
912
- )
913
-
914
- theme_name.change(fn=None, inputs=theme_name, outputs=[], js=THEME_JS)
915
- demo.load(
916
- fn=None,
917
- inputs=[],
918
- outputs=[],
919
- js='() => { document.documentElement.setAttribute("data-crawler-theme", "dark"); }',
920
- )
921
- demo.load(
922
- fn=None,
923
- inputs=[seed_urls_table],
924
- outputs=[seed_widget_html],
925
- js=SEED_WIDGET_JS,
926
- )
927
- demo.load(fn=poll_dashboard, inputs=[], outputs=outputs)
928
-
929
- timer = gr.Timer(value=1.0)
930
- timer.tick(fn=poll_dashboard, inputs=[], outputs=outputs)
931
-
932
- return demo
933
-
934
-
935
- demo = build_ui()
936
-
937
-
938
- def main() -> None:
939
- demo.queue(default_concurrency_limit=32).launch()
940
-
941
-
942
- if __name__ == "__main__":
943
- main()