#!/usr/bin/env python3 """ Fast Vietnamese Legal Corpus Downloader Uses Playwright with concurrent downloads """ import re import sqlite3 import asyncio from pathlib import Path from datetime import datetime import click from rich.console import Console from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn console = Console() DATA_DIR = Path(__file__).parent.parent / "data" DB_PATH = Path(__file__).parent.parent / "vietnam_laws.sqlite" def slugify(text: str) -> str: vietnamese_map = { 'à': 'a', 'á': 'a', 'ả': 'a', 'ã': 'a', 'ạ': 'a', 'ă': 'a', 'ằ': 'a', 'ắ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ặ': 'a', 'â': 'a', 'ầ': 'a', 'ấ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ậ': 'a', 'đ': 'd', 'è': 'e', 'é': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ẹ': 'e', 'ê': 'e', 'ề': 'e', 'ế': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e', 'ì': 'i', 'í': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ị': 'i', 'ò': 'o', 'ó': 'o', 'ỏ': 'o', 'õ': 'o', 'ọ': 'o', 'ô': 'o', 'ồ': 'o', 'ố': 'o', 'ổ': 'o', 'ỗ': 'o', 'ộ': 'o', 'ơ': 'o', 'ờ': 'o', 'ớ': 'o', 'ở': 'o', 'ỡ': 'o', 'ợ': 'o', 'ù': 'u', 'ú': 'u', 'ủ': 'u', 'ũ': 'u', 'ụ': 'u', 'ư': 'u', 'ừ': 'u', 'ứ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u', 'ỳ': 'y', 'ý': 'y', 'ỷ': 'y', 'ỹ': 'y', 'ỵ': 'y', } text = text.lower() for viet, ascii_char in vietnamese_map.items(): text = text.replace(viet, ascii_char) text = re.sub(r'[^a-z0-9]+', '-', text) return text.strip('-') def get_laws_from_db() -> list[dict]: if not DB_PATH.exists(): return [] conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row cursor = conn.cursor() laws = [] cursor.execute("SELECT * FROM codes") for row in cursor.fetchall(): laws.append({ "type": "code", "name": row["name"], "name_vi": row["name_vi"], "year": row["year"], "document_number": row["document_number"], "effective_date": row["effective_date"], "status": row["status"], }) cursor.execute("SELECT * FROM laws") for row in cursor.fetchall(): laws.append({ "type": "law", "name": row["name"], "name_vi": row["name_vi"], "year": row["year"], "document_number": row["document_number"], "effective_date": row["effective_date"], "status": row["status"], }) conn.close() return laws def get_filepath(law: dict) -> Path: law_type = law.get("type", "law") year = law.get("year", "unknown") name_vi = law.get("name_vi", law.get("name", "unknown")) slug = slugify(name_vi) prefix = "code" if law_type == "code" else "law" return DATA_DIR / f"{prefix}-{year}-{slug}.md" def needs_download(law: dict) -> bool: filepath = get_filepath(law) if not filepath.exists(): return True # Check if file has content (> 1KB) return filepath.stat().st_size < 1000 def save_law_file(law: dict, content: str | None = None, url: str | None = None): DATA_DIR.mkdir(parents=True, exist_ok=True) filepath = get_filepath(law) lines = ["---"] lines.append(f"title: {law.get('name_vi', law.get('name'))}") if law.get("name"): lines.append(f"title_en: {law['name']}") lines.append(f"type: {law.get('type', 'law')}") lines.append(f"year: {law.get('year')}") if law.get("document_number"): lines.append(f"document_number: {law['document_number']}") if law.get("effective_date"): lines.append(f"effective_date: {law['effective_date']}") lines.append(f"status: {law.get('status', 'Active')}") if url: lines.append(f'url: "{url}"') lines.append(f'downloaded_at: "{datetime.now().isoformat()}"') lines.append("---\n") md = "\n".join(lines) md += f"\n# {law.get('name_vi', law.get('name'))}\n\n" if law.get("document_number"): md += f"**Số hiệu:** {law['document_number']}\n\n" if content: md += "---\n\n" + content else: md += "*Nội dung chưa được tải xuống.*\n" filepath.write_text(md, encoding="utf-8") async def download_law(page, law: dict, semaphore: asyncio.Semaphore) -> bool: async with semaphore: name = law.get("name_vi", "") doc_num = law.get("document_number", "") try: # Search for law keyword = doc_num if doc_num else name search_url = f"https://thuvienphapluat.vn/page/tim-van-ban.aspx?keyword={keyword}" await page.goto(search_url, wait_until="domcontentloaded", timeout=15000) await asyncio.sleep(0.5) # Find first result link = await page.query_selector("a[href*='/van-ban/']") if not link: save_law_file(law, None, None) return False url = await link.get_attribute("href") if not url.startswith("http"): url = f"https://thuvienphapluat.vn{url}" # Go to law page await page.goto(url, wait_until="domcontentloaded", timeout=15000) await asyncio.sleep(0.5) # Extract content content = None content_elem = await page.query_selector(".content1, .toanvancontent, .fulltext, #toanvancontent") if content_elem: content = await content_elem.inner_text() save_law_file(law, content, url) return True except Exception as e: save_law_file(law, None, None) return False async def run_downloads(laws: list[dict], concurrency: int = 5): from playwright.async_api import async_playwright async with async_playwright() as p: browser = await p.chromium.launch(headless=True) semaphore = asyncio.Semaphore(concurrency) # Create multiple pages pages = [] for _ in range(concurrency): context = await browser.new_context( user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36" ) page = await context.new_page() pages.append(page) success = 0 with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(), TaskProgressColumn(), console=console, ) as progress: task = progress.add_task("Downloading...", total=len(laws)) # Process in batches for i in range(0, len(laws), concurrency): batch = laws[i:i + concurrency] tasks = [] for j, law in enumerate(batch): page = pages[j % len(pages)] tasks.append(download_law(page, law, semaphore)) results = await asyncio.gather(*tasks, return_exceptions=True) for r in results: if r is True: success += 1 progress.advance(task) progress.update(task, description=f"[cyan]Downloaded: {success}/{len(laws)}[/cyan]") await browser.close() return success @click.command() @click.option("--concurrency", default=5, help="Number of concurrent downloads") @click.option("--skip-existing", is_flag=True, help="Skip files that already have content") def download(concurrency: int, skip_existing: bool): """Fast parallel download of Vietnamese laws.""" console.print("[bold blue]VLC Fast Downloader[/bold blue]\n") laws = get_laws_from_db() if not laws: console.print("[yellow]No laws in database[/yellow]") return if skip_existing: laws = [l for l in laws if needs_download(l)] console.print(f"[yellow]Skipping already downloaded files[/yellow]") console.print(f"Downloading [green]{len(laws)}[/green] laws (concurrency: {concurrency})") console.print(f"Output: [cyan]{DATA_DIR}[/cyan]\n") success = asyncio.run(run_downloads(laws, concurrency)) console.print(f"\n[green]Done![/green] Successfully downloaded: {success}/{len(laws)}") if __name__ == "__main__": download()