import asyncio import gzip import os import threading import time import uuid from pathlib import Path import aiohttp import gradio as gr # Configuration DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) OUTPUT_FILE = DATA_DIR / "pure_web_text.txt" STATE_FILE = DATA_DIR / "downloaded_segments.log" ERROR_FILE = DATA_DIR / "download_errors.log" MAX_CONCURRENT = 4 MAX_ARCHIVES_PER_RUN = 10 RETRIES = 3 TIMEOUT_SECONDS = 180 DATA_DIR.mkdir(parents=True, exist_ok=True) metrics = { "status": "Idle", "total": 0, "completed": 0, "failed": 0, "lines": 0, "bytes": 0, "started": 0.0, "running": False, } metrics_lock = threading.Lock() start_lock = threading.Lock() # Thread-safe metrics helpers def update_metrics(**values): with metrics_lock: metrics.update(values) def increment_metric(key, amount=1): with metrics_lock: metrics[key] += amount def get_metrics(): with metrics_lock: result = metrics.copy() elapsed = max(time.time() - result["started"], 0.001) if result["started"] else 0.0 result["speed"] = (result["bytes"] / elapsed / (1024 * 1024)) if result["started"] else 0.0 return result # Common Crawl discovery async def discover_crawl(session): url = "https://index.commoncrawl.org/collinfo.json" async with session.get(url) as response: response.raise_for_status() catalog = await response.json(content_type=None) if not isinstance(catalog, list) or not catalog: raise RuntimeError("The Common Crawl catalog is empty.") for item in catalog: crawl_id = item.get("id") if crawl_id: manifest = item.get("wet.paths") if not manifest: manifest = ( "https://data.commoncrawl.org/" f"crawl-data/{crawl_id}/wet.paths.gz" ) elif not manifest.startswith("https://"): manifest = "https://data.commoncrawl.org/" + manifest.lstrip("/") return crawl_id, manifest raise RuntimeError("No valid crawl was found.") # Download a limited number of manifest entries async def load_manifest(session, manifest_url): manifest_path = DATA_DIR / "wet.paths.gz" async with session.get(manifest_url) as response: response.raise_for_status() with open(manifest_path, "wb") as output: async for chunk in response.content.iter_chunked(65536): output.write(chunk) paths = [] with gzip.open( manifest_path, "rt", encoding="utf-8", errors="replace", ) as source: for line in source: path = line.strip() if path: paths.append(path) if len(paths) >= MAX_ARCHIVES_PER_RUN: break return [ path if path.startswith("https://") else "https://data.commoncrawl.org/" + path.lstrip("/") for path in paths ] # Resume support def load_completed(): if not STATE_FILE.exists(): return set() with open(STATE_FILE, "r", encoding="utf-8") as source: return {line.strip() for line in source if line.strip()} def log_error(url, error): with open(ERROR_FILE, "a", encoding="utf-8") as output: output.write(f"{time.time()} | {url} | {error}\n") # Basic line filter def useful_line(line): line = line.strip() if len(line) < 40: return False if line.startswith(("WARC/", "Content-", "HTTP/")): return False return True # Download and extract a WET archive async def process_archive( url, session, semaphore, output_lock, state_lock, ): for attempt in range(RETRIES): temp_path = DATA_DIR / f"archive_{uuid.uuid4().hex}.gz" try: async with semaphore: downloaded = 0 async with session.get(url) as response: response.raise_for_status() with open(temp_path, "wb") as output: async for chunk in response.content.iter_chunked(65536): output.write(chunk) downloaded += len(chunk) increment_metric("bytes", downloaded) saved_lines = 0 batch = [] with gzip.open( temp_path, "rt", encoding="utf-8", errors="replace", ) as source: for line in source: if useful_line(line): batch.append(line.strip()) if len(batch) >= 200: async with output_lock: with open( OUTPUT_FILE, "a", encoding="utf-8", ) as output: output.write("\n".join(batch) + "\n") saved_lines += len(batch) batch.clear() if batch: async with output_lock: with open( OUTPUT_FILE, "a", encoding="utf-8", ) as output: output.write("\n".join(batch) + "\n") saved_lines += len(batch) increment_metric("lines", saved_lines) async with state_lock: with open(STATE_FILE, "a", encoding="utf-8") as state: state.write(url + "\n") increment_metric("completed") return except Exception as exc: if attempt == RETRIES - 1: increment_metric("failed") log_error(url, repr(exc)) return await asyncio.sleep(2 ** attempt) finally: try: temp_path.unlink(missing_ok=True) except OSError: pass # Main pipeline async def run_pipeline(): update_metrics( status="Discovering Common Crawl...", total=0, completed=0, failed=0, lines=0, bytes=0, started=time.time(), ) timeout = aiohttp.ClientTimeout(total=TIMEOUT_SECONDS) connector = aiohttp.TCPConnector( limit=MAX_CONCURRENT, ttl_dns_cache=300, ) async with aiohttp.ClientSession( timeout=timeout, connector=connector, headers={"User-Agent": "CommonCrawlTextCollector/1.0"}, ) as session: crawl_id, manifest_url = await discover_crawl(session) update_metrics(status=f"Loading manifest for {crawl_id}...") targets = await load_manifest(session, manifest_url) completed_urls = load_completed() pending = [url for url in targets if url not in completed_urls] update_metrics( total=len(targets), completed=len(targets) - len(pending), status=f"Processing {len(pending)} archives...", ) if not pending: update_metrics(status="All selected archives are complete.") return semaphore = asyncio.Semaphore(MAX_CONCURRENT) output_lock = asyncio.Lock() state_lock = asyncio.Lock() queue = asyncio.Queue() for url in pending: queue.put_nowait(url) async def worker(): while True: try: url = queue.get_nowait() except asyncio.QueueEmpty: return try: await process_archive( url, session, semaphore, output_lock, state_lock, ) finally: queue.task_done() await asyncio.gather( *(worker() for _ in range(min(MAX_CONCURRENT, len(pending)))) ) result = get_metrics() update_metrics( status=( f"Finished crawl {crawl_id}. " f"Completed: {result['completed']}; " f"failed: {result['failed']}." ) ) # Background execution def background_worker(): try: asyncio.run(run_pipeline()) except Exception as exc: log_error("PIPELINE", repr(exc)) update_metrics(status=f"Pipeline error: {exc}") finally: update_metrics(running=False) def start_pipeline(): with start_lock: if get_metrics()["running"]: return "The pipeline is already running." update_metrics( running=True, status="Starting pipeline...", ) thread = threading.Thread( target=background_worker, daemon=True, ) thread.start() return "Started. Progress will update automatically." # Dashboard def refresh_dashboard(): data = get_metrics() total = data["total"] completed = data["completed"] percentage = completed * 100 / total if total else 0 return ( data["status"], f"{completed}/{total} ({percentage:.1f}%)", str(data["failed"]), f"{data['lines']:,}", f"{data['speed']:.2f} MB/s", ) with gr.Blocks() as demo: gr.Markdown("# Common Crawl Text Collector") gr.Markdown("A small test collector for Common Crawl WET archives.") start_button = gr.Button( "Start / Resume", variant="primary", ) status = gr.Textbox(label="Status", value="Idle") progress = gr.Textbox(label="Archives Completed", value="0/0") failures = gr.Textbox(label="Failed Archives", value="0") lines = gr.Textbox(label="Text Lines Saved", value="0") speed = gr.Textbox(label="Download Speed", value="0 MB/s") start_button.click( fn=start_pipeline, outputs=status, ) timer = gr.Timer(value=2) timer.tick( fn=refresh_dashboard, outputs=[status, progress, failures, lines, speed], ) if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")), theme=gr.themes.Soft(), )