Spaces:
Sleeping
Sleeping
Download src/coveragecheck/ingest/download.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 8.93 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/ingest/download.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/ingest/download.py
-
curl -L -o download.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/ingest/download.py
8.93 kB
| """Step 1: make sure every document in data/manifest.csv is present in data/raw/. | |
| - fetch=manual rows are not downloaded: both FSRA and e-Laws refuse automated | |
| requests (403 / bot check), so the script tells you which file to fetch by hand. | |
| e-Laws laws were downloaded as Word .doc and converted once to .docx with | |
| LibreOffice (Docling can't read .doc without it); the originals stay in | |
| data/raw/originals/ and are verified too. | |
| - fetch=auto rows are downloaded with a plain, honestly-labelled HTTP request and a | |
| 1-second delay between requests (e-Laws' robots.txt crawl delay). | |
| - Every file's SHA-256 is recorded in the manifest the first time it is seen, and | |
| checked on later runs. That pins the exact bytes the evals were built on. | |
| Run: uv run python -m coveragecheck.ingest.download | |
| """ | |
| import csv | |
| import hashlib | |
| import io | |
| import re | |
| import sys | |
| import time | |
| import zipfile | |
| from collections.abc import Callable | |
| from datetime import date, datetime | |
| from pathlib import Path | |
| import httpx | |
| import pymupdf | |
| from coveragecheck import config | |
| USER_AGENT = "coveragecheck/0.1 (portfolio research project; public-documents only)" | |
| CRAWL_DELAY_SECONDS = 1.0 | |
| PROBLEM_STATUSES = {"MISSING", "INVALID", "MISMATCH"} | |
| # A "fetcher" takes a URL and returns the response body. Real runs use http_get; | |
| # tests pass a fake one so they never touch the network. | |
| Fetcher = Callable[[str], bytes] | |
| def read_manifest(path: Path) -> list[dict[str, str]]: | |
| """Load the manifest as a list of rows (one dict per document). | |
| utf-8-sig also accepts the invisible "BOM" marker Excel adds when saving a CSV. | |
| """ | |
| with path.open(newline="", encoding="utf-8-sig") as f: | |
| return list(csv.DictReader(f)) | |
| def write_manifest(path: Path, rows: list[dict[str, str]]) -> None: | |
| """Save rows back to the manifest, keeping the original column order.""" | |
| with path.open("w", newline="", encoding="utf-8") as f: | |
| writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()), lineterminator="\n") | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def sha256_bytes(data: bytes) -> str: | |
| """Fingerprint of the file contents: any change to the bytes changes it.""" | |
| return hashlib.sha256(data).hexdigest() | |
| def law_text(filename: str, data: bytes) -> bytes | None: | |
| """Return the searchable text layer of an e-Laws file, or None if unreadable. | |
| A .docx is a zip archive; its body text lives in word/document.xml, where Word | |
| splits sentences into formatting "runs" separated by XML tags, so we strip the | |
| tags to get searchable text back. An .html file is used as-is. | |
| """ | |
| if Path(filename).suffix.lower() == ".docx": | |
| try: | |
| with zipfile.ZipFile(io.BytesIO(data)) as z: | |
| xml = z.read("word/document.xml") | |
| except (zipfile.BadZipFile, KeyError): | |
| return None | |
| return re.sub(rb"<[^>]+>", b"", xml) | |
| return data | |
| def pdf_opens(data: bytes) -> bool: | |
| """True if the bytes are a complete PDF that opens and has pages. | |
| A complete PDF starts with "%PDF" and ends with an "%%EOF" marker; a cut-off | |
| download loses the marker. (Opening alone isn't enough: PyMuPDF silently | |
| repairs truncated files.) | |
| """ | |
| if not data.startswith(b"%PDF") or b"%%EOF" not in data[-1024:]: | |
| return False | |
| try: | |
| with pymupdf.open(stream=data, filetype="pdf") as doc: | |
| return doc.page_count > 0 | |
| except Exception: # pymupdf raises several error types for corrupt files | |
| return False | |
| def looks_valid(filename: str, data: bytes) -> bool: | |
| """Reject obviously wrong files (error pages, bot challenges, wrong formats).""" | |
| suffix = Path(filename).suffix.lower() | |
| if suffix == ".pdf": | |
| return pdf_opens(data) | |
| if suffix == ".doc": | |
| return False # legacy Word: convert to .docx first (see module docstring) | |
| # e-Laws laws (.docx or .html): size is not a reliable signal (bot-challenge | |
| # pages are ~50 KB), but every real law states its consolidation period. | |
| text = law_text(filename, data) | |
| return text is not None and consolidation_start(text) is not None | |
| def consolidation_start(text: bytes) -> date | None: | |
| """Find the date an e-Laws text version starts applying. | |
| Current pages say "Consolidation Period: From July 1, 2026 ..."; | |
| point-in-time pages say "... period July 1, 2025 to June 30, 2026". | |
| """ | |
| decoded = text.decode("utf-8", errors="ignore") | |
| for pattern in ( | |
| r"Consolidation Period:\s*From\s+([A-Z][a-z]+ \d{1,2}, \d{4})", | |
| r"period\s+([A-Z][a-z]+ \d{1,2}, \d{4}) to ", | |
| ): | |
| m = re.search(pattern, decoded) | |
| if m: | |
| return datetime.strptime(m.group(1), "%B %d, %Y").date() | |
| return None | |
| def http_get(url: str) -> bytes: | |
| """Download one URL, identifying ourselves honestly, and fail on HTTP errors.""" | |
| response = httpx.get(url, headers={"User-Agent": USER_AGENT}, follow_redirects=True, timeout=60) | |
| response.raise_for_status() | |
| return response.content | |
| def check_original(row: dict[str, str], raw_dir: Path) -> tuple[str, str] | None: | |
| """For converted files, verify the untouched original download is still intact.""" | |
| if not row.get("original_filename"): | |
| return None | |
| path = raw_dir / row["original_filename"] | |
| if not path.exists(): | |
| return "MISSING", f"original {row['original_filename']} is gone; re-download it" | |
| if sha256_bytes(path.read_bytes()) != row["original_sha256"]: | |
| return "MISMATCH", f"original {row['original_filename']} differs from its sha256" | |
| return None | |
| def process_row(row: dict[str, str], raw_dir: Path, fetch: Fetcher) -> tuple[str, str]: | |
| """Ensure one document is on disk and matches its recorded hash. | |
| Returns (status, detail). Updates the row in place when it records a new | |
| hash or download date. Statuses: ok, downloaded, MISSING, INVALID, MISMATCH. | |
| """ | |
| path = raw_dir / row["filename"] | |
| if path.exists(): | |
| data = path.read_bytes() | |
| if not looks_valid(path.name, data): | |
| return "INVALID", "file on disk is not a valid document; delete it and rerun" | |
| status = "ok" | |
| elif row["fetch"] == "auto": | |
| data = fetch(row["url"]) | |
| if not looks_valid(path.name, data): | |
| return "INVALID", ( | |
| f"server returned a non-document page ({len(data)} bytes, likely a bot " | |
| f"check); save {row['url']} from a browser as {path.name}" | |
| ) | |
| status = "downloaded" | |
| else: | |
| return "MISSING", f"download by hand from {row['url']} and save as {path.name}" | |
| # Compare fingerprints BEFORE saving, so changed upstream bytes never land on disk. | |
| digest = sha256_bytes(data) | |
| if row["sha256"] and row["sha256"] != digest: | |
| return "MISMATCH", "contents differ from the recorded sha256" | |
| if status == "downloaded": | |
| path.write_bytes(data) | |
| row["downloaded_on"] = date.today().isoformat() | |
| row["sha256"] = digest # no-op when already recorded; pins it on first sighting | |
| original_problem = check_original(row, raw_dir) | |
| if original_problem: | |
| return original_problem | |
| detail = "" | |
| if path.suffix.lower() != ".pdf" and row["effective_from"]: | |
| start = consolidation_start(law_text(path.name, data) or b"") | |
| if start and start.isoformat() != row["effective_from"]: | |
| detail = f"warning: text now starts {start}, manifest says {row['effective_from']}" | |
| return status, detail | |
| def run(manifest: Path, raw_dir: Path, fetch: Fetcher, delay: float) -> int: | |
| """Process every manifest row, print a table, save new hashes; return exit code.""" | |
| raw_dir.mkdir(parents=True, exist_ok=True) | |
| rows = read_manifest(manifest) | |
| problems = 0 | |
| changed = False | |
| print(f"{'doc_id':<18} {'status':<11} {'size':>9} {'sha256':<12} detail") | |
| for row in rows: | |
| before = dict(row) | |
| needs_network = row["fetch"] == "auto" and not (raw_dir / row["filename"]).exists() | |
| try: | |
| status, detail = process_row(row, raw_dir, fetch) | |
| except httpx.HTTPError as e: | |
| status, detail = "INVALID", f"request failed: {e}" | |
| if needs_network: | |
| time.sleep(delay) # e-Laws crawl delay | |
| changed |= row != before | |
| path = raw_dir / row["filename"] | |
| size = f"{path.stat().st_size / 1024:,.0f} KB" if path.exists() else "-" | |
| print(f"{row['doc_id']:<18} {status:<11} {size:>9} {row['sha256'][:12]:<12} {detail}") | |
| problems += status in PROBLEM_STATUSES | |
| if changed: # a verify-only run leaves the file (and git status) untouched | |
| write_manifest(manifest, rows) | |
| print(f"\n{len(rows) - problems}/{len(rows)} documents ready.") | |
| return 1 if problems else 0 | |
| def main() -> None: | |
| sys.exit(run(config.MANIFEST_PATH, config.RAW_DIR, http_get, CRAWL_DELAY_SECONDS)) | |
| if __name__ == "__main__": | |
| main() | |