Wave2 scrapers_and_normalizers overlay for US Code collectors/verifiers
Browse files- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir_scripts/normalize_country_laws.py +44 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/us_code_scraper.py +2136 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/us_code_verifier.py +392 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/uscode_release_catalog.py +2022 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/uscode_release_processor.py +1539 -0
- scrapers_and_normalizers/scripts/scrapers/legal/us_code_scraper.py +7 -0
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir_scripts/normalize_country_laws.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Normalize a country-law source into a CID-keyed corpus report (no GraphRAG, no upload)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
sys.path.insert(0, str(ROOT))
|
| 13 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 14 |
+
|
| 15 |
+
from country_laws_ir.build import CACHE, REPORTS # noqa: E402
|
| 16 |
+
from country_laws_ir.catalog import get_country # noqa: E402
|
| 17 |
+
from country_laws_ir.normalize import build_corpus, load_source # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main() -> int:
|
| 21 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 22 |
+
ap.add_argument("--source-repo", "--source", dest="source", default="endomorphosis/ipfs_malta_laws")
|
| 23 |
+
ap.add_argument("--out", default=None)
|
| 24 |
+
args = ap.parse_args()
|
| 25 |
+
country = get_country(args.source)
|
| 26 |
+
laws, articles, source_meta = load_source(country["repo"], CACHE)
|
| 27 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 28 |
+
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 29 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 31 |
+
print(json.dumps({
|
| 32 |
+
"out": str(out),
|
| 33 |
+
"n_out": int(len(corpus)),
|
| 34 |
+
"unit": report["unit"],
|
| 35 |
+
"drops": report["drops"],
|
| 36 |
+
"language_breakdown": report.get("language_breakdown"),
|
| 37 |
+
"quality_flags": report.get("quality_flags"),
|
| 38 |
+
"schema_surprises": report.get("schema_surprises"),
|
| 39 |
+
}, indent=2, ensure_ascii=False))
|
| 40 |
+
return 0
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
raise SystemExit(main())
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/us_code_scraper.py
ADDED
|
@@ -0,0 +1,2136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""US Code scraper for building federal statutory law datasets.
|
| 2 |
+
|
| 3 |
+
This module downloads and parses title packages from GovInfo package endpoints,
|
| 4 |
+
producing section-level records suitable for full U.S. Code ingestion.
|
| 5 |
+
|
| 6 |
+
Official sources (in order):
|
| 7 |
+
1. GovInfo public content ZIP
|
| 8 |
+
2. GovInfo package API ``zipLink`` (same method as Vaquill-AI/open-us-law)
|
| 9 |
+
3. U.S. House OLRC releasepoint HTM ZIP
|
| 10 |
+
|
| 11 |
+
Recovery-only fallbacks (not legal authority): Wayback CDX raw captures and,
|
| 12 |
+
when enabled, Common Crawl. Archive.is is HTML-oriented and is not used for
|
| 13 |
+
binary ZIP packages.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import time
|
| 21 |
+
import zipfile
|
| 22 |
+
from datetime import datetime
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
| 25 |
+
from urllib.parse import urljoin
|
| 26 |
+
from xml.etree import ElementTree as ET
|
| 27 |
+
|
| 28 |
+
import anyio
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
import requests
|
| 32 |
+
from bs4 import BeautifulSoup
|
| 33 |
+
|
| 34 |
+
REQUESTS_AVAILABLE = True
|
| 35 |
+
except ImportError:
|
| 36 |
+
REQUESTS_AVAILABLE = False
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
DEFAULT_USCODE_CACHE_DIR = Path.home() / ".ipfs_datasets" / "us_code" / "cache"
|
| 41 |
+
DEFAULT_USCODE_INDEX_DIR = Path.home() / ".ipfs_datasets" / "us_code"
|
| 42 |
+
DEFAULT_USCODE_INDEX_PATH = DEFAULT_USCODE_INDEX_DIR / "uscode_index_latest.jsonl"
|
| 43 |
+
DEFAULT_USCODE_JSONLD_DIRNAME = "uscode_jsonld"
|
| 44 |
+
MIN_USCODE_YEAR = 1994
|
| 45 |
+
USER_AGENT = "ipfs-datasets-uscode-scraper/2.0"
|
| 46 |
+
DEFAULT_USCODE_DOWNLOAD_RETRIES = 4
|
| 47 |
+
DEFAULT_USCODE_YEAR_FALLBACKS = 8
|
| 48 |
+
DEFAULT_USHOUSE_RELEASE_MAX_PROBE = 220
|
| 49 |
+
GOVINFO_API_BASE = "https://api.govinfo.gov"
|
| 50 |
+
WAYBACK_CDX_URL = "https://web.archive.org/cdx/search/cdx"
|
| 51 |
+
OFFICIAL_ZIP_SOURCES = (
|
| 52 |
+
"govinfo-content-zip",
|
| 53 |
+
"govinfo-api-ziplink",
|
| 54 |
+
"ushouse-releasepoint-htm-zip",
|
| 55 |
+
)
|
| 56 |
+
RECOVERY_ZIP_SOURCES = ("wayback-cdx", "common_crawl")
|
| 57 |
+
SUBSEC_TOKEN_RE = re.compile(r"\(([0-9]+|[A-Za-z]{1,6})\)")
|
| 58 |
+
ROMAN_LOWER_RE = re.compile(r"^[ivxlcdm]+$")
|
| 59 |
+
ROMAN_UPPER_RE = re.compile(r"^[IVXLCDM]+$")
|
| 60 |
+
COMMON_ROMAN_LOWER = {
|
| 61 |
+
"i",
|
| 62 |
+
"ii",
|
| 63 |
+
"iii",
|
| 64 |
+
"iv",
|
| 65 |
+
"v",
|
| 66 |
+
"vi",
|
| 67 |
+
"vii",
|
| 68 |
+
"viii",
|
| 69 |
+
"ix",
|
| 70 |
+
"x",
|
| 71 |
+
"xi",
|
| 72 |
+
"xii",
|
| 73 |
+
"xiii",
|
| 74 |
+
"xiv",
|
| 75 |
+
"xv",
|
| 76 |
+
}
|
| 77 |
+
COMMON_ROMAN_UPPER = {token.upper() for token in COMMON_ROMAN_LOWER}
|
| 78 |
+
CHAPTER_RE = re.compile(
|
| 79 |
+
r"\b(CHAPTER\s+[A-Z0-9\-]+)\s*[\-—]\s*(.+?)(?=\s+Sec\.|\s+§|$)", re.IGNORECASE
|
| 80 |
+
)
|
| 81 |
+
SUBCHAPTER_RE = re.compile(
|
| 82 |
+
r"\b(SUBCHAPTER\s+[A-Z0-9\-]+)\s*[\-—]\s*(.+?)(?=\s+Sec\.|\s+§|$)", re.IGNORECASE
|
| 83 |
+
)
|
| 84 |
+
PART_RE = re.compile(r"\b(PART\s+[A-Z0-9\-]+)\s*[\-—]\s*(.+?)(?=\s+Sec\.|\s+§|$)", re.IGNORECASE)
|
| 85 |
+
PUBLIC_LAW_CITATION_RE = re.compile(
|
| 86 |
+
r"Pub\.?\s*L\.?\s*(?:No\.?\s*)?\d+\s*[–—−‑-]\s*\d+", re.IGNORECASE
|
| 87 |
+
)
|
| 88 |
+
PUBLIC_LAW_LONGFORM_RE = re.compile(
|
| 89 |
+
r"Public\s+Law\s+(?:No\.?\s*)?\d+\s*[–—−‑-]\s*\d+", re.IGNORECASE
|
| 90 |
+
)
|
| 91 |
+
PUBLIC_LAW_CONGRESS_RE = re.compile(
|
| 92 |
+
r"Public\s+Law\s+\d+\s*,\s*[A-Za-z][A-Za-z\-\s]{1,80}\s+Congress", re.IGNORECASE
|
| 93 |
+
)
|
| 94 |
+
STAT_CITATION_RE = re.compile(r"\b\d+\s+Stat\.?\s+\d+\b", re.IGNORECASE)
|
| 95 |
+
USC_CITATION_RE = re.compile(
|
| 96 |
+
r"\b\d+\s+U\.?\s*S\.?\s*C\.?\s*(?:§+\s*|sec(?:tion)?\.?\s*)?\d[\w\-\.()]*", re.IGNORECASE
|
| 97 |
+
)
|
| 98 |
+
TITLE_SECTION_CITATION_RE = re.compile(
|
| 99 |
+
r"\bsection\s+[\w\-.()]+\s+of\s+Title\s+\d+\b", re.IGNORECASE
|
| 100 |
+
)
|
| 101 |
+
THIS_TITLE_SECTION_CITATION_RE = re.compile(
|
| 102 |
+
r"\bsection\s+[\w\-.(),\sand]+\s+of\s+this\s+title\b", re.IGNORECASE
|
| 103 |
+
)
|
| 104 |
+
THIS_CHAPTER_SECTION_CITATION_RE = re.compile(
|
| 105 |
+
r"\bsection\s+[\w\-.(),\sand]+\s+of\s+this\s+chapter\b", re.IGNORECASE
|
| 106 |
+
)
|
| 107 |
+
ACT_CITATION_RE = re.compile(r"\bAct\s+[A-Z][a-z]{2,9}\.?\s+\d{1,2},\s+\d{4}\b", re.IGNORECASE)
|
| 108 |
+
CHAPTER_STAT_CITATION_RE = re.compile(
|
| 109 |
+
r"\bch\.?\s*\d+[A-Za-z\-]*,\s*\d+\s+Stat\.?\s+\d+\b", re.IGNORECASE
|
| 110 |
+
)
|
| 111 |
+
DOCID_COMMENT_RE = re.compile(r"<!--\s*documentid:[^>]*-->", re.IGNORECASE)
|
| 112 |
+
DOCID_SECTION_KEY_RE = re.compile(r"documentid:\s*[0-9A-Za-z]+_([0-9A-Za-z._\-]+)", re.IGNORECASE)
|
| 113 |
+
USHOUSE_RELEASE_LINK_RE = re.compile(
|
| 114 |
+
r"releasepoints/us/pl/(?P<congress>\d+)/(?P<release>[A-Za-z0-9]+)/"
|
| 115 |
+
r"htm_usc(?P<title_code>[0-9]{2}[a-z]?)@(?P<tag>[0-9]+-[A-Za-z0-9]+)\\.zip",
|
| 116 |
+
re.IGNORECASE,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# US Code titles mapping
|
| 120 |
+
US_CODE_TITLES = {
|
| 121 |
+
"1": "General Provisions",
|
| 122 |
+
"2": "The Congress",
|
| 123 |
+
"3": "The President",
|
| 124 |
+
"4": "Flag and Seal, Seat of Government, and the States",
|
| 125 |
+
"5": "Government Organization and Employees",
|
| 126 |
+
"6": "Domestic Security",
|
| 127 |
+
"7": "Agriculture",
|
| 128 |
+
"8": "Aliens and Nationality",
|
| 129 |
+
"9": "Arbitration",
|
| 130 |
+
"10": "Armed Forces",
|
| 131 |
+
"11": "Bankruptcy",
|
| 132 |
+
"12": "Banks and Banking",
|
| 133 |
+
"13": "Census",
|
| 134 |
+
"14": "Coast Guard",
|
| 135 |
+
"15": "Commerce and Trade",
|
| 136 |
+
"16": "Conservation",
|
| 137 |
+
"17": "Copyrights",
|
| 138 |
+
"18": "Crimes and Criminal Procedure",
|
| 139 |
+
"19": "Customs Duties",
|
| 140 |
+
"20": "Education",
|
| 141 |
+
"21": "Food and Drugs",
|
| 142 |
+
"22": "Foreign Relations and Intercourse",
|
| 143 |
+
"23": "Highways",
|
| 144 |
+
"24": "Hospitals and Asylums",
|
| 145 |
+
"25": "Indians",
|
| 146 |
+
"26": "Internal Revenue Code",
|
| 147 |
+
"27": "Intoxicating Liquors",
|
| 148 |
+
"28": "Judiciary and Judicial Procedure",
|
| 149 |
+
"29": "Labor",
|
| 150 |
+
"30": "Mineral Lands and Mining",
|
| 151 |
+
"31": "Money and Finance",
|
| 152 |
+
"32": "National Guard",
|
| 153 |
+
"33": "Navigation and Navigable Waters",
|
| 154 |
+
"34": "Crime Control and Law Enforcement",
|
| 155 |
+
"35": "Patents",
|
| 156 |
+
"36": "Patriotic and National Observances, Ceremonies, and Organizations",
|
| 157 |
+
"37": "Pay and Allowances of the Uniformed Services",
|
| 158 |
+
"38": "Veterans' Benefits",
|
| 159 |
+
"39": "Postal Service",
|
| 160 |
+
"40": "Public Buildings, Property, and Works",
|
| 161 |
+
"41": "Public Contracts",
|
| 162 |
+
"42": "The Public Health and Welfare",
|
| 163 |
+
"43": "Public Lands",
|
| 164 |
+
"44": "Public Printing and Documents",
|
| 165 |
+
"45": "Railroads",
|
| 166 |
+
"46": "Shipping",
|
| 167 |
+
"47": "Telecommunications",
|
| 168 |
+
"48": "Territories and Insular Possessions",
|
| 169 |
+
"49": "Transportation",
|
| 170 |
+
"50": "War and National Defense",
|
| 171 |
+
"51": "National and Commercial Space Programs",
|
| 172 |
+
"52": "Voting and Elections",
|
| 173 |
+
"54": "National Park Service and Related Programs",
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
_USHOUSE_DOWNLOAD_LINKS_BY_CODE: Optional[Dict[str, str]] = None
|
| 177 |
+
_USHOUSE_RELEASE_CACHE_BY_CONGRESS: Dict[int, str] = {}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _title_sort_key(title: str) -> int:
|
| 181 |
+
try:
|
| 182 |
+
return int(str(title))
|
| 183 |
+
except Exception:
|
| 184 |
+
return 10**9
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _normalize_titles(titles: Optional[List[str]]) -> List[str]:
|
| 188 |
+
if titles is None or "all" in [str(t).lower() for t in titles]:
|
| 189 |
+
return sorted(list(US_CODE_TITLES.keys()), key=_title_sort_key)
|
| 190 |
+
out: List[str] = []
|
| 191 |
+
for value in titles:
|
| 192 |
+
key = str(value).strip()
|
| 193 |
+
if key in US_CODE_TITLES:
|
| 194 |
+
out.append(key)
|
| 195 |
+
return sorted(list(dict.fromkeys(out)), key=_title_sort_key)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _make_session() -> "requests.Session":
|
| 199 |
+
session = requests.Session()
|
| 200 |
+
session.headers.update(
|
| 201 |
+
{
|
| 202 |
+
"User-Agent": USER_AGENT,
|
| 203 |
+
"Accept": "application/zip, text/html, application/xhtml+xml;q=0.9, */*;q=0.8",
|
| 204 |
+
}
|
| 205 |
+
)
|
| 206 |
+
return session
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _govinfo_zip_url(year: int, title_num: str) -> str:
|
| 210 |
+
return (
|
| 211 |
+
f"https://www.govinfo.gov/content/pkg/USCODE-{int(year)}-title{title_num}/"
|
| 212 |
+
f"zip/USCODE-{int(year)}-title{title_num}.zip"
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _govinfo_section_url(year: int, title_num: str, html_name: str) -> str:
|
| 217 |
+
return (
|
| 218 |
+
f"https://www.govinfo.gov/content/pkg/USCODE-{int(year)}-title{title_num}/html/{html_name}"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _govinfo_api_summary_url(year: int, title_num: str) -> str:
|
| 223 |
+
return f"{GOVINFO_API_BASE}/packages/USCODE-{int(year)}-title{title_num}/summary"
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _govinfo_api_key() -> str:
|
| 227 |
+
return str(os.environ.get("GOVINFO_API_KEY") or "").strip()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _source_authority_class(source: str) -> str:
|
| 231 |
+
if source in OFFICIAL_ZIP_SOURCES:
|
| 232 |
+
return "official"
|
| 233 |
+
return "recovery"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _govinfo_api_zip_link(
|
| 237 |
+
session: "requests.Session",
|
| 238 |
+
*,
|
| 239 |
+
year: int,
|
| 240 |
+
title_num: str,
|
| 241 |
+
) -> Optional[str]:
|
| 242 |
+
"""Resolve the GovInfo package API zipLink used by Vaquill open-us-law."""
|
| 243 |
+
|
| 244 |
+
params: Dict[str, str] = {}
|
| 245 |
+
api_key = _govinfo_api_key()
|
| 246 |
+
if api_key:
|
| 247 |
+
params["api_key"] = api_key
|
| 248 |
+
try:
|
| 249 |
+
response = session.get(
|
| 250 |
+
_govinfo_api_summary_url(year, title_num),
|
| 251 |
+
params=params or None,
|
| 252 |
+
timeout=30,
|
| 253 |
+
)
|
| 254 |
+
if int(response.status_code) != 200:
|
| 255 |
+
return None
|
| 256 |
+
payload = response.json()
|
| 257 |
+
except Exception:
|
| 258 |
+
return None
|
| 259 |
+
if not isinstance(payload, dict):
|
| 260 |
+
return None
|
| 261 |
+
download = payload.get("download") if isinstance(payload.get("download"), dict) else {}
|
| 262 |
+
link = str(download.get("zipLink") or "").strip()
|
| 263 |
+
return link or None
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _wayback_raw_capture_url(timestamp: str, original: str) -> str:
|
| 267 |
+
ts = str(timestamp or "").strip()
|
| 268 |
+
original_url = str(original or "").strip()
|
| 269 |
+
return f"https://web.archive.org/web/{ts}id_/{original_url}"
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _wayback_cdx_zip_url(
|
| 273 |
+
session: "requests.Session",
|
| 274 |
+
original_url: str,
|
| 275 |
+
) -> Optional[str]:
|
| 276 |
+
"""Return a Wayback ``id_`` raw-capture URL for a GovInfo ZIP, if one exists."""
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
response = session.get(
|
| 280 |
+
WAYBACK_CDX_URL,
|
| 281 |
+
params={
|
| 282 |
+
"url": original_url,
|
| 283 |
+
"output": "json",
|
| 284 |
+
"filter": "statuscode:200",
|
| 285 |
+
"fl": "timestamp,original,mimetype",
|
| 286 |
+
"limit": "8",
|
| 287 |
+
},
|
| 288 |
+
timeout=30,
|
| 289 |
+
)
|
| 290 |
+
if int(response.status_code) != 200:
|
| 291 |
+
return None
|
| 292 |
+
rows = response.json()
|
| 293 |
+
except Exception:
|
| 294 |
+
return None
|
| 295 |
+
if not isinstance(rows, list) or len(rows) < 2:
|
| 296 |
+
return None
|
| 297 |
+
header = [str(item).lower() for item in rows[0]]
|
| 298 |
+
try:
|
| 299 |
+
ts_idx = header.index("timestamp")
|
| 300 |
+
orig_idx = header.index("original")
|
| 301 |
+
mime_idx = header.index("mimetype") if "mimetype" in header else -1
|
| 302 |
+
except ValueError:
|
| 303 |
+
ts_idx, orig_idx, mime_idx = 0, 1, 2 if len(header) > 2 else -1
|
| 304 |
+
zip_hit: Optional[Tuple[str, str]] = None
|
| 305 |
+
any_hit: Optional[Tuple[str, str]] = None
|
| 306 |
+
for row in rows[1:]:
|
| 307 |
+
if not isinstance(row, list) or len(row) <= max(ts_idx, orig_idx):
|
| 308 |
+
continue
|
| 309 |
+
timestamp = str(row[ts_idx] or "").strip()
|
| 310 |
+
original = str(row[orig_idx] or original_url).strip()
|
| 311 |
+
if not timestamp or not original:
|
| 312 |
+
continue
|
| 313 |
+
mime = str(row[mime_idx] or "").lower() if mime_idx >= 0 and len(row) > mime_idx else ""
|
| 314 |
+
hit = (timestamp, original)
|
| 315 |
+
if "zip" in mime:
|
| 316 |
+
zip_hit = hit
|
| 317 |
+
break
|
| 318 |
+
if zip_hit is None and original.lower().endswith(".zip"):
|
| 319 |
+
zip_hit = hit
|
| 320 |
+
if any_hit is None:
|
| 321 |
+
any_hit = hit
|
| 322 |
+
chosen = zip_hit or any_hit
|
| 323 |
+
if chosen is None:
|
| 324 |
+
return None
|
| 325 |
+
return _wayback_raw_capture_url(chosen[0], chosen[1])
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def iter_official_title_zip_candidates(
|
| 329 |
+
session: "requests.Session",
|
| 330 |
+
*,
|
| 331 |
+
year: int,
|
| 332 |
+
title_num: str,
|
| 333 |
+
) -> List[Dict[str, str]]:
|
| 334 |
+
"""Official ZIP locations: public content URL, then GovInfo API zipLink."""
|
| 335 |
+
|
| 336 |
+
candidates: List[Dict[str, str]] = [
|
| 337 |
+
{
|
| 338 |
+
"source": "govinfo-content-zip",
|
| 339 |
+
"url": _govinfo_zip_url(year, title_num),
|
| 340 |
+
"authority": "official",
|
| 341 |
+
}
|
| 342 |
+
]
|
| 343 |
+
api_link = _govinfo_api_zip_link(session, year=year, title_num=title_num)
|
| 344 |
+
if api_link and api_link != candidates[0]["url"]:
|
| 345 |
+
candidates.append(
|
| 346 |
+
{
|
| 347 |
+
"source": "govinfo-api-ziplink",
|
| 348 |
+
"url": api_link,
|
| 349 |
+
"authority": "official",
|
| 350 |
+
}
|
| 351 |
+
)
|
| 352 |
+
return candidates
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def iter_recovery_title_zip_candidates(
|
| 356 |
+
session: "requests.Session",
|
| 357 |
+
*,
|
| 358 |
+
year: int,
|
| 359 |
+
title_num: str,
|
| 360 |
+
) -> List[Dict[str, str]]:
|
| 361 |
+
"""Archive recovery candidates for a title ZIP. Not legal authority."""
|
| 362 |
+
|
| 363 |
+
original = _govinfo_zip_url(year, title_num)
|
| 364 |
+
candidates: List[Dict[str, str]] = []
|
| 365 |
+
wayback = _wayback_cdx_zip_url(session, original)
|
| 366 |
+
if wayback:
|
| 367 |
+
candidates.append(
|
| 368 |
+
{
|
| 369 |
+
"source": "wayback-cdx",
|
| 370 |
+
"url": wayback,
|
| 371 |
+
"authority": "recovery",
|
| 372 |
+
}
|
| 373 |
+
)
|
| 374 |
+
return candidates
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def build_uscode_section_url(title_num: str, section: str) -> str:
|
| 378 |
+
"""Build the canonical U.S. Code section URL used by recovery fuzzing."""
|
| 379 |
+
title = str(title_num or "").strip()
|
| 380 |
+
normalized_section = str(section or "").strip()
|
| 381 |
+
if not title or not normalized_section:
|
| 382 |
+
return ""
|
| 383 |
+
return f"https://uscode.house.gov/view.xhtml?req=granuleid:USC-prelim-title{title}-section{normalized_section}"
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def build_public_law_url(congress: str, law_number: str) -> str:
|
| 387 |
+
"""Build the Congress.gov public-law URL used by recovery fuzzing."""
|
| 388 |
+
normalized_congress = str(congress or "").strip()
|
| 389 |
+
normalized_law_number = str(law_number or "").strip()
|
| 390 |
+
if not normalized_congress or not normalized_law_number:
|
| 391 |
+
return ""
|
| 392 |
+
return f"https://www.congress.gov/public-law/{normalized_congress}th-congress/{normalized_law_number}"
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def _ushouse_download_page_url() -> str:
|
| 396 |
+
return "https://uscode.house.gov/download/download.shtml"
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _ushouse_title_code(title_num: str) -> str:
|
| 400 |
+
value = str(title_num or "").strip()
|
| 401 |
+
if value.isdigit():
|
| 402 |
+
return f"{int(value):02d}"
|
| 403 |
+
return value.lower()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _year_to_congress(year: int) -> int:
|
| 407 |
+
# 1st Congress started in 1789 and each Congress spans two years.
|
| 408 |
+
return int((int(year) - 1789) // 2 + 1)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _looks_like_zip_response(response: "requests.Response") -> bool:
|
| 412 |
+
try:
|
| 413 |
+
content_type = str(response.headers.get("content-type") or "").lower()
|
| 414 |
+
if "zip" in content_type:
|
| 415 |
+
return True
|
| 416 |
+
magic = response.raw.read(4)
|
| 417 |
+
return magic == b"PK\x03\x04"
|
| 418 |
+
except Exception:
|
| 419 |
+
return False
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _load_ushouse_download_links(session: "requests.Session") -> Dict[str, str]:
|
| 423 |
+
global _USHOUSE_DOWNLOAD_LINKS_BY_CODE
|
| 424 |
+
if _USHOUSE_DOWNLOAD_LINKS_BY_CODE is not None:
|
| 425 |
+
return dict(_USHOUSE_DOWNLOAD_LINKS_BY_CODE)
|
| 426 |
+
|
| 427 |
+
page_url = _ushouse_download_page_url()
|
| 428 |
+
response = session.get(page_url, timeout=40)
|
| 429 |
+
if int(response.status_code) != 200:
|
| 430 |
+
raise RuntimeError(f"Failed to load US House download page: HTTP {response.status_code}")
|
| 431 |
+
|
| 432 |
+
text = str(response.text or "")
|
| 433 |
+
matches = list(USHOUSE_RELEASE_LINK_RE.finditer(text))
|
| 434 |
+
if not matches:
|
| 435 |
+
raise RuntimeError("No US House releasepoint links found on download page")
|
| 436 |
+
|
| 437 |
+
links: Dict[str, str] = {}
|
| 438 |
+
for match in matches:
|
| 439 |
+
code = str(match.group("title_code") or "").lower()
|
| 440 |
+
rel = str(match.group(0) or "").strip()
|
| 441 |
+
if not code or not rel:
|
| 442 |
+
continue
|
| 443 |
+
if code not in links:
|
| 444 |
+
links[code] = urljoin("https://uscode.house.gov/download/", rel)
|
| 445 |
+
|
| 446 |
+
if not links:
|
| 447 |
+
raise RuntimeError("Unable to parse US House title links")
|
| 448 |
+
|
| 449 |
+
_USHOUSE_DOWNLOAD_LINKS_BY_CODE = dict(links)
|
| 450 |
+
return dict(links)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def _discover_ushouse_release_for_congress(
|
| 454 |
+
session: "requests.Session",
|
| 455 |
+
congress: int,
|
| 456 |
+
*,
|
| 457 |
+
max_release_probe: int = DEFAULT_USHOUSE_RELEASE_MAX_PROBE,
|
| 458 |
+
) -> Optional[str]:
|
| 459 |
+
congress_int = int(congress)
|
| 460 |
+
if congress_int in _USHOUSE_RELEASE_CACHE_BY_CONGRESS:
|
| 461 |
+
return _USHOUSE_RELEASE_CACHE_BY_CONGRESS[congress_int]
|
| 462 |
+
|
| 463 |
+
probe_code = "01"
|
| 464 |
+
for release in range(int(max_release_probe), 0, -1):
|
| 465 |
+
release_s = str(int(release))
|
| 466 |
+
url = (
|
| 467 |
+
f"https://uscode.house.gov/download/releasepoints/us/pl/{congress_int}/{release_s}/"
|
| 468 |
+
f"htm_usc{probe_code}@{congress_int}-{release_s}.zip"
|
| 469 |
+
)
|
| 470 |
+
try:
|
| 471 |
+
response = session.get(url, timeout=30, stream=True)
|
| 472 |
+
if int(response.status_code) != 200:
|
| 473 |
+
continue
|
| 474 |
+
if _looks_like_zip_response(response):
|
| 475 |
+
_USHOUSE_RELEASE_CACHE_BY_CONGRESS[congress_int] = release_s
|
| 476 |
+
return release_s
|
| 477 |
+
except Exception:
|
| 478 |
+
continue
|
| 479 |
+
return None
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _ushouse_releasepoint_title_zip_url(*, congress: int, release: str, title_num: str) -> str:
|
| 483 |
+
code = _ushouse_title_code(title_num)
|
| 484 |
+
rel = str(release).strip()
|
| 485 |
+
return (
|
| 486 |
+
f"https://uscode.house.gov/download/releasepoints/us/pl/{int(congress)}/{rel}/"
|
| 487 |
+
f"htm_usc{code}@{int(congress)}-{rel}.zip"
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _discover_latest_year(session: "requests.Session") -> Optional[int]:
|
| 492 |
+
current_year = datetime.now().year
|
| 493 |
+
for year in range(current_year, MIN_USCODE_YEAR - 1, -1):
|
| 494 |
+
probe = _govinfo_zip_url(year, "1")
|
| 495 |
+
try:
|
| 496 |
+
response = session.get(probe, timeout=25, stream=True)
|
| 497 |
+
if int(response.status_code) != 200:
|
| 498 |
+
continue
|
| 499 |
+
content_type = str(response.headers.get("content-type") or "").lower()
|
| 500 |
+
if "zip" not in content_type:
|
| 501 |
+
continue
|
| 502 |
+
chunk = response.raw.read(4)
|
| 503 |
+
if chunk == b"PK\x03\x04":
|
| 504 |
+
return year
|
| 505 |
+
except Exception:
|
| 506 |
+
continue
|
| 507 |
+
return None
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _is_valid_zip_file(path: Path) -> bool:
|
| 511 |
+
if not path.exists() or path.stat().st_size <= 0:
|
| 512 |
+
return False
|
| 513 |
+
try:
|
| 514 |
+
with zipfile.ZipFile(path) as archive:
|
| 515 |
+
if archive.testzip() is not None:
|
| 516 |
+
return False
|
| 517 |
+
return True
|
| 518 |
+
except Exception:
|
| 519 |
+
return False
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def _download_title_zip(
|
| 523 |
+
session: "requests.Session",
|
| 524 |
+
*,
|
| 525 |
+
year: int,
|
| 526 |
+
title_num: str,
|
| 527 |
+
cache_dir: Path,
|
| 528 |
+
force_download: bool,
|
| 529 |
+
max_attempts: int = DEFAULT_USCODE_DOWNLOAD_RETRIES,
|
| 530 |
+
include_official: bool = True,
|
| 531 |
+
include_recovery: bool = False,
|
| 532 |
+
) -> Dict[str, Any]:
|
| 533 |
+
out_path = cache_dir / f"USCODE-{int(year)}-title{title_num}.zip"
|
| 534 |
+
candidates: List[Dict[str, str]] = []
|
| 535 |
+
if include_official:
|
| 536 |
+
candidates.extend(
|
| 537 |
+
iter_official_title_zip_candidates(session, year=year, title_num=title_num)
|
| 538 |
+
)
|
| 539 |
+
if include_recovery:
|
| 540 |
+
candidates.extend(
|
| 541 |
+
iter_recovery_title_zip_candidates(session, year=year, title_num=title_num)
|
| 542 |
+
)
|
| 543 |
+
last_error: Optional[Exception] = None
|
| 544 |
+
attempts: List[Dict[str, Any]] = []
|
| 545 |
+
for candidate in candidates:
|
| 546 |
+
source = str(candidate.get("source") or "govinfo-content-zip")
|
| 547 |
+
url = str(candidate.get("url") or "")
|
| 548 |
+
try:
|
| 549 |
+
zip_path = _download_zip_from_url(
|
| 550 |
+
session,
|
| 551 |
+
url=url,
|
| 552 |
+
out_path=out_path,
|
| 553 |
+
force_download=force_download,
|
| 554 |
+
max_attempts=max_attempts,
|
| 555 |
+
not_found_hint=f"title {title_num} year {year} via {source}",
|
| 556 |
+
)
|
| 557 |
+
attempts.append({"source": source, "url": url, "status": "success"})
|
| 558 |
+
return {
|
| 559 |
+
"zip_path": zip_path,
|
| 560 |
+
"source": source,
|
| 561 |
+
"source_url": url,
|
| 562 |
+
"source_authority_class": _source_authority_class(source),
|
| 563 |
+
"attempts": attempts,
|
| 564 |
+
}
|
| 565 |
+
except Exception as exc:
|
| 566 |
+
last_error = exc if isinstance(exc, Exception) else Exception(str(exc))
|
| 567 |
+
attempts.append(
|
| 568 |
+
{
|
| 569 |
+
"source": source,
|
| 570 |
+
"url": url,
|
| 571 |
+
"status": "error",
|
| 572 |
+
"error": str(exc),
|
| 573 |
+
}
|
| 574 |
+
)
|
| 575 |
+
continue
|
| 576 |
+
if last_error is not None:
|
| 577 |
+
raise last_error
|
| 578 |
+
raise RuntimeError(f"Failed to download title zip for title {title_num} year {year}")
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _download_zip_from_url(
|
| 582 |
+
session: "requests.Session",
|
| 583 |
+
*,
|
| 584 |
+
url: str,
|
| 585 |
+
out_path: Path,
|
| 586 |
+
force_download: bool,
|
| 587 |
+
max_attempts: int,
|
| 588 |
+
not_found_hint: str,
|
| 589 |
+
) -> Path:
|
| 590 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 591 |
+
if out_path.exists() and not force_download:
|
| 592 |
+
if _is_valid_zip_file(out_path):
|
| 593 |
+
return out_path
|
| 594 |
+
try:
|
| 595 |
+
out_path.unlink(missing_ok=True)
|
| 596 |
+
except Exception:
|
| 597 |
+
pass
|
| 598 |
+
|
| 599 |
+
last_error: Optional[Exception] = None
|
| 600 |
+
|
| 601 |
+
for attempt in range(1, max(1, int(max_attempts)) + 1):
|
| 602 |
+
tmp_path = out_path.with_suffix(out_path.suffix + ".part")
|
| 603 |
+
try:
|
| 604 |
+
try:
|
| 605 |
+
tmp_path.unlink(missing_ok=True)
|
| 606 |
+
except Exception:
|
| 607 |
+
pass
|
| 608 |
+
|
| 609 |
+
response = session.get(url, timeout=90, stream=True)
|
| 610 |
+
status_code = int(response.status_code)
|
| 611 |
+
if status_code != 200:
|
| 612 |
+
if status_code == 404:
|
| 613 |
+
raise RuntimeError(f"Title zip not found (HTTP 404) for {not_found_hint}")
|
| 614 |
+
raise RuntimeError(f"Failed to download title zip: HTTP {status_code} ({url})")
|
| 615 |
+
|
| 616 |
+
with tmp_path.open("wb") as handle:
|
| 617 |
+
for chunk in response.iter_content(chunk_size=1024 * 1024):
|
| 618 |
+
if not chunk:
|
| 619 |
+
continue
|
| 620 |
+
handle.write(chunk)
|
| 621 |
+
|
| 622 |
+
if tmp_path.stat().st_size <= 0:
|
| 623 |
+
raise RuntimeError(f"Downloaded empty zip for {not_found_hint}")
|
| 624 |
+
|
| 625 |
+
if not _is_valid_zip_file(tmp_path):
|
| 626 |
+
raise RuntimeError(f"Downloaded invalid zip for {not_found_hint}")
|
| 627 |
+
|
| 628 |
+
tmp_path.replace(out_path)
|
| 629 |
+
return out_path
|
| 630 |
+
except Exception as exc:
|
| 631 |
+
last_error = exc if isinstance(exc, Exception) else Exception(str(exc))
|
| 632 |
+
try:
|
| 633 |
+
tmp_path.unlink(missing_ok=True)
|
| 634 |
+
except Exception:
|
| 635 |
+
pass
|
| 636 |
+
|
| 637 |
+
# 404 means this title-year package likely does not exist; fail fast for this year.
|
| 638 |
+
if "HTTP 404" in str(exc):
|
| 639 |
+
break
|
| 640 |
+
|
| 641 |
+
if attempt < max(1, int(max_attempts)):
|
| 642 |
+
time.sleep(min(8.0, float(attempt)))
|
| 643 |
+
|
| 644 |
+
if last_error is not None:
|
| 645 |
+
raise last_error
|
| 646 |
+
raise RuntimeError(f"Failed to download title zip for {not_found_hint}")
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def _download_title_zip_ushouse(
|
| 650 |
+
session: "requests.Session",
|
| 651 |
+
*,
|
| 652 |
+
title_num: str,
|
| 653 |
+
cache_dir: Path,
|
| 654 |
+
force_download: bool,
|
| 655 |
+
max_attempts: int = DEFAULT_USCODE_DOWNLOAD_RETRIES,
|
| 656 |
+
year: Optional[int] = None,
|
| 657 |
+
) -> Dict[str, Any]:
|
| 658 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 659 |
+
|
| 660 |
+
source_url: Optional[str] = None
|
| 661 |
+
source_release: Optional[str] = None
|
| 662 |
+
source_congress: Optional[int] = None
|
| 663 |
+
|
| 664 |
+
if year is not None:
|
| 665 |
+
congress = _year_to_congress(int(year))
|
| 666 |
+
release = _discover_ushouse_release_for_congress(session, congress)
|
| 667 |
+
if release:
|
| 668 |
+
source_congress = int(congress)
|
| 669 |
+
source_release = str(release)
|
| 670 |
+
source_url = _ushouse_releasepoint_title_zip_url(
|
| 671 |
+
congress=source_congress,
|
| 672 |
+
release=source_release,
|
| 673 |
+
title_num=title_num,
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
if not source_url:
|
| 677 |
+
links = _load_ushouse_download_links(session)
|
| 678 |
+
code = _ushouse_title_code(title_num).lower()
|
| 679 |
+
source_url = links.get(code)
|
| 680 |
+
if source_url:
|
| 681 |
+
match = USHOUSE_RELEASE_LINK_RE.search(source_url)
|
| 682 |
+
if match:
|
| 683 |
+
source_congress = int(match.group("congress"))
|
| 684 |
+
source_release = str(match.group("release"))
|
| 685 |
+
|
| 686 |
+
if not source_url:
|
| 687 |
+
raise RuntimeError(f"No US House releasepoint source URL found for title {title_num}")
|
| 688 |
+
|
| 689 |
+
year_part = str(int(year)) if year is not None else "latest"
|
| 690 |
+
out_name = f"USHOUSE-USCODE-{year_part}-title{title_num}"
|
| 691 |
+
if source_congress is not None and source_release is not None:
|
| 692 |
+
out_name += f"-c{source_congress}-r{source_release}"
|
| 693 |
+
out_path = cache_dir / f"{out_name}.zip"
|
| 694 |
+
|
| 695 |
+
zip_path = _download_zip_from_url(
|
| 696 |
+
session,
|
| 697 |
+
url=source_url,
|
| 698 |
+
out_path=out_path,
|
| 699 |
+
force_download=force_download,
|
| 700 |
+
max_attempts=max_attempts,
|
| 701 |
+
not_found_hint=f"US House releasepoint title {title_num}",
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
section_url_base = source_url.rsplit("/", 1)[0] if "/" in source_url else source_url
|
| 705 |
+
source_package = f"USHOUSE-USCODE-{source_congress or 'latest'}-{source_release or 'latest'}-title{title_num}"
|
| 706 |
+
|
| 707 |
+
return {
|
| 708 |
+
"zip_path": zip_path,
|
| 709 |
+
"source_url": source_url,
|
| 710 |
+
"source_package": source_package,
|
| 711 |
+
"section_url_base": section_url_base,
|
| 712 |
+
"source_congress": source_congress,
|
| 713 |
+
"source_release": source_release,
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def _candidate_years_for_title(
|
| 718 |
+
session: "requests.Session",
|
| 719 |
+
*,
|
| 720 |
+
title_num: str,
|
| 721 |
+
year: Optional[int],
|
| 722 |
+
max_year_fallbacks: int,
|
| 723 |
+
) -> List[int]:
|
| 724 |
+
"""Build candidate package years for a title, newest-first."""
|
| 725 |
+
if year is not None:
|
| 726 |
+
return [int(year)]
|
| 727 |
+
|
| 728 |
+
latest = _discover_latest_year(session)
|
| 729 |
+
if latest is None:
|
| 730 |
+
return []
|
| 731 |
+
|
| 732 |
+
window = max(1, int(max_year_fallbacks))
|
| 733 |
+
out: List[int] = []
|
| 734 |
+
for y in range(int(latest), MIN_USCODE_YEAR - 1, -1):
|
| 735 |
+
out.append(y)
|
| 736 |
+
if len(out) >= window:
|
| 737 |
+
break
|
| 738 |
+
return out
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def _extract_section_number_from_filename(file_name: str) -> str:
|
| 742 |
+
match = re.search(r"-sec([^.]+)\.htm$", file_name, flags=re.IGNORECASE)
|
| 743 |
+
if match:
|
| 744 |
+
return str(match.group(1)).strip()
|
| 745 |
+
return Path(file_name).stem
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def _extract_section_heading(text: str, section_number: str, fallback_heading: str) -> str:
|
| 749 |
+
source = _norm_space(str(text or ""))
|
| 750 |
+
sec_raw = str(section_number or "").strip()
|
| 751 |
+
sec_no = re.escape(sec_raw)
|
| 752 |
+
if not source or not sec_no:
|
| 753 |
+
return _norm_space(fallback_heading)[:500]
|
| 754 |
+
|
| 755 |
+
def _normalize_ref(value: str) -> str:
|
| 756 |
+
return re.sub(r"\s+", "", str(value or "").replace("–", "-").replace("—", "-").lower())
|
| 757 |
+
|
| 758 |
+
sec_norm = _normalize_ref(sec_raw)
|
| 759 |
+
|
| 760 |
+
sec_pattern = re.compile(
|
| 761 |
+
rf"Sec\.\s*{sec_no}\s*-\s*(.+?)(?=\s+From\s+the\s+U\.S\.\s+Government\s+Publishing\s+Office|\s+§\s*{sec_no}\.?|\s+Editorial\s+Notes|\s+Statutory\s+Notes|$)",
|
| 762 |
+
re.IGNORECASE,
|
| 763 |
+
)
|
| 764 |
+
sec_match = sec_pattern.search(source)
|
| 765 |
+
if sec_match:
|
| 766 |
+
return _norm_space(sec_match.group(1))[:500]
|
| 767 |
+
|
| 768 |
+
secs_pattern = re.compile(
|
| 769 |
+
r"Secs?\.\s*([^\-]{1,140})\s*-\s*(.+?)(?=\s+From\s+the\s+U\.S\.\s+Government\s+Publishing\s+Office|\s+§{1,2}\s|\s+Editorial\s+Notes|\s+Statutory\s+Notes|$)",
|
| 770 |
+
re.IGNORECASE,
|
| 771 |
+
)
|
| 772 |
+
for match in secs_pattern.finditer(source):
|
| 773 |
+
refs = _normalize_ref(match.group(1))
|
| 774 |
+
if sec_norm and sec_norm in refs:
|
| 775 |
+
return _norm_space(match.group(2))[:500]
|
| 776 |
+
|
| 777 |
+
section_symbol_pattern = re.compile(
|
| 778 |
+
rf"§\s*{sec_no}\.?\s*(.+?)(?=\s+\([a-zA-Z0-9]{{1,4}}\)\s|\s+\([A-Z][a-z]{{2,9}}\.?\s+\d{{1,2}},\s+\d{{4}}|\s+Editorial\s+Notes|\s+Statutory\s+Notes|$)",
|
| 779 |
+
re.IGNORECASE,
|
| 780 |
+
)
|
| 781 |
+
section_symbol_match = section_symbol_pattern.search(source)
|
| 782 |
+
if section_symbol_match:
|
| 783 |
+
return _norm_space(section_symbol_match.group(1))[:500]
|
| 784 |
+
|
| 785 |
+
section_symbols_pattern = re.compile(
|
| 786 |
+
r"§{2}\s*([^\.]{1,140})\.\s*(.+?)(?=\s+Editorial\s+Notes|\s+Statutory\s+Notes|$)",
|
| 787 |
+
re.IGNORECASE,
|
| 788 |
+
)
|
| 789 |
+
for match in section_symbols_pattern.finditer(source):
|
| 790 |
+
refs = _normalize_ref(match.group(1))
|
| 791 |
+
if sec_norm and sec_norm in refs:
|
| 792 |
+
return _norm_space(match.group(2))[:500]
|
| 793 |
+
|
| 794 |
+
return _norm_space(fallback_heading)[:500]
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
_MODS_NS = {"mods": "http://www.loc.gov/mods/v3"}
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def parse_usc_mods_metadata(mods_xml: bytes) -> Dict[str, Dict[str, str]]:
|
| 801 |
+
"""Parse GovInfo ``mods.xml`` granule metadata from a US Code title ZIP.
|
| 802 |
+
|
| 803 |
+
Adapted from the Vaquill-AI/open-us-law ``parse_usc_zip`` MODS walk
|
| 804 |
+
(Apache-2.0). Missing or malformed MODS is a no-op.
|
| 805 |
+
"""
|
| 806 |
+
|
| 807 |
+
metadata: Dict[str, Dict[str, str]] = {}
|
| 808 |
+
if not mods_xml:
|
| 809 |
+
return metadata
|
| 810 |
+
try:
|
| 811 |
+
root = ET.fromstring(mods_xml)
|
| 812 |
+
except ET.ParseError:
|
| 813 |
+
return metadata
|
| 814 |
+
for item in root.iter("{http://www.loc.gov/mods/v3}relatedItem"):
|
| 815 |
+
rid = str(item.get("ID") or "")
|
| 816 |
+
if not rid.startswith("id-USCODE"):
|
| 817 |
+
continue
|
| 818 |
+
granule_id = rid[len("id-") :]
|
| 819 |
+
entry: Dict[str, str] = {}
|
| 820 |
+
title_info = item.find("mods:titleInfo", _MODS_NS)
|
| 821 |
+
if title_info is not None:
|
| 822 |
+
title_el = title_info.find("mods:title", _MODS_NS)
|
| 823 |
+
if title_el is not None and title_el.text:
|
| 824 |
+
entry["section_title"] = title_el.text.strip()
|
| 825 |
+
part = title_info.find("mods:partName", _MODS_NS)
|
| 826 |
+
if part is not None and part.text:
|
| 827 |
+
entry["part_name"] = part.text.strip()
|
| 828 |
+
for ident in item.findall("mods:identifier", _MODS_NS):
|
| 829 |
+
itype = str(ident.get("type") or "")
|
| 830 |
+
if itype == "Parent Id" and ident.text:
|
| 831 |
+
entry["parent_id"] = ident.text.strip()
|
| 832 |
+
elif itype == "uri" and ident.text:
|
| 833 |
+
entry["details_url"] = ident.text.strip()
|
| 834 |
+
elif itype == "former granule identifier" and ident.text:
|
| 835 |
+
entry["former_id"] = ident.text.strip()
|
| 836 |
+
for related in item.findall("mods:relatedItem", _MODS_NS):
|
| 837 |
+
href = str(related.get("{http://www.w3.org/1999/xlink}href") or "")
|
| 838 |
+
if ".htm" in href:
|
| 839 |
+
entry["html_url"] = href
|
| 840 |
+
elif ".pdf" in href:
|
| 841 |
+
entry["pdf_url"] = href
|
| 842 |
+
origin = item.find("mods:originInfo", _MODS_NS)
|
| 843 |
+
if origin is not None:
|
| 844 |
+
issued = origin.find("mods:dateIssued", _MODS_NS)
|
| 845 |
+
if issued is not None and issued.text:
|
| 846 |
+
entry["date_issued"] = issued.text.strip()
|
| 847 |
+
if entry:
|
| 848 |
+
metadata[granule_id] = entry
|
| 849 |
+
return metadata
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def _mods_from_zip(archive: zipfile.ZipFile) -> Dict[str, Dict[str, str]]:
|
| 853 |
+
for name in archive.namelist():
|
| 854 |
+
if name.lower().endswith("mods.xml"):
|
| 855 |
+
try:
|
| 856 |
+
return parse_usc_mods_metadata(archive.read(name))
|
| 857 |
+
except Exception:
|
| 858 |
+
return {}
|
| 859 |
+
return {}
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def _granule_id_from_html_name(html_name: str) -> str:
|
| 863 |
+
stem = Path(html_name).stem
|
| 864 |
+
return stem
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def _extract_section_number_and_heading(heading_text: str) -> tuple[str, str]:
|
| 868 |
+
text = _norm_space(heading_text)
|
| 869 |
+
if not text:
|
| 870 |
+
return "", ""
|
| 871 |
+
|
| 872 |
+
m = re.match(
|
| 873 |
+
r"^§+\s*([0-9A-Za-z.\-]+(?:\s+to\s+[0-9A-Za-z.\-]+)?)\.?\s*(.*)$", text, re.IGNORECASE
|
| 874 |
+
)
|
| 875 |
+
if m:
|
| 876 |
+
section_number = _norm_space(m.group(1)).strip()
|
| 877 |
+
heading = _norm_space(m.group(2)).strip(" .")
|
| 878 |
+
return section_number, heading or text
|
| 879 |
+
|
| 880 |
+
m = re.match(r"^(?:Sec\.|SEC\.)\s*([0-9A-Za-z.\-]+)\.?\s*(.*)$", text)
|
| 881 |
+
if m:
|
| 882 |
+
section_number = _norm_space(m.group(1)).strip()
|
| 883 |
+
heading = _norm_space(m.group(2)).strip(" .")
|
| 884 |
+
return section_number, heading or text
|
| 885 |
+
|
| 886 |
+
return "", text
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def _extract_sections_from_zip(
|
| 890 |
+
zip_path: Path,
|
| 891 |
+
*,
|
| 892 |
+
year: int,
|
| 893 |
+
title_num: str,
|
| 894 |
+
title_name: str,
|
| 895 |
+
include_metadata: bool,
|
| 896 |
+
source_package: Optional[str] = None,
|
| 897 |
+
section_url_base: Optional[str] = None,
|
| 898 |
+
) -> List[Dict[str, Any]]:
|
| 899 |
+
def _iter_documentid_chunks(html_text: str) -> Iterator[str]:
|
| 900 |
+
markers = list(DOCID_COMMENT_RE.finditer(html_text))
|
| 901 |
+
for idx, marker in enumerate(markers):
|
| 902 |
+
start = marker.start()
|
| 903 |
+
end = markers[idx + 1].start() if idx + 1 < len(markers) else len(html_text)
|
| 904 |
+
if end > start:
|
| 905 |
+
yield html_text[start:end]
|
| 906 |
+
|
| 907 |
+
def _source_url_for_entry(html_name: str) -> str:
|
| 908 |
+
if section_url_base:
|
| 909 |
+
return f"{str(section_url_base).rstrip('/')}/{html_name}"
|
| 910 |
+
return _govinfo_section_url(year, title_num, html_name)
|
| 911 |
+
|
| 912 |
+
def _extract_consolidated_sections(html_text: str, html_name: str) -> List[Dict[str, Any]]:
|
| 913 |
+
consolidated: List[Dict[str, Any]] = []
|
| 914 |
+
for chunk in _iter_documentid_chunks(html_text):
|
| 915 |
+
if "section-head" not in chunk:
|
| 916 |
+
continue
|
| 917 |
+
|
| 918 |
+
soup = BeautifulSoup(chunk, "html.parser")
|
| 919 |
+
head = soup.find(class_=re.compile(r"\bsection-head\b", re.IGNORECASE))
|
| 920 |
+
if head is None:
|
| 921 |
+
continue
|
| 922 |
+
|
| 923 |
+
heading_text = _norm_space(head.get_text(" ", strip=True))
|
| 924 |
+
section_number, heading = _extract_section_number_and_heading(heading_text)
|
| 925 |
+
if not section_number:
|
| 926 |
+
match = DOCID_SECTION_KEY_RE.search(chunk)
|
| 927 |
+
if match:
|
| 928 |
+
section_number = _norm_space(match.group(1)).strip("._-")
|
| 929 |
+
if not section_number:
|
| 930 |
+
continue
|
| 931 |
+
|
| 932 |
+
body_text = _norm_space(soup.get_text(" ", strip=True))
|
| 933 |
+
if not body_text:
|
| 934 |
+
continue
|
| 935 |
+
|
| 936 |
+
record: Dict[str, Any] = {
|
| 937 |
+
"section_number": section_number,
|
| 938 |
+
"heading": heading,
|
| 939 |
+
"text": body_text,
|
| 940 |
+
"body_text": body_text,
|
| 941 |
+
"citations": _extract_citations(body_text),
|
| 942 |
+
}
|
| 943 |
+
if include_metadata:
|
| 944 |
+
record.update(
|
| 945 |
+
{
|
| 946 |
+
"title_number": title_num,
|
| 947 |
+
"title_name": title_name,
|
| 948 |
+
"year": int(year),
|
| 949 |
+
"package": source_package or f"USCODE-{int(year)}-title{title_num}",
|
| 950 |
+
"source_url": _source_url_for_entry(html_name),
|
| 951 |
+
}
|
| 952 |
+
)
|
| 953 |
+
consolidated.append(record)
|
| 954 |
+
return consolidated
|
| 955 |
+
|
| 956 |
+
def _apply_mods(record: Dict[str, Any], html_name: str) -> None:
|
| 957 |
+
granule_id = _granule_id_from_html_name(html_name)
|
| 958 |
+
meta = mods_meta.get(granule_id) or {}
|
| 959 |
+
if not meta:
|
| 960 |
+
return
|
| 961 |
+
record["granule_id"] = granule_id
|
| 962 |
+
if meta.get("section_title"):
|
| 963 |
+
record["heading"] = meta["section_title"][:500]
|
| 964 |
+
if meta.get("pdf_url"):
|
| 965 |
+
record["pdf_url"] = meta["pdf_url"]
|
| 966 |
+
if meta.get("details_url"):
|
| 967 |
+
record["details_url"] = meta["details_url"]
|
| 968 |
+
if meta.get("date_issued"):
|
| 969 |
+
record["date_issued"] = meta["date_issued"]
|
| 970 |
+
if meta.get("former_id"):
|
| 971 |
+
record["former_granule_id"] = meta["former_id"]
|
| 972 |
+
chapter = record.get("chapter")
|
| 973 |
+
if isinstance(chapter, dict) and meta.get("part_name") and not chapter.get("chapter_name"):
|
| 974 |
+
chapter["chapter_name"] = meta["part_name"]
|
| 975 |
+
|
| 976 |
+
sections: List[Dict[str, Any]] = []
|
| 977 |
+
with zipfile.ZipFile(zip_path) as archive:
|
| 978 |
+
mods_meta = _mods_from_zip(archive)
|
| 979 |
+
names = sorted(archive.namelist())
|
| 980 |
+
html_entries = [
|
| 981 |
+
name
|
| 982 |
+
for name in names
|
| 983 |
+
if name.lower().endswith((".htm", ".html")) and "-sec" in name.lower()
|
| 984 |
+
]
|
| 985 |
+
if not html_entries:
|
| 986 |
+
html_entries = [name for name in names if name.lower().endswith((".htm", ".html"))]
|
| 987 |
+
|
| 988 |
+
for entry_name in html_entries:
|
| 989 |
+
html_name = Path(entry_name).name
|
| 990 |
+
raw = archive.read(entry_name)
|
| 991 |
+
try:
|
| 992 |
+
html_text = raw.decode("utf-8", errors="ignore")
|
| 993 |
+
except Exception:
|
| 994 |
+
html_text = str(raw)
|
| 995 |
+
|
| 996 |
+
if (
|
| 997 |
+
"documentid:" in html_text
|
| 998 |
+
and "section-head" in html_text
|
| 999 |
+
and "-sec" not in html_name.lower()
|
| 1000 |
+
):
|
| 1001 |
+
for item in _extract_consolidated_sections(html_text, html_name):
|
| 1002 |
+
_apply_mods(item, html_name)
|
| 1003 |
+
sections.append(item)
|
| 1004 |
+
continue
|
| 1005 |
+
|
| 1006 |
+
soup = BeautifulSoup(raw, "html.parser")
|
| 1007 |
+
|
| 1008 |
+
text = soup.get_text(" ", strip=True)
|
| 1009 |
+
subsection_text = _trim_nonstatutory_tail(text)
|
| 1010 |
+
section_number = _extract_section_number_from_filename(html_name)
|
| 1011 |
+
heading_node = soup.find(["h1", "h2", "h3", "h4", "title"])
|
| 1012 |
+
fallback_heading = heading_node.get_text(" ", strip=True) if heading_node else html_name
|
| 1013 |
+
heading = _extract_section_heading(text, section_number, fallback_heading)
|
| 1014 |
+
chapter_info = _extract_chapter_info(
|
| 1015 |
+
subsection_text,
|
| 1016 |
+
title_num=title_num,
|
| 1017 |
+
title_name=title_name,
|
| 1018 |
+
heading=heading,
|
| 1019 |
+
)
|
| 1020 |
+
section_body = _extract_section_body(subsection_text, section_number, heading)
|
| 1021 |
+
preamble = _extract_preamble(section_body)
|
| 1022 |
+
if not preamble:
|
| 1023 |
+
preamble = _norm_space(heading)
|
| 1024 |
+
citations = _extract_citations(text, subsection_text)
|
| 1025 |
+
legislative_history = _extract_legislative_history(text, subsection_text)
|
| 1026 |
+
|
| 1027 |
+
record: Dict[str, Any] = {
|
| 1028 |
+
"section_number": section_number,
|
| 1029 |
+
"heading": heading[:500],
|
| 1030 |
+
"text": text,
|
| 1031 |
+
"chapter": chapter_info,
|
| 1032 |
+
"preamble": preamble,
|
| 1033 |
+
"citations": citations,
|
| 1034 |
+
"legislative_history": legislative_history,
|
| 1035 |
+
"subsections": _parse_subsections(section_body),
|
| 1036 |
+
}
|
| 1037 |
+
record["parser_warnings"] = _validate_subsection_tree(record.get("subsections") or [])
|
| 1038 |
+
if include_metadata:
|
| 1039 |
+
record.update(
|
| 1040 |
+
{
|
| 1041 |
+
"title_number": title_num,
|
| 1042 |
+
"title_name": title_name,
|
| 1043 |
+
"year": int(year),
|
| 1044 |
+
"package": source_package or f"USCODE-{int(year)}-title{title_num}",
|
| 1045 |
+
"source_url": _source_url_for_entry(html_name),
|
| 1046 |
+
}
|
| 1047 |
+
)
|
| 1048 |
+
_apply_mods(record, html_name)
|
| 1049 |
+
sections.append(record)
|
| 1050 |
+
|
| 1051 |
+
return sections
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
def _write_index_jsonl(sections: List[Dict[str, Any]], *, index_path: Path) -> None:
|
| 1055 |
+
index_path.parent.mkdir(parents=True, exist_ok=True)
|
| 1056 |
+
with index_path.open("w", encoding="utf-8") as handle:
|
| 1057 |
+
for item in sections:
|
| 1058 |
+
handle.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
def _load_index_jsonl(index_path: Path) -> List[Dict[str, Any]]:
|
| 1062 |
+
if not index_path.exists():
|
| 1063 |
+
return []
|
| 1064 |
+
out: List[Dict[str, Any]] = []
|
| 1065 |
+
with index_path.open("r", encoding="utf-8") as handle:
|
| 1066 |
+
for line in handle:
|
| 1067 |
+
line = line.strip()
|
| 1068 |
+
if not line:
|
| 1069 |
+
continue
|
| 1070 |
+
try:
|
| 1071 |
+
obj = json.loads(line)
|
| 1072 |
+
except Exception:
|
| 1073 |
+
continue
|
| 1074 |
+
if isinstance(obj, dict):
|
| 1075 |
+
out.append(obj)
|
| 1076 |
+
return out
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
def _norm_space(text: str) -> str:
|
| 1080 |
+
text = str(text or "")
|
| 1081 |
+
text = text.replace("\u00a0", " ")
|
| 1082 |
+
text = text.replace("\ufeff", "")
|
| 1083 |
+
text = text.replace("\u2019", "'")
|
| 1084 |
+
text = text.replace("\u201c", '"').replace("\u201d", '"')
|
| 1085 |
+
text = re.sub(r"\s+", " ", text)
|
| 1086 |
+
return text.strip()
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
def _classify_subsec_kind(token: str, prev_kind: Optional[str]) -> str:
|
| 1090 |
+
if token.isdigit():
|
| 1091 |
+
return "numeric"
|
| 1092 |
+
|
| 1093 |
+
if token.islower():
|
| 1094 |
+
if token in COMMON_ROMAN_LOWER and prev_kind in {
|
| 1095 |
+
"alpha_upper",
|
| 1096 |
+
"roman_lower",
|
| 1097 |
+
"roman_upper",
|
| 1098 |
+
}:
|
| 1099 |
+
return "roman_lower"
|
| 1100 |
+
if len(token) > 1 and ROMAN_LOWER_RE.match(token):
|
| 1101 |
+
return "roman_lower"
|
| 1102 |
+
return "alpha_lower"
|
| 1103 |
+
|
| 1104 |
+
if token.isupper():
|
| 1105 |
+
if token in COMMON_ROMAN_UPPER and prev_kind in {"roman_lower", "roman_upper"}:
|
| 1106 |
+
return "roman_upper"
|
| 1107 |
+
if len(token) > 1 and ROMAN_UPPER_RE.match(token):
|
| 1108 |
+
return "roman_upper"
|
| 1109 |
+
return "alpha_upper"
|
| 1110 |
+
|
| 1111 |
+
return "other"
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def _subsec_level(kind: str) -> int:
|
| 1115 |
+
order = {
|
| 1116 |
+
"numeric": 1,
|
| 1117 |
+
"alpha_lower": 2,
|
| 1118 |
+
"alpha_upper": 3,
|
| 1119 |
+
"roman_lower": 4,
|
| 1120 |
+
"roman_upper": 5,
|
| 1121 |
+
"other": 6,
|
| 1122 |
+
}
|
| 1123 |
+
return int(order.get(kind, 6))
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
def _subsec_rank_map(first_kind: str) -> Dict[str, int]:
|
| 1127 |
+
sequence = [
|
| 1128 |
+
"numeric",
|
| 1129 |
+
"alpha_lower",
|
| 1130 |
+
"alpha_upper",
|
| 1131 |
+
"roman_lower",
|
| 1132 |
+
"roman_upper",
|
| 1133 |
+
"other",
|
| 1134 |
+
]
|
| 1135 |
+
if first_kind in sequence:
|
| 1136 |
+
idx = sequence.index(first_kind)
|
| 1137 |
+
sequence = sequence[idx:] + sequence[:idx]
|
| 1138 |
+
return {kind: rank + 1 for rank, kind in enumerate(sequence)}
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def _find_subsec_markers(text: str) -> List[tuple[int, int, str]]:
|
| 1142 |
+
markers: List[tuple[int, int, str]] = []
|
| 1143 |
+
for match in SUBSEC_TOKEN_RE.finditer(text):
|
| 1144 |
+
start = match.start()
|
| 1145 |
+
end = match.end()
|
| 1146 |
+
token = match.group(1)
|
| 1147 |
+
|
| 1148 |
+
if len(token) > 6:
|
| 1149 |
+
continue
|
| 1150 |
+
if token.isdigit() and len(token) > 3:
|
| 1151 |
+
continue
|
| 1152 |
+
if token.isalpha():
|
| 1153 |
+
if not (token.islower() or token.isupper()):
|
| 1154 |
+
continue
|
| 1155 |
+
if len(token) > 1:
|
| 1156 |
+
if token.islower() and not ROMAN_LOWER_RE.match(token):
|
| 1157 |
+
continue
|
| 1158 |
+
if token.isupper() and not ROMAN_UPPER_RE.match(token):
|
| 1159 |
+
continue
|
| 1160 |
+
|
| 1161 |
+
prev_ch = text[start - 1] if start > 0 else ""
|
| 1162 |
+
next_ch = text[end] if end < len(text) else ""
|
| 1163 |
+
|
| 1164 |
+
valid_left = (start == 0) or prev_ch.isspace() or prev_ch in ";:.(["
|
| 1165 |
+
valid_right = (end == len(text)) or next_ch.isspace() or next_ch in "(),;:.]"
|
| 1166 |
+
if not (valid_left and valid_right):
|
| 1167 |
+
continue
|
| 1168 |
+
|
| 1169 |
+
markers.append((start, end, token))
|
| 1170 |
+
return markers
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
def _parse_subsections(text: str) -> List[Dict[str, Any]]:
|
| 1174 |
+
text = _norm_space(text)
|
| 1175 |
+
markers = _find_subsec_markers(text)
|
| 1176 |
+
if not markers:
|
| 1177 |
+
return []
|
| 1178 |
+
|
| 1179 |
+
items: List[Dict[str, Any]] = []
|
| 1180 |
+
prev_kind: Optional[str] = None
|
| 1181 |
+
for idx, (start, end, token) in enumerate(markers):
|
| 1182 |
+
next_start = markers[idx + 1][0] if idx + 1 < len(markers) else len(text)
|
| 1183 |
+
body = _norm_space(text[end:next_start])
|
| 1184 |
+
kind = _classify_subsec_kind(token, prev_kind)
|
| 1185 |
+
prev_kind = kind
|
| 1186 |
+
items.append(
|
| 1187 |
+
{
|
| 1188 |
+
"start": start,
|
| 1189 |
+
"end": end,
|
| 1190 |
+
"label": f"({token})",
|
| 1191 |
+
"token": token,
|
| 1192 |
+
"kind": kind,
|
| 1193 |
+
"text": body,
|
| 1194 |
+
"subsections": [],
|
| 1195 |
+
}
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
rank_map = _subsec_rank_map(str(items[0].get("kind") or "numeric"))
|
| 1199 |
+
for item in items:
|
| 1200 |
+
item["level"] = int(rank_map.get(str(item.get("kind") or "other"), _subsec_level("other")))
|
| 1201 |
+
|
| 1202 |
+
roots: List[Dict[str, Any]] = []
|
| 1203 |
+
stack: List[Dict[str, Any]] = []
|
| 1204 |
+
prev_item: Optional[Dict[str, Any]] = None
|
| 1205 |
+
prev_node: Optional[Dict[str, Any]] = None
|
| 1206 |
+
|
| 1207 |
+
def _is_chained(current: Dict[str, Any], previous: Optional[Dict[str, Any]]) -> bool:
|
| 1208 |
+
if previous is None:
|
| 1209 |
+
return False
|
| 1210 |
+
gap = text[int(previous["end"]) : int(current["start"])]
|
| 1211 |
+
return gap.strip() == ""
|
| 1212 |
+
|
| 1213 |
+
for item in items:
|
| 1214 |
+
level = int(item["level"])
|
| 1215 |
+
chained = _is_chained(item, prev_item)
|
| 1216 |
+
|
| 1217 |
+
if chained and prev_node is not None:
|
| 1218 |
+
parent_subsections = prev_node.get("subsections", [])
|
| 1219 |
+
else:
|
| 1220 |
+
while stack and int(stack[-1]["level"]) >= level:
|
| 1221 |
+
stack.pop()
|
| 1222 |
+
parent_subsections = roots if not stack else stack[-1]["subsections"]
|
| 1223 |
+
|
| 1224 |
+
existing_node: Optional[Dict[str, Any]] = None
|
| 1225 |
+
for sibling in reversed(parent_subsections):
|
| 1226 |
+
if sibling.get("label") == item["label"]:
|
| 1227 |
+
existing_node = sibling
|
| 1228 |
+
break
|
| 1229 |
+
|
| 1230 |
+
if existing_node is None:
|
| 1231 |
+
node = {
|
| 1232 |
+
"label": item["label"],
|
| 1233 |
+
"token": item["token"],
|
| 1234 |
+
"kind": item["kind"],
|
| 1235 |
+
"text": item["text"],
|
| 1236 |
+
"subsections": [],
|
| 1237 |
+
}
|
| 1238 |
+
parent_subsections.append(node)
|
| 1239 |
+
else:
|
| 1240 |
+
node = existing_node
|
| 1241 |
+
new_text = item["text"]
|
| 1242 |
+
old_text = _norm_space(str(node.get("text", "")))
|
| 1243 |
+
if new_text:
|
| 1244 |
+
if not old_text:
|
| 1245 |
+
node["text"] = new_text
|
| 1246 |
+
elif new_text not in old_text:
|
| 1247 |
+
node["text"] = f"{old_text} {new_text}".strip()
|
| 1248 |
+
|
| 1249 |
+
if not chained:
|
| 1250 |
+
stack.append({"level": level, "subsections": node["subsections"]})
|
| 1251 |
+
prev_item = item
|
| 1252 |
+
prev_node = node
|
| 1253 |
+
|
| 1254 |
+
return roots
|
| 1255 |
+
|
| 1256 |
+
|
| 1257 |
+
def _trim_nonstatutory_tail(text: str) -> str:
|
| 1258 |
+
text = _norm_space(text)
|
| 1259 |
+
if not text:
|
| 1260 |
+
return text
|
| 1261 |
+
|
| 1262 |
+
cut_markers = [
|
| 1263 |
+
"Editorial Notes",
|
| 1264 |
+
"Statutory Notes and Related Subsidiaries",
|
| 1265 |
+
"Amendments",
|
| 1266 |
+
"References in Text",
|
| 1267 |
+
]
|
| 1268 |
+
|
| 1269 |
+
lower_text = text.lower()
|
| 1270 |
+
cut_at: Optional[int] = None
|
| 1271 |
+
for marker in cut_markers:
|
| 1272 |
+
idx = lower_text.find(marker.lower())
|
| 1273 |
+
if idx > 0:
|
| 1274 |
+
cut_at = idx if cut_at is None else min(cut_at, idx)
|
| 1275 |
+
|
| 1276 |
+
if cut_at is None:
|
| 1277 |
+
return text
|
| 1278 |
+
return _norm_space(text[:cut_at])
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
def _dedupe_keep_order(items: List[str]) -> List[str]:
|
| 1282 |
+
out: List[str] = []
|
| 1283 |
+
seen = set()
|
| 1284 |
+
for item in items:
|
| 1285 |
+
value = _norm_space(item)
|
| 1286 |
+
if not value or value in seen:
|
| 1287 |
+
continue
|
| 1288 |
+
seen.add(value)
|
| 1289 |
+
out.append(value)
|
| 1290 |
+
return out
|
| 1291 |
+
|
| 1292 |
+
|
| 1293 |
+
def _extract_chapter_info(
|
| 1294 |
+
text: str,
|
| 1295 |
+
*,
|
| 1296 |
+
title_num: str,
|
| 1297 |
+
title_name: str,
|
| 1298 |
+
heading: str,
|
| 1299 |
+
) -> Dict[str, Any]:
|
| 1300 |
+
source = str(text or "")
|
| 1301 |
+
|
| 1302 |
+
for pattern in (CHAPTER_RE, SUBCHAPTER_RE, PART_RE):
|
| 1303 |
+
match = pattern.search(source)
|
| 1304 |
+
if match:
|
| 1305 |
+
chapter_label = _norm_space(match.group(1)).upper()
|
| 1306 |
+
chapter_name = _norm_space(match.group(2))
|
| 1307 |
+
if chapter_name:
|
| 1308 |
+
return {
|
| 1309 |
+
"chapter_label": chapter_label,
|
| 1310 |
+
"chapter_name": chapter_name,
|
| 1311 |
+
"chapter_inferred": False,
|
| 1312 |
+
}
|
| 1313 |
+
|
| 1314 |
+
heading_text = _norm_space(heading)
|
| 1315 |
+
heading_match = re.search(r"\b(CHAPTER\s+[A-Z0-9\-]+)\b", heading_text, flags=re.IGNORECASE)
|
| 1316 |
+
if heading_match:
|
| 1317 |
+
return {
|
| 1318 |
+
"chapter_label": _norm_space(heading_match.group(1)).upper(),
|
| 1319 |
+
"chapter_name": heading_text,
|
| 1320 |
+
"chapter_inferred": True,
|
| 1321 |
+
}
|
| 1322 |
+
|
| 1323 |
+
return {
|
| 1324 |
+
"chapter_label": f"TITLE {str(title_num).strip()}",
|
| 1325 |
+
"chapter_name": _norm_space(title_name),
|
| 1326 |
+
"chapter_inferred": True,
|
| 1327 |
+
}
|
| 1328 |
+
|
| 1329 |
+
|
| 1330 |
+
def _extract_section_body(text: str, section_number: str, heading: str) -> str:
|
| 1331 |
+
core = _trim_nonstatutory_tail(text)
|
| 1332 |
+
section_patterns = [
|
| 1333 |
+
rf"§\s*{re.escape(section_number)}\.?\s*",
|
| 1334 |
+
rf"Sec\.\s*{re.escape(section_number)}\s*-\s*",
|
| 1335 |
+
]
|
| 1336 |
+
|
| 1337 |
+
body = core
|
| 1338 |
+
for pattern in section_patterns:
|
| 1339 |
+
match = re.search(pattern, core, flags=re.IGNORECASE)
|
| 1340 |
+
if match:
|
| 1341 |
+
body = core[match.end() :]
|
| 1342 |
+
break
|
| 1343 |
+
|
| 1344 |
+
heading_clean = _norm_space(heading)
|
| 1345 |
+
if heading_clean and body.lower().startswith(heading_clean.lower()):
|
| 1346 |
+
body = body[len(heading_clean) :].lstrip(" -:;,.\t")
|
| 1347 |
+
|
| 1348 |
+
return _norm_space(body)
|
| 1349 |
+
|
| 1350 |
+
|
| 1351 |
+
def _extract_preamble(section_body: str) -> str:
|
| 1352 |
+
text = _norm_space(section_body)
|
| 1353 |
+
if not text:
|
| 1354 |
+
return ""
|
| 1355 |
+
|
| 1356 |
+
markers = _find_subsec_markers(text)
|
| 1357 |
+
if markers and int(markers[0][0]) > 0:
|
| 1358 |
+
return _norm_space(text[: int(markers[0][0])])
|
| 1359 |
+
|
| 1360 |
+
sentence_match = re.match(r"(.{1,500}?[\.;:])(\s|$)", text)
|
| 1361 |
+
if sentence_match:
|
| 1362 |
+
return _norm_space(sentence_match.group(1))
|
| 1363 |
+
return _norm_space(text[:500])
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
def _extract_citations(text: str, core_text: str = "") -> Dict[str, List[str]]:
|
| 1367 |
+
base = str(text or "")
|
| 1368 |
+
core = str(core_text or "") or base
|
| 1369 |
+
public_laws = _dedupe_keep_order(
|
| 1370 |
+
PUBLIC_LAW_CITATION_RE.findall(base)
|
| 1371 |
+
+ PUBLIC_LAW_LONGFORM_RE.findall(base)
|
| 1372 |
+
+ PUBLIC_LAW_CONGRESS_RE.findall(base)
|
| 1373 |
+
)
|
| 1374 |
+
statutes_at_large = _dedupe_keep_order(STAT_CITATION_RE.findall(base))
|
| 1375 |
+
usc_citations = _dedupe_keep_order(
|
| 1376 |
+
USC_CITATION_RE.findall(core)
|
| 1377 |
+
+ TITLE_SECTION_CITATION_RE.findall(core)
|
| 1378 |
+
+ THIS_TITLE_SECTION_CITATION_RE.findall(core)
|
| 1379 |
+
+ THIS_CHAPTER_SECTION_CITATION_RE.findall(core)
|
| 1380 |
+
)
|
| 1381 |
+
usc_citations = [
|
| 1382 |
+
item
|
| 1383 |
+
for item in usc_citations
|
| 1384 |
+
if "united states code" not in item.lower() and "u.s.c. title" not in item.lower()
|
| 1385 |
+
]
|
| 1386 |
+
session_laws = _dedupe_keep_order(
|
| 1387 |
+
ACT_CITATION_RE.findall(base) + CHAPTER_STAT_CITATION_RE.findall(base)
|
| 1388 |
+
)
|
| 1389 |
+
if not public_laws:
|
| 1390 |
+
public_laws = _dedupe_keep_order(session_laws + statutes_at_large)
|
| 1391 |
+
return {
|
| 1392 |
+
"public_laws": public_laws,
|
| 1393 |
+
"statutes_at_large": statutes_at_large,
|
| 1394 |
+
"usc_citations": usc_citations,
|
| 1395 |
+
"session_laws": session_laws,
|
| 1396 |
+
}
|
| 1397 |
+
|
| 1398 |
+
|
| 1399 |
+
def _extract_legislative_history(full_text: str, core_text: str) -> Dict[str, Any]:
|
| 1400 |
+
enactment_blocks: List[str] = []
|
| 1401 |
+
for match in re.finditer(r"\(([^)]{3,1800})\)", core_text):
|
| 1402 |
+
block = _norm_space(match.group(1))
|
| 1403 |
+
if not block:
|
| 1404 |
+
continue
|
| 1405 |
+
if re.search(
|
| 1406 |
+
r"(Pub\.?\s*L\.?|\b\d+\s+Stat\.?\s+\d+\b|\bch\.\s*\d+)", block, flags=re.IGNORECASE
|
| 1407 |
+
):
|
| 1408 |
+
enactment_blocks.append(block)
|
| 1409 |
+
|
| 1410 |
+
nonparen_pattern = re.compile(
|
| 1411 |
+
r"([^.;]{0,160}(?:Pub\.?\s*L\.?\s*\d+[–-]\d+|\b\d+\s+Stat\.?\s+\d+\b|Act\s+[A-Z][a-z]{2,9}\.?\s+\d{1,2},\s+\d{4})[^.;]{0,260}[.;]?)",
|
| 1412 |
+
re.IGNORECASE,
|
| 1413 |
+
)
|
| 1414 |
+
for match in nonparen_pattern.finditer(str(core_text or "")):
|
| 1415 |
+
block = _norm_space(match.group(1))
|
| 1416 |
+
if block:
|
| 1417 |
+
enactment_blocks.append(block)
|
| 1418 |
+
|
| 1419 |
+
editorial_excerpt = ""
|
| 1420 |
+
editorial_idx = str(full_text or "").find("Editorial Notes")
|
| 1421 |
+
if editorial_idx >= 0:
|
| 1422 |
+
editorial_excerpt = _norm_space(str(full_text or "")[editorial_idx : editorial_idx + 3000])
|
| 1423 |
+
|
| 1424 |
+
amendment_mentions = []
|
| 1425 |
+
if editorial_excerpt:
|
| 1426 |
+
amendment_mentions = _dedupe_keep_order(
|
| 1427 |
+
PUBLIC_LAW_CITATION_RE.findall(editorial_excerpt)
|
| 1428 |
+
+ PUBLIC_LAW_LONGFORM_RE.findall(editorial_excerpt)
|
| 1429 |
+
+ PUBLIC_LAW_CONGRESS_RE.findall(editorial_excerpt)
|
| 1430 |
+
)
|
| 1431 |
+
|
| 1432 |
+
return {
|
| 1433 |
+
"enactment_citation_blocks": _dedupe_keep_order(enactment_blocks),
|
| 1434 |
+
"amendment_public_laws": amendment_mentions,
|
| 1435 |
+
"editorial_notes_excerpt": editorial_excerpt,
|
| 1436 |
+
}
|
| 1437 |
+
|
| 1438 |
+
|
| 1439 |
+
def _validate_subsection_tree(nodes: List[Dict[str, Any]], *, max_depth: int = 6) -> List[str]:
|
| 1440 |
+
issues: List[str] = []
|
| 1441 |
+
|
| 1442 |
+
def walk(siblings: List[Dict[str, Any]], depth: int, path: str) -> None:
|
| 1443 |
+
if depth > max_depth:
|
| 1444 |
+
issues.append(f"depth>{max_depth} at {path or 'root'}")
|
| 1445 |
+
|
| 1446 |
+
seen_labels: Dict[str, int] = {}
|
| 1447 |
+
for index, node in enumerate(siblings, start=1):
|
| 1448 |
+
label = str(node.get("label", ""))
|
| 1449 |
+
kind = str(node.get("kind", ""))
|
| 1450 |
+
text = _norm_space(str(node.get("text", "")))
|
| 1451 |
+
children = node.get("subsections", [])
|
| 1452 |
+
|
| 1453 |
+
if label:
|
| 1454 |
+
seen_labels[label] = seen_labels.get(label, 0) + 1
|
| 1455 |
+
if seen_labels[label] > 1:
|
| 1456 |
+
issues.append(f"duplicate sibling label {label} at {path or 'root'}")
|
| 1457 |
+
|
| 1458 |
+
if not text and not children:
|
| 1459 |
+
issues.append(f"empty leaf node {label or '#' + str(index)} at {path or 'root'}")
|
| 1460 |
+
|
| 1461 |
+
if kind not in {
|
| 1462 |
+
"numeric",
|
| 1463 |
+
"alpha_lower",
|
| 1464 |
+
"alpha_upper",
|
| 1465 |
+
"roman_lower",
|
| 1466 |
+
"roman_upper",
|
| 1467 |
+
"other",
|
| 1468 |
+
}:
|
| 1469 |
+
issues.append(f"unknown kind {kind} for {label or '#' + str(index)}")
|
| 1470 |
+
|
| 1471 |
+
child_path = f"{path}/{label}" if path else label
|
| 1472 |
+
if isinstance(children, list) and children:
|
| 1473 |
+
walk(children, depth + 1, child_path)
|
| 1474 |
+
|
| 1475 |
+
walk(nodes, depth=1, path="")
|
| 1476 |
+
return sorted(set(issues))
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
def _build_section_jsonld(section: Dict[str, Any]) -> Dict[str, Any]:
|
| 1480 |
+
title_number = str(section.get("title_number") or "")
|
| 1481 |
+
section_number = str(section.get("section_number") or "")
|
| 1482 |
+
year_value = section.get("year")
|
| 1483 |
+
source_url = str(section.get("source_url") or "")
|
| 1484 |
+
title_name = str(section.get("title_name") or "")
|
| 1485 |
+
heading = str(section.get("heading") or "")
|
| 1486 |
+
text = str(section.get("text") or "")
|
| 1487 |
+
chapter = section.get("chapter") or {}
|
| 1488 |
+
preamble = str(section.get("preamble") or "")
|
| 1489 |
+
citations = section.get("citations") or {}
|
| 1490 |
+
legislative_history = section.get("legislative_history") or {}
|
| 1491 |
+
subsections = section.get("subsections") or []
|
| 1492 |
+
parser_warnings = section.get("parser_warnings") or []
|
| 1493 |
+
|
| 1494 |
+
return {
|
| 1495 |
+
"@context": {
|
| 1496 |
+
"@vocab": "https://schema.org/",
|
| 1497 |
+
"usc": "https://uscode.house.gov/",
|
| 1498 |
+
"titleNumber": "usc:titleNumber",
|
| 1499 |
+
"sectionNumber": "usc:sectionNumber",
|
| 1500 |
+
"sourceUrl": "usc:sourceUrl",
|
| 1501 |
+
},
|
| 1502 |
+
"@type": "Legislation",
|
| 1503 |
+
"@id": f"urn:uscode:title:{title_number}:section:{section_number}:year:{year_value}",
|
| 1504 |
+
"name": heading or f"Title {title_number} Section {section_number}",
|
| 1505 |
+
"isPartOf": {
|
| 1506 |
+
"@type": "CreativeWork",
|
| 1507 |
+
"name": f"United States Code Title {title_number}",
|
| 1508 |
+
"identifier": f"USC-{title_number}",
|
| 1509 |
+
},
|
| 1510 |
+
"legislationType": "statute",
|
| 1511 |
+
"titleNumber": title_number,
|
| 1512 |
+
"titleName": title_name,
|
| 1513 |
+
"sectionNumber": section_number,
|
| 1514 |
+
"dateModified": str(year_value) if year_value is not None else None,
|
| 1515 |
+
"sourceUrl": source_url,
|
| 1516 |
+
"chapter": chapter,
|
| 1517 |
+
"preamble": preamble,
|
| 1518 |
+
"citations": citations,
|
| 1519 |
+
"legislativeHistory": legislative_history,
|
| 1520 |
+
"text": text,
|
| 1521 |
+
"subsections": subsections,
|
| 1522 |
+
"parser_warnings": parser_warnings,
|
| 1523 |
+
}
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
+
def _write_title_jsonld(
|
| 1527 |
+
*,
|
| 1528 |
+
title_number: str,
|
| 1529 |
+
year: Optional[int],
|
| 1530 |
+
sections: List[Dict[str, Any]],
|
| 1531 |
+
output_root: Path,
|
| 1532 |
+
) -> Path:
|
| 1533 |
+
jsonld_dir = output_root / DEFAULT_USCODE_JSONLD_DIRNAME
|
| 1534 |
+
jsonld_dir.mkdir(parents=True, exist_ok=True)
|
| 1535 |
+
year_part = str(year) if year is not None else "unknown"
|
| 1536 |
+
out_path = jsonld_dir / f"USCODE-{year_part}-title{title_number}.jsonld"
|
| 1537 |
+
|
| 1538 |
+
with out_path.open("w", encoding="utf-8") as handle:
|
| 1539 |
+
for section in sections:
|
| 1540 |
+
record = _build_section_jsonld(section)
|
| 1541 |
+
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 1542 |
+
return out_path
|
| 1543 |
+
|
| 1544 |
+
|
| 1545 |
+
def _resolve_output_dir(output_dir: Optional[str] = None) -> Path:
|
| 1546 |
+
if output_dir:
|
| 1547 |
+
return Path(output_dir).expanduser().resolve()
|
| 1548 |
+
return DEFAULT_USCODE_INDEX_DIR
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
async def fetch_us_code_title(
|
| 1552 |
+
title_num: str,
|
| 1553 |
+
title_name: str,
|
| 1554 |
+
include_metadata: bool = True,
|
| 1555 |
+
rate_limit_delay: float = 1.0,
|
| 1556 |
+
year: Optional[int] = None,
|
| 1557 |
+
cache_dir: Optional[Path] = None,
|
| 1558 |
+
force_download: bool = False,
|
| 1559 |
+
keep_zip_cache: bool = False,
|
| 1560 |
+
max_year_fallbacks: int = DEFAULT_USCODE_YEAR_FALLBACKS,
|
| 1561 |
+
download_retries: int = DEFAULT_USCODE_DOWNLOAD_RETRIES,
|
| 1562 |
+
) -> Dict[str, Any]:
|
| 1563 |
+
"""Fetch a US Code title from GovInfo package ZIP content.
|
| 1564 |
+
|
| 1565 |
+
Args:
|
| 1566 |
+
title_num: Title number (e.g., "18")
|
| 1567 |
+
title_name: Title name (e.g., "Crimes and Criminal Procedure")
|
| 1568 |
+
include_metadata: Include metadata like effective dates
|
| 1569 |
+
rate_limit_delay: Delay between requests
|
| 1570 |
+
|
| 1571 |
+
Returns:
|
| 1572 |
+
Dict with title data and sections
|
| 1573 |
+
"""
|
| 1574 |
+
if not REQUESTS_AVAILABLE:
|
| 1575 |
+
return {
|
| 1576 |
+
"title_number": title_num,
|
| 1577 |
+
"title_name": title_name,
|
| 1578 |
+
"source": "US Code",
|
| 1579 |
+
"source_url": "https://www.govinfo.gov/",
|
| 1580 |
+
"scraped_at": datetime.now().isoformat(),
|
| 1581 |
+
"error": "Required libraries unavailable: install requests and beautifulsoup4",
|
| 1582 |
+
"sections": [],
|
| 1583 |
+
}
|
| 1584 |
+
|
| 1585 |
+
cache_root = Path(cache_dir) if cache_dir is not None else DEFAULT_USCODE_CACHE_DIR
|
| 1586 |
+
try:
|
| 1587 |
+
session = _make_session()
|
| 1588 |
+
candidate_years = _candidate_years_for_title(
|
| 1589 |
+
session,
|
| 1590 |
+
title_num=title_num,
|
| 1591 |
+
year=year,
|
| 1592 |
+
max_year_fallbacks=max_year_fallbacks,
|
| 1593 |
+
)
|
| 1594 |
+
if not candidate_years:
|
| 1595 |
+
raise RuntimeError("Unable to discover an available USCODE package year")
|
| 1596 |
+
|
| 1597 |
+
last_error = None
|
| 1598 |
+
tried_years: List[int] = []
|
| 1599 |
+
source_attempts: List[Dict[str, Any]] = []
|
| 1600 |
+
for selected_year in candidate_years:
|
| 1601 |
+
tried_years.append(int(selected_year))
|
| 1602 |
+
try:
|
| 1603 |
+
downloaded = _download_title_zip(
|
| 1604 |
+
session,
|
| 1605 |
+
year=selected_year,
|
| 1606 |
+
title_num=title_num,
|
| 1607 |
+
cache_dir=cache_root / str(selected_year),
|
| 1608 |
+
force_download=bool(force_download),
|
| 1609 |
+
max_attempts=download_retries,
|
| 1610 |
+
include_official=True,
|
| 1611 |
+
include_recovery=False,
|
| 1612 |
+
)
|
| 1613 |
+
zip_path = Path(str(downloaded["zip_path"]))
|
| 1614 |
+
sections = _extract_sections_from_zip(
|
| 1615 |
+
zip_path,
|
| 1616 |
+
year=selected_year,
|
| 1617 |
+
title_num=title_num,
|
| 1618 |
+
title_name=title_name,
|
| 1619 |
+
include_metadata=include_metadata,
|
| 1620 |
+
source_package=f"USCODE-{int(selected_year)}-title{title_num}",
|
| 1621 |
+
)
|
| 1622 |
+
|
| 1623 |
+
if not keep_zip_cache:
|
| 1624 |
+
try:
|
| 1625 |
+
zip_path.unlink(missing_ok=True)
|
| 1626 |
+
except Exception:
|
| 1627 |
+
pass
|
| 1628 |
+
|
| 1629 |
+
await anyio.sleep(max(0.0, float(rate_limit_delay)))
|
| 1630 |
+
source_attempts.extend(list(downloaded.get("attempts") or []))
|
| 1631 |
+
source_name = str(downloaded.get("source") or "govinfo-content-zip")
|
| 1632 |
+
return {
|
| 1633 |
+
"title_number": title_num,
|
| 1634 |
+
"title_name": title_name,
|
| 1635 |
+
"source": "US Code (GovInfo package ZIP)",
|
| 1636 |
+
"source_url": downloaded.get("source_url")
|
| 1637 |
+
or _govinfo_zip_url(selected_year, title_num),
|
| 1638 |
+
"source_authority_class": downloaded.get("source_authority_class")
|
| 1639 |
+
or "official",
|
| 1640 |
+
"package_source": source_name,
|
| 1641 |
+
"scraped_at": datetime.now().isoformat(),
|
| 1642 |
+
"year": selected_year,
|
| 1643 |
+
"zip_path": str(zip_path),
|
| 1644 |
+
"candidate_years": candidate_years,
|
| 1645 |
+
"tried_years": tried_years,
|
| 1646 |
+
"source_attempts": source_attempts,
|
| 1647 |
+
"sections": sections,
|
| 1648 |
+
}
|
| 1649 |
+
except Exception as year_exc:
|
| 1650 |
+
source_attempts.append(
|
| 1651 |
+
{
|
| 1652 |
+
"source": "govinfo-package-zip",
|
| 1653 |
+
"year": int(selected_year),
|
| 1654 |
+
"status": "error",
|
| 1655 |
+
"error": str(year_exc),
|
| 1656 |
+
}
|
| 1657 |
+
)
|
| 1658 |
+
last_error = year_exc
|
| 1659 |
+
continue
|
| 1660 |
+
|
| 1661 |
+
# Secondary official fallback source: U.S. House releasepoint HTM ZIP.
|
| 1662 |
+
try:
|
| 1663 |
+
target_year = int(year) if year is not None else int(candidate_years[0])
|
| 1664 |
+
ushouse = _download_title_zip_ushouse(
|
| 1665 |
+
session,
|
| 1666 |
+
title_num=title_num,
|
| 1667 |
+
cache_dir=cache_root / "ushouse",
|
| 1668 |
+
force_download=bool(force_download),
|
| 1669 |
+
max_attempts=download_retries,
|
| 1670 |
+
year=target_year,
|
| 1671 |
+
)
|
| 1672 |
+
us_zip_path = Path(str(ushouse.get("zip_path")))
|
| 1673 |
+
sections = _extract_sections_from_zip(
|
| 1674 |
+
us_zip_path,
|
| 1675 |
+
year=target_year,
|
| 1676 |
+
title_num=title_num,
|
| 1677 |
+
title_name=title_name,
|
| 1678 |
+
include_metadata=include_metadata,
|
| 1679 |
+
source_package=str(ushouse.get("source_package") or "USHOUSE-USCODE"),
|
| 1680 |
+
section_url_base=str(ushouse.get("section_url_base") or "").strip() or None,
|
| 1681 |
+
)
|
| 1682 |
+
|
| 1683 |
+
if not keep_zip_cache:
|
| 1684 |
+
try:
|
| 1685 |
+
us_zip_path.unlink(missing_ok=True)
|
| 1686 |
+
except Exception:
|
| 1687 |
+
pass
|
| 1688 |
+
|
| 1689 |
+
await anyio.sleep(max(0.0, float(rate_limit_delay)))
|
| 1690 |
+
source_attempts.append(
|
| 1691 |
+
{
|
| 1692 |
+
"source": "ushouse-releasepoint-htm-zip",
|
| 1693 |
+
"status": "success",
|
| 1694 |
+
"source_url": ushouse.get("source_url"),
|
| 1695 |
+
"source_congress": ushouse.get("source_congress"),
|
| 1696 |
+
"source_release": ushouse.get("source_release"),
|
| 1697 |
+
}
|
| 1698 |
+
)
|
| 1699 |
+
return {
|
| 1700 |
+
"title_number": title_num,
|
| 1701 |
+
"title_name": title_name,
|
| 1702 |
+
"source": "US Code (US House releasepoint HTM ZIP)",
|
| 1703 |
+
"source_url": ushouse.get("source_url"),
|
| 1704 |
+
"source_authority_class": "official",
|
| 1705 |
+
"package_source": "ushouse-releasepoint-htm-zip",
|
| 1706 |
+
"scraped_at": datetime.now().isoformat(),
|
| 1707 |
+
"year": target_year,
|
| 1708 |
+
"zip_path": str(us_zip_path),
|
| 1709 |
+
"candidate_years": candidate_years,
|
| 1710 |
+
"tried_years": tried_years,
|
| 1711 |
+
"source_attempts": source_attempts,
|
| 1712 |
+
"sections": sections,
|
| 1713 |
+
}
|
| 1714 |
+
except Exception as ushouse_exc:
|
| 1715 |
+
source_attempts.append(
|
| 1716 |
+
{
|
| 1717 |
+
"source": "ushouse-releasepoint-htm-zip",
|
| 1718 |
+
"status": "error",
|
| 1719 |
+
"error": str(ushouse_exc),
|
| 1720 |
+
}
|
| 1721 |
+
)
|
| 1722 |
+
last_error = RuntimeError(
|
| 1723 |
+
f"GovInfo package ZIP attempts failed ({tried_years}); "
|
| 1724 |
+
f"US House fallback also failed: {ushouse_exc}"
|
| 1725 |
+
)
|
| 1726 |
+
|
| 1727 |
+
# Recovery-only: Wayback (and optional Common Crawl) of the GovInfo ZIP.
|
| 1728 |
+
for selected_year in tried_years or candidate_years:
|
| 1729 |
+
try:
|
| 1730 |
+
recovered = _download_title_zip(
|
| 1731 |
+
session,
|
| 1732 |
+
year=int(selected_year),
|
| 1733 |
+
title_num=title_num,
|
| 1734 |
+
cache_dir=cache_root / "recovery" / str(selected_year),
|
| 1735 |
+
force_download=bool(force_download),
|
| 1736 |
+
max_attempts=max(1, int(download_retries)),
|
| 1737 |
+
include_official=False,
|
| 1738 |
+
include_recovery=True,
|
| 1739 |
+
)
|
| 1740 |
+
if str(recovered.get("source_authority_class") or "") != "recovery":
|
| 1741 |
+
continue
|
| 1742 |
+
rec_path = Path(str(recovered["zip_path"]))
|
| 1743 |
+
sections = _extract_sections_from_zip(
|
| 1744 |
+
rec_path,
|
| 1745 |
+
year=int(selected_year),
|
| 1746 |
+
title_num=title_num,
|
| 1747 |
+
title_name=title_name,
|
| 1748 |
+
include_metadata=include_metadata,
|
| 1749 |
+
source_package=f"USCODE-{int(selected_year)}-title{title_num}",
|
| 1750 |
+
)
|
| 1751 |
+
if not keep_zip_cache:
|
| 1752 |
+
try:
|
| 1753 |
+
rec_path.unlink(missing_ok=True)
|
| 1754 |
+
except Exception:
|
| 1755 |
+
pass
|
| 1756 |
+
source_attempts.extend(list(recovered.get("attempts") or []))
|
| 1757 |
+
return {
|
| 1758 |
+
"title_number": title_num,
|
| 1759 |
+
"title_name": title_name,
|
| 1760 |
+
"source": "US Code (archive recovery ZIP)",
|
| 1761 |
+
"source_url": recovered.get("source_url"),
|
| 1762 |
+
"source_authority_class": "recovery",
|
| 1763 |
+
"package_source": recovered.get("source"),
|
| 1764 |
+
"scraped_at": datetime.now().isoformat(),
|
| 1765 |
+
"year": int(selected_year),
|
| 1766 |
+
"zip_path": str(rec_path),
|
| 1767 |
+
"candidate_years": candidate_years,
|
| 1768 |
+
"tried_years": tried_years,
|
| 1769 |
+
"source_attempts": source_attempts,
|
| 1770 |
+
"sections": sections,
|
| 1771 |
+
}
|
| 1772 |
+
except Exception as recovery_exc:
|
| 1773 |
+
source_attempts.append(
|
| 1774 |
+
{
|
| 1775 |
+
"source": "archive-recovery-zip",
|
| 1776 |
+
"year": int(selected_year),
|
| 1777 |
+
"status": "error",
|
| 1778 |
+
"error": str(recovery_exc),
|
| 1779 |
+
}
|
| 1780 |
+
)
|
| 1781 |
+
last_error = recovery_exc
|
| 1782 |
+
continue
|
| 1783 |
+
|
| 1784 |
+
raise RuntimeError(
|
| 1785 |
+
f"Failed to fetch title {title_num} after trying years {tried_years}: {last_error}"
|
| 1786 |
+
)
|
| 1787 |
+
except Exception as e:
|
| 1788 |
+
logger.error("Failed to fetch title %s: %s", title_num, e)
|
| 1789 |
+
return {
|
| 1790 |
+
"title_number": title_num,
|
| 1791 |
+
"title_name": title_name,
|
| 1792 |
+
"source": "US Code",
|
| 1793 |
+
"source_url": "https://www.govinfo.gov/",
|
| 1794 |
+
"scraped_at": datetime.now().isoformat(),
|
| 1795 |
+
"error": str(e),
|
| 1796 |
+
"candidate_years": [],
|
| 1797 |
+
"tried_years": [],
|
| 1798 |
+
"sections": [],
|
| 1799 |
+
}
|
| 1800 |
+
|
| 1801 |
+
|
| 1802 |
+
async def search_us_code(
|
| 1803 |
+
query: str,
|
| 1804 |
+
titles: Optional[List[str]] = None,
|
| 1805 |
+
max_results: int = 100,
|
| 1806 |
+
limit: Optional[int] = None, # Alias for max_results
|
| 1807 |
+
index_path: Optional[str] = None,
|
| 1808 |
+
) -> Dict[str, Any]:
|
| 1809 |
+
"""Search US Code for sections matching a query.
|
| 1810 |
+
|
| 1811 |
+
Args:
|
| 1812 |
+
query: Search query string
|
| 1813 |
+
titles: Optional list of title numbers to search within
|
| 1814 |
+
max_results: Maximum number of results to return
|
| 1815 |
+
limit: Alias for max_results (for compatibility)
|
| 1816 |
+
|
| 1817 |
+
Returns:
|
| 1818 |
+
Dict with search results
|
| 1819 |
+
"""
|
| 1820 |
+
if limit is not None:
|
| 1821 |
+
max_results = limit
|
| 1822 |
+
|
| 1823 |
+
try:
|
| 1824 |
+
query_text = str(query or "").strip().lower()
|
| 1825 |
+
if not query_text:
|
| 1826 |
+
return {
|
| 1827 |
+
"status": "error",
|
| 1828 |
+
"error": "Query must be non-empty",
|
| 1829 |
+
"results": [],
|
| 1830 |
+
}
|
| 1831 |
+
|
| 1832 |
+
title_filter = set(_normalize_titles(titles)) if titles else None
|
| 1833 |
+
resolved_index_path = (
|
| 1834 |
+
Path(index_path).expanduser().resolve() if index_path else DEFAULT_USCODE_INDEX_PATH
|
| 1835 |
+
)
|
| 1836 |
+
rows = _load_index_jsonl(resolved_index_path)
|
| 1837 |
+
if not rows:
|
| 1838 |
+
return {
|
| 1839 |
+
"status": "error",
|
| 1840 |
+
"error": "No local US Code index found. Run scrape_us_code() first.",
|
| 1841 |
+
"results": [],
|
| 1842 |
+
}
|
| 1843 |
+
|
| 1844 |
+
results: List[Dict[str, Any]] = []
|
| 1845 |
+
for row in rows:
|
| 1846 |
+
title_num = str(row.get("title_number") or "").strip()
|
| 1847 |
+
if title_filter and title_num not in title_filter:
|
| 1848 |
+
continue
|
| 1849 |
+
|
| 1850 |
+
heading = str(row.get("heading") or "")
|
| 1851 |
+
text = str(row.get("text") or "")
|
| 1852 |
+
haystack = f"{heading}\n{text}".lower()
|
| 1853 |
+
if query_text not in haystack:
|
| 1854 |
+
continue
|
| 1855 |
+
|
| 1856 |
+
idx = haystack.find(query_text)
|
| 1857 |
+
lo = max(0, idx - 200)
|
| 1858 |
+
hi = min(len(text), lo + 500)
|
| 1859 |
+
snippet = text[lo:hi].strip() if text else heading[:500]
|
| 1860 |
+
|
| 1861 |
+
results.append(
|
| 1862 |
+
{
|
| 1863 |
+
"title_number": title_num,
|
| 1864 |
+
"title_name": row.get("title_name"),
|
| 1865 |
+
"section_number": row.get("section_number"),
|
| 1866 |
+
"title": f"Title {title_num} § {row.get('section_number')}",
|
| 1867 |
+
"snippet": snippet,
|
| 1868 |
+
"url": row.get("source_url", ""),
|
| 1869 |
+
"year": row.get("year"),
|
| 1870 |
+
}
|
| 1871 |
+
)
|
| 1872 |
+
if len(results) >= int(max_results):
|
| 1873 |
+
break
|
| 1874 |
+
|
| 1875 |
+
return {
|
| 1876 |
+
"status": "success",
|
| 1877 |
+
"query": query,
|
| 1878 |
+
"results": results,
|
| 1879 |
+
"count": len(results),
|
| 1880 |
+
"index_path": str(resolved_index_path),
|
| 1881 |
+
}
|
| 1882 |
+
except Exception as e:
|
| 1883 |
+
logger.error("US Code search failed: %s", e)
|
| 1884 |
+
return {
|
| 1885 |
+
"status": "error",
|
| 1886 |
+
"error": str(e),
|
| 1887 |
+
"results": [],
|
| 1888 |
+
}
|
| 1889 |
+
|
| 1890 |
+
|
| 1891 |
+
async def get_us_code_titles() -> Dict[str, Any]:
|
| 1892 |
+
"""Get list of all US Code titles.
|
| 1893 |
+
|
| 1894 |
+
Returns:
|
| 1895 |
+
Dict containing:
|
| 1896 |
+
- status: "success" or "error"
|
| 1897 |
+
- titles: Dictionary mapping title numbers to names
|
| 1898 |
+
- count: Number of titles
|
| 1899 |
+
- error: Error message (if failed)
|
| 1900 |
+
"""
|
| 1901 |
+
try:
|
| 1902 |
+
return {
|
| 1903 |
+
"status": "success",
|
| 1904 |
+
"titles": US_CODE_TITLES,
|
| 1905 |
+
"count": len(US_CODE_TITLES),
|
| 1906 |
+
"source": "US Code - GovInfo package titles",
|
| 1907 |
+
}
|
| 1908 |
+
except Exception as e:
|
| 1909 |
+
logger.error(f"Failed to get US Code titles: {e}")
|
| 1910 |
+
return {"status": "error", "error": str(e), "titles": {}, "count": 0}
|
| 1911 |
+
|
| 1912 |
+
|
| 1913 |
+
async def scrape_us_code(
|
| 1914 |
+
titles: Optional[List[str]] = None,
|
| 1915 |
+
output_format: str = "json",
|
| 1916 |
+
include_metadata: bool = True,
|
| 1917 |
+
rate_limit_delay: float = 1.0,
|
| 1918 |
+
max_sections: Optional[int] = None,
|
| 1919 |
+
year: Optional[int] = None,
|
| 1920 |
+
cache_dir: Optional[str] = None,
|
| 1921 |
+
force_download: bool = False,
|
| 1922 |
+
output_dir: Optional[str] = None,
|
| 1923 |
+
keep_zip_cache: bool = False,
|
| 1924 |
+
max_year_fallbacks: int = DEFAULT_USCODE_YEAR_FALLBACKS,
|
| 1925 |
+
download_retries: int = DEFAULT_USCODE_DOWNLOAD_RETRIES,
|
| 1926 |
+
continue_on_error: bool = True,
|
| 1927 |
+
) -> Dict[str, Any]:
|
| 1928 |
+
"""Scrape US Code sections and build a structured dataset.
|
| 1929 |
+
|
| 1930 |
+
Args:
|
| 1931 |
+
titles: List of title numbers to scrape (e.g., ["1", "15", "18"]).
|
| 1932 |
+
If None or ["all"], scrapes all titles.
|
| 1933 |
+
output_format: Output format - "json" or "parquet"
|
| 1934 |
+
include_metadata: Include section metadata (effective dates, amendments, etc.)
|
| 1935 |
+
rate_limit_delay: Delay between requests in seconds (default 1.0)
|
| 1936 |
+
max_sections: Maximum number of sections to scrape (for testing/limiting)
|
| 1937 |
+
|
| 1938 |
+
Returns:
|
| 1939 |
+
Dict containing:
|
| 1940 |
+
- status: "success" or "error"
|
| 1941 |
+
- data: Scraped US Code sections
|
| 1942 |
+
- metadata: Scraping metadata (titles, count, timing)
|
| 1943 |
+
- output_format: Format of the data
|
| 1944 |
+
- error: Error message (if failed)
|
| 1945 |
+
"""
|
| 1946 |
+
try:
|
| 1947 |
+
selected_titles = _normalize_titles(titles)
|
| 1948 |
+
if not selected_titles:
|
| 1949 |
+
return {
|
| 1950 |
+
"status": "error",
|
| 1951 |
+
"error": "No valid titles specified",
|
| 1952 |
+
"data": [],
|
| 1953 |
+
"metadata": {},
|
| 1954 |
+
}
|
| 1955 |
+
|
| 1956 |
+
logger.info("Starting US Code scraping for titles: %s", selected_titles)
|
| 1957 |
+
start_time = time.time()
|
| 1958 |
+
|
| 1959 |
+
if not REQUESTS_AVAILABLE:
|
| 1960 |
+
return {
|
| 1961 |
+
"status": "error",
|
| 1962 |
+
"error": "Required libraries unavailable: install requests and beautifulsoup4",
|
| 1963 |
+
"data": [],
|
| 1964 |
+
"metadata": {},
|
| 1965 |
+
}
|
| 1966 |
+
|
| 1967 |
+
output_root = _resolve_output_dir(output_dir)
|
| 1968 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 1969 |
+
cache_root = (
|
| 1970 |
+
Path(cache_dir).expanduser().resolve() if cache_dir else (output_root / "cache")
|
| 1971 |
+
)
|
| 1972 |
+
index_path = output_root / "uscode_index_latest.jsonl"
|
| 1973 |
+
jsonld_paths: List[str] = []
|
| 1974 |
+
scraped_titles: List[Dict[str, Any]] = []
|
| 1975 |
+
failed_titles: List[Dict[str, Any]] = []
|
| 1976 |
+
sections_count = 0
|
| 1977 |
+
|
| 1978 |
+
for title_num in selected_titles:
|
| 1979 |
+
if max_sections and sections_count >= max_sections:
|
| 1980 |
+
logger.info("Reached max_sections limit of %s", max_sections)
|
| 1981 |
+
break
|
| 1982 |
+
|
| 1983 |
+
title_name = US_CODE_TITLES[title_num]
|
| 1984 |
+
logger.info("Scraping Title %s: %s", title_num, title_name)
|
| 1985 |
+
|
| 1986 |
+
title_data = await fetch_us_code_title(
|
| 1987 |
+
title_num,
|
| 1988 |
+
title_name,
|
| 1989 |
+
include_metadata=include_metadata,
|
| 1990 |
+
rate_limit_delay=rate_limit_delay,
|
| 1991 |
+
year=year,
|
| 1992 |
+
cache_dir=cache_root,
|
| 1993 |
+
force_download=force_download,
|
| 1994 |
+
keep_zip_cache=keep_zip_cache,
|
| 1995 |
+
max_year_fallbacks=max_year_fallbacks,
|
| 1996 |
+
download_retries=download_retries,
|
| 1997 |
+
)
|
| 1998 |
+
|
| 1999 |
+
title_error = str(title_data.get("error") or "").strip()
|
| 2000 |
+
if title_error:
|
| 2001 |
+
failed_titles.append(
|
| 2002 |
+
{
|
| 2003 |
+
"title_number": title_num,
|
| 2004 |
+
"title_name": title_name,
|
| 2005 |
+
"error": title_error,
|
| 2006 |
+
"candidate_years": title_data.get("candidate_years", []),
|
| 2007 |
+
"tried_years": title_data.get("tried_years", []),
|
| 2008 |
+
}
|
| 2009 |
+
)
|
| 2010 |
+
if not continue_on_error:
|
| 2011 |
+
break
|
| 2012 |
+
continue
|
| 2013 |
+
|
| 2014 |
+
sections = (
|
| 2015 |
+
list(title_data.get("sections") or []) if isinstance(title_data, dict) else []
|
| 2016 |
+
)
|
| 2017 |
+
if max_sections is not None and sections:
|
| 2018 |
+
remaining = int(max_sections) - int(sections_count)
|
| 2019 |
+
if remaining <= 0:
|
| 2020 |
+
sections = []
|
| 2021 |
+
elif len(sections) > remaining:
|
| 2022 |
+
sections = sections[:remaining]
|
| 2023 |
+
title_data["sections"] = sections
|
| 2024 |
+
|
| 2025 |
+
if sections:
|
| 2026 |
+
jsonld_path = _write_title_jsonld(
|
| 2027 |
+
title_number=title_num,
|
| 2028 |
+
year=title_data.get("year"),
|
| 2029 |
+
sections=sections,
|
| 2030 |
+
output_root=output_root,
|
| 2031 |
+
)
|
| 2032 |
+
title_data["jsonld_path"] = str(jsonld_path)
|
| 2033 |
+
jsonld_paths.append(str(jsonld_path))
|
| 2034 |
+
scraped_titles.append(title_data)
|
| 2035 |
+
sections_count += len(sections)
|
| 2036 |
+
else:
|
| 2037 |
+
failed_titles.append(
|
| 2038 |
+
{
|
| 2039 |
+
"title_number": title_num,
|
| 2040 |
+
"title_name": title_name,
|
| 2041 |
+
"error": "No sections extracted",
|
| 2042 |
+
"candidate_years": title_data.get("candidate_years", []),
|
| 2043 |
+
"tried_years": title_data.get("tried_years", []),
|
| 2044 |
+
}
|
| 2045 |
+
)
|
| 2046 |
+
if not continue_on_error:
|
| 2047 |
+
break
|
| 2048 |
+
|
| 2049 |
+
elapsed_time = time.time() - start_time
|
| 2050 |
+
|
| 2051 |
+
flat_sections: List[Dict[str, Any]] = []
|
| 2052 |
+
for title_blob in scraped_titles:
|
| 2053 |
+
title_num = str(title_blob.get("title_number") or "")
|
| 2054 |
+
title_name = str(title_blob.get("title_name") or US_CODE_TITLES.get(title_num, ""))
|
| 2055 |
+
year_value = title_blob.get("year")
|
| 2056 |
+
for section in title_blob.get("sections") or []:
|
| 2057 |
+
if not isinstance(section, dict):
|
| 2058 |
+
continue
|
| 2059 |
+
row = dict(section)
|
| 2060 |
+
row.setdefault("title_number", title_num)
|
| 2061 |
+
row.setdefault("title_name", title_name)
|
| 2062 |
+
row.setdefault("year", year_value)
|
| 2063 |
+
flat_sections.append(row)
|
| 2064 |
+
|
| 2065 |
+
_write_index_jsonl(flat_sections, index_path=index_path)
|
| 2066 |
+
|
| 2067 |
+
effective_year = None
|
| 2068 |
+
if scraped_titles:
|
| 2069 |
+
effective_year = scraped_titles[0].get("year")
|
| 2070 |
+
|
| 2071 |
+
metadata = {
|
| 2072 |
+
"titles_requested": selected_titles,
|
| 2073 |
+
"titles_requested_count": len(selected_titles),
|
| 2074 |
+
"titles_scraped": [str(t.get("title_number")) for t in scraped_titles],
|
| 2075 |
+
"titles_count": len(scraped_titles),
|
| 2076 |
+
"failed_titles": failed_titles,
|
| 2077 |
+
"failed_titles_count": len(failed_titles),
|
| 2078 |
+
"sections_count": sections_count,
|
| 2079 |
+
"elapsed_time_seconds": elapsed_time,
|
| 2080 |
+
"scraped_at": datetime.now().isoformat(),
|
| 2081 |
+
"source": "GovInfo USCODE package ZIP",
|
| 2082 |
+
"rate_limit_delay": rate_limit_delay,
|
| 2083 |
+
"include_metadata": include_metadata,
|
| 2084 |
+
"year": effective_year,
|
| 2085 |
+
"cache_dir": str(cache_root),
|
| 2086 |
+
"index_path": str(index_path),
|
| 2087 |
+
"output_dir": str(output_root),
|
| 2088 |
+
"force_download": bool(force_download),
|
| 2089 |
+
"keep_zip_cache": bool(keep_zip_cache),
|
| 2090 |
+
"max_year_fallbacks": int(max_year_fallbacks),
|
| 2091 |
+
"download_retries": int(download_retries),
|
| 2092 |
+
"continue_on_error": bool(continue_on_error),
|
| 2093 |
+
"jsonld_dir": str(output_root / DEFAULT_USCODE_JSONLD_DIRNAME),
|
| 2094 |
+
"jsonld_files": jsonld_paths,
|
| 2095 |
+
}
|
| 2096 |
+
|
| 2097 |
+
logger.info(
|
| 2098 |
+
"Completed US Code scraping: %s sections in %.2fs", sections_count, elapsed_time
|
| 2099 |
+
)
|
| 2100 |
+
|
| 2101 |
+
if not scraped_titles:
|
| 2102 |
+
return {
|
| 2103 |
+
"status": "error",
|
| 2104 |
+
"error": "No US Code titles were successfully scraped",
|
| 2105 |
+
"data": scraped_titles,
|
| 2106 |
+
"metadata": metadata,
|
| 2107 |
+
"output_format": output_format,
|
| 2108 |
+
"note": "Comprehensive title-package ingestion from GovInfo USCODE ZIP sources.",
|
| 2109 |
+
}
|
| 2110 |
+
|
| 2111 |
+
return {
|
| 2112 |
+
"status": "success",
|
| 2113 |
+
"data": scraped_titles,
|
| 2114 |
+
"metadata": metadata,
|
| 2115 |
+
"output_format": output_format,
|
| 2116 |
+
"note": "Comprehensive title-package ingestion from GovInfo USCODE ZIP sources.",
|
| 2117 |
+
}
|
| 2118 |
+
|
| 2119 |
+
except Exception as e:
|
| 2120 |
+
logger.error("US Code scraping failed: %s", e)
|
| 2121 |
+
return {
|
| 2122 |
+
"status": "error",
|
| 2123 |
+
"error": str(e),
|
| 2124 |
+
"data": [],
|
| 2125 |
+
"metadata": {},
|
| 2126 |
+
}
|
| 2127 |
+
|
| 2128 |
+
|
| 2129 |
+
__all__ = [
|
| 2130 |
+
"build_public_law_url",
|
| 2131 |
+
"build_uscode_section_url",
|
| 2132 |
+
"get_us_code_titles",
|
| 2133 |
+
"scrape_us_code",
|
| 2134 |
+
"search_us_code",
|
| 2135 |
+
"fetch_us_code_title",
|
| 2136 |
+
]
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/us_code_verifier.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""US Code verification engine — canonical domain module.
|
| 2 |
+
|
| 3 |
+
Verification suite for testing the US Code scraper. Imported by:
|
| 4 |
+
ipfs_datasets_py.mcp_server.tools.legal_dataset_tools.verify_us_code_scraper
|
| 5 |
+
|
| 6 |
+
Usage::
|
| 7 |
+
|
| 8 |
+
from ipfs_datasets_py.processors.legal_scrapers.us_code_verifier import (
|
| 9 |
+
USCodeVerifier,
|
| 10 |
+
)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any, Dict, List
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from ipfs_datasets_py.processors.legal_scrapers.federal_scrapers.us_code_scraper import (
|
| 20 |
+
scrape_us_code,
|
| 21 |
+
get_us_code_titles,
|
| 22 |
+
search_us_code,
|
| 23 |
+
)
|
| 24 |
+
except ImportError:
|
| 25 |
+
scrape_us_code = None # type: ignore[assignment]
|
| 26 |
+
get_us_code_titles = None # type: ignore[assignment]
|
| 27 |
+
search_us_code = None # type: ignore[assignment]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class USCodeVerifier:
|
| 31 |
+
"""Verification suite for US Code scraper."""
|
| 32 |
+
|
| 33 |
+
def __init__(self):
|
| 34 |
+
self.results = {
|
| 35 |
+
"timestamp": datetime.now().isoformat(),
|
| 36 |
+
"tests": [],
|
| 37 |
+
"summary": {"total": 0, "passed": 0, "failed": 0, "warnings": 0},
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
def log_test(self, name: str, status: str, message: str, details: Dict[str, Any] = None):
|
| 41 |
+
"""Log a test result."""
|
| 42 |
+
test_result = {"name": name, "status": status, "message": message, "details": details or {}}
|
| 43 |
+
self.results["tests"].append(test_result)
|
| 44 |
+
self.results["summary"]["total"] += 1
|
| 45 |
+
|
| 46 |
+
if status == "PASS":
|
| 47 |
+
self.results["summary"]["passed"] += 1
|
| 48 |
+
print(f"✅ {name}: {message}")
|
| 49 |
+
elif status == "FAIL":
|
| 50 |
+
self.results["summary"]["failed"] += 1
|
| 51 |
+
print(f"❌ {name}: {message}")
|
| 52 |
+
elif status == "WARN":
|
| 53 |
+
self.results["summary"]["warnings"] += 1
|
| 54 |
+
print(f"⚠️ {name}: {message}")
|
| 55 |
+
|
| 56 |
+
if details:
|
| 57 |
+
print(f" Details: {json.dumps(details, indent=2)}")
|
| 58 |
+
|
| 59 |
+
async def test_get_titles(self):
|
| 60 |
+
"""Test fetching US Code titles."""
|
| 61 |
+
print("\n" + "=" * 80)
|
| 62 |
+
print("TEST 1: Get US Code Titles")
|
| 63 |
+
print("=" * 80)
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
result = await get_us_code_titles()
|
| 67 |
+
|
| 68 |
+
if result.get("status") == "success":
|
| 69 |
+
titles = result.get("titles", {})
|
| 70 |
+
count = len(titles)
|
| 71 |
+
|
| 72 |
+
if count >= 50: # Should have ~54 titles
|
| 73 |
+
self.log_test(
|
| 74 |
+
"Get Titles",
|
| 75 |
+
"PASS",
|
| 76 |
+
f"Retrieved {count} US Code titles",
|
| 77 |
+
{"title_count": count, "sample_titles": list(titles.items())[:5]},
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
self.log_test(
|
| 81 |
+
"Get Titles",
|
| 82 |
+
"WARN",
|
| 83 |
+
f"Retrieved only {count} titles (expected ~54)",
|
| 84 |
+
{"title_count": count},
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
self.log_test(
|
| 88 |
+
"Get Titles", "FAIL", f"Failed to get titles: {result.get('error')}", result
|
| 89 |
+
)
|
| 90 |
+
except Exception as e:
|
| 91 |
+
self.log_test("Get Titles", "FAIL", f"Exception: {str(e)}")
|
| 92 |
+
|
| 93 |
+
async def test_scrape_single_title(self):
|
| 94 |
+
"""Test scraping a single title."""
|
| 95 |
+
print("\n" + "=" * 80)
|
| 96 |
+
print("TEST 2: Scrape Single Title (Title 1 - General Provisions)")
|
| 97 |
+
print("=" * 80)
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
result = await scrape_us_code(
|
| 101 |
+
titles=["1"],
|
| 102 |
+
output_format="json",
|
| 103 |
+
include_metadata=True,
|
| 104 |
+
rate_limit_delay=1.0,
|
| 105 |
+
max_sections=10, # Limit for testing
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
if result.get("status") == "success":
|
| 109 |
+
data = result.get("data", [])
|
| 110 |
+
metadata = result.get("metadata", {})
|
| 111 |
+
|
| 112 |
+
if len(data) > 0:
|
| 113 |
+
self.log_test(
|
| 114 |
+
"Scrape Single Title",
|
| 115 |
+
"PASS",
|
| 116 |
+
f"Scraped Title 1: {len(data)} sections",
|
| 117 |
+
{
|
| 118 |
+
"sections_count": len(data),
|
| 119 |
+
"sample_section": data[0] if data else None,
|
| 120 |
+
"metadata": metadata,
|
| 121 |
+
},
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
self.log_test(
|
| 125 |
+
"Scrape Single Title", "WARN", "No sections scraped from Title 1", result
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
self.log_test(
|
| 129 |
+
"Scrape Single Title", "FAIL", f"Failed: {result.get('error')}", result
|
| 130 |
+
)
|
| 131 |
+
except Exception as e:
|
| 132 |
+
self.log_test("Scrape Single Title", "FAIL", f"Exception: {str(e)}")
|
| 133 |
+
|
| 134 |
+
async def test_scrape_multiple_titles(self):
|
| 135 |
+
"""Test scraping multiple titles."""
|
| 136 |
+
print("\n" + "=" * 80)
|
| 137 |
+
print("TEST 3: Scrape Multiple Titles (1, 15, 18)")
|
| 138 |
+
print("=" * 80)
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
result = await scrape_us_code(
|
| 142 |
+
titles=["1", "15", "18"],
|
| 143 |
+
output_format="json",
|
| 144 |
+
include_metadata=True,
|
| 145 |
+
rate_limit_delay=1.0,
|
| 146 |
+
max_sections=5, # Limit per title for testing
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
if result.get("status") == "success" or result.get("status") == "partial_success":
|
| 150 |
+
data = result.get("data", [])
|
| 151 |
+
metadata = result.get("metadata", {})
|
| 152 |
+
|
| 153 |
+
# Check if we got data from multiple titles
|
| 154 |
+
titles_found = set()
|
| 155 |
+
for section in data:
|
| 156 |
+
if "title_number" in section:
|
| 157 |
+
titles_found.add(section["title_number"])
|
| 158 |
+
|
| 159 |
+
if len(titles_found) >= 2:
|
| 160 |
+
self.log_test(
|
| 161 |
+
"Scrape Multiple Titles",
|
| 162 |
+
"PASS",
|
| 163 |
+
f"Scraped {len(titles_found)} titles: {sorted(titles_found)}",
|
| 164 |
+
{
|
| 165 |
+
"titles_found": sorted(titles_found),
|
| 166 |
+
"total_sections": len(data),
|
| 167 |
+
"metadata": metadata,
|
| 168 |
+
},
|
| 169 |
+
)
|
| 170 |
+
elif len(titles_found) == 1:
|
| 171 |
+
self.log_test(
|
| 172 |
+
"Scrape Multiple Titles",
|
| 173 |
+
"WARN",
|
| 174 |
+
f"Only scraped 1 title: {titles_found}",
|
| 175 |
+
{"sections_count": len(data)},
|
| 176 |
+
)
|
| 177 |
+
else:
|
| 178 |
+
self.log_test(
|
| 179 |
+
"Scrape Multiple Titles",
|
| 180 |
+
"WARN",
|
| 181 |
+
"No title information in scraped data",
|
| 182 |
+
{"sections_count": len(data)},
|
| 183 |
+
)
|
| 184 |
+
else:
|
| 185 |
+
self.log_test(
|
| 186 |
+
"Scrape Multiple Titles", "FAIL", f"Failed: {result.get('error')}", result
|
| 187 |
+
)
|
| 188 |
+
except Exception as e:
|
| 189 |
+
self.log_test("Scrape Multiple Titles", "FAIL", f"Exception: {str(e)}")
|
| 190 |
+
|
| 191 |
+
async def test_data_structure(self):
|
| 192 |
+
"""Test that scraped data has the correct structure."""
|
| 193 |
+
print("\n" + "=" * 80)
|
| 194 |
+
print("TEST 4: Validate Data Structure")
|
| 195 |
+
print("=" * 80)
|
| 196 |
+
|
| 197 |
+
try:
|
| 198 |
+
result = await scrape_us_code(
|
| 199 |
+
titles=["15"], # Commerce and Trade
|
| 200 |
+
output_format="json",
|
| 201 |
+
include_metadata=True,
|
| 202 |
+
rate_limit_delay=1.0,
|
| 203 |
+
max_sections=3,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if result.get("status") in ["success", "partial_success"]:
|
| 207 |
+
data = result.get("data", [])
|
| 208 |
+
|
| 209 |
+
if not data:
|
| 210 |
+
self.log_test("Data Structure", "WARN", "No data to validate structure", result)
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
# Check required fields
|
| 214 |
+
required_fields = ["title_number", "title_name", "section_number"]
|
| 215 |
+
sample_section = data[0]
|
| 216 |
+
|
| 217 |
+
missing_fields = [f for f in required_fields if f not in sample_section]
|
| 218 |
+
|
| 219 |
+
if not missing_fields:
|
| 220 |
+
self.log_test(
|
| 221 |
+
"Data Structure",
|
| 222 |
+
"PASS",
|
| 223 |
+
"Data structure is valid",
|
| 224 |
+
{"sample_section": sample_section, "total_sections": len(data)},
|
| 225 |
+
)
|
| 226 |
+
else:
|
| 227 |
+
self.log_test(
|
| 228 |
+
"Data Structure",
|
| 229 |
+
"WARN",
|
| 230 |
+
f"Missing fields: {missing_fields}",
|
| 231 |
+
{"sample_section": sample_section},
|
| 232 |
+
)
|
| 233 |
+
else:
|
| 234 |
+
self.log_test(
|
| 235 |
+
"Data Structure",
|
| 236 |
+
"FAIL",
|
| 237 |
+
f"Failed to scrape data: {result.get('error')}",
|
| 238 |
+
result,
|
| 239 |
+
)
|
| 240 |
+
except Exception as e:
|
| 241 |
+
self.log_test("Data Structure", "FAIL", f"Exception: {str(e)}")
|
| 242 |
+
|
| 243 |
+
async def test_search_functionality(self):
|
| 244 |
+
"""Test search functionality."""
|
| 245 |
+
print("\n" + "=" * 80)
|
| 246 |
+
print("TEST 5: Search Functionality")
|
| 247 |
+
print("=" * 80)
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
result = await search_us_code(query="commerce", titles=["15"], limit=5)
|
| 251 |
+
|
| 252 |
+
if result.get("status") == "success":
|
| 253 |
+
results = result.get("results", [])
|
| 254 |
+
|
| 255 |
+
if len(results) > 0:
|
| 256 |
+
self.log_test(
|
| 257 |
+
"Search Functionality",
|
| 258 |
+
"PASS",
|
| 259 |
+
f"Found {len(results)} results for 'commerce'",
|
| 260 |
+
{
|
| 261 |
+
"result_count": len(results),
|
| 262 |
+
"sample_result": results[0] if results else None,
|
| 263 |
+
},
|
| 264 |
+
)
|
| 265 |
+
else:
|
| 266 |
+
self.log_test("Search Functionality", "WARN", "No search results found", result)
|
| 267 |
+
else:
|
| 268 |
+
self.log_test(
|
| 269 |
+
"Search Functionality",
|
| 270 |
+
"WARN",
|
| 271 |
+
f"Search returned status: {result.get('status')}",
|
| 272 |
+
result,
|
| 273 |
+
)
|
| 274 |
+
except Exception as e:
|
| 275 |
+
self.log_test("Search Functionality", "FAIL", f"Exception: {str(e)}")
|
| 276 |
+
|
| 277 |
+
async def test_metadata_inclusion(self):
|
| 278 |
+
"""Test that metadata is included when requested."""
|
| 279 |
+
print("\n" + "=" * 80)
|
| 280 |
+
print("TEST 6: Metadata Inclusion")
|
| 281 |
+
print("=" * 80)
|
| 282 |
+
|
| 283 |
+
try:
|
| 284 |
+
# Test with metadata
|
| 285 |
+
result_with = await scrape_us_code(titles=["1"], include_metadata=True, max_sections=2)
|
| 286 |
+
|
| 287 |
+
# Test without metadata
|
| 288 |
+
result_without = await scrape_us_code(
|
| 289 |
+
titles=["1"], include_metadata=False, max_sections=2
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
metadata_present = bool(result_with.get("metadata"))
|
| 293 |
+
|
| 294 |
+
if metadata_present:
|
| 295 |
+
self.log_test(
|
| 296 |
+
"Metadata Inclusion",
|
| 297 |
+
"PASS",
|
| 298 |
+
"Metadata is correctly included/excluded",
|
| 299 |
+
{
|
| 300 |
+
"with_metadata": bool(result_with.get("metadata")),
|
| 301 |
+
"without_metadata": bool(result_without.get("metadata")),
|
| 302 |
+
"sample_metadata": result_with.get("metadata"),
|
| 303 |
+
},
|
| 304 |
+
)
|
| 305 |
+
else:
|
| 306 |
+
self.log_test(
|
| 307 |
+
"Metadata Inclusion",
|
| 308 |
+
"WARN",
|
| 309 |
+
"Metadata not present in results",
|
| 310 |
+
{"result_with": result_with, "result_without": result_without},
|
| 311 |
+
)
|
| 312 |
+
except Exception as e:
|
| 313 |
+
self.log_test("Metadata Inclusion", "FAIL", f"Exception: {str(e)}")
|
| 314 |
+
|
| 315 |
+
async def test_rate_limiting(self):
|
| 316 |
+
"""Test that rate limiting is respected."""
|
| 317 |
+
print("\n" + "=" * 80)
|
| 318 |
+
print("TEST 7: Rate Limiting")
|
| 319 |
+
print("=" * 80)
|
| 320 |
+
|
| 321 |
+
try:
|
| 322 |
+
import time
|
| 323 |
+
|
| 324 |
+
start_time = time.time()
|
| 325 |
+
|
| 326 |
+
result = await scrape_us_code(
|
| 327 |
+
titles=["1"],
|
| 328 |
+
rate_limit_delay=2.0, # 2 second delay
|
| 329 |
+
max_sections=3,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
elapsed = time.time() - start_time
|
| 333 |
+
|
| 334 |
+
# Should take at least 4 seconds (2 delay * 2 requests minimum)
|
| 335 |
+
if elapsed >= 2.0:
|
| 336 |
+
self.log_test(
|
| 337 |
+
"Rate Limiting",
|
| 338 |
+
"PASS",
|
| 339 |
+
f"Rate limiting appears to be working (took {elapsed:.2f}s)",
|
| 340 |
+
{"elapsed_seconds": elapsed},
|
| 341 |
+
)
|
| 342 |
+
else:
|
| 343 |
+
self.log_test(
|
| 344 |
+
"Rate Limiting",
|
| 345 |
+
"WARN",
|
| 346 |
+
f"Completed too quickly ({elapsed:.2f}s), rate limiting may not be working",
|
| 347 |
+
{"elapsed_seconds": elapsed},
|
| 348 |
+
)
|
| 349 |
+
except Exception as e:
|
| 350 |
+
self.log_test("Rate Limiting", "FAIL", f"Exception: {str(e)}")
|
| 351 |
+
|
| 352 |
+
async def run_all_tests(self):
|
| 353 |
+
"""Run all verification tests."""
|
| 354 |
+
print("\n" + "=" * 80)
|
| 355 |
+
print("US CODE SCRAPER VERIFICATION")
|
| 356 |
+
print("=" * 80)
|
| 357 |
+
print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 358 |
+
|
| 359 |
+
# Run tests
|
| 360 |
+
await self.test_get_titles()
|
| 361 |
+
await self.test_scrape_single_title()
|
| 362 |
+
await self.test_scrape_multiple_titles()
|
| 363 |
+
await self.test_data_structure()
|
| 364 |
+
await self.test_search_functionality()
|
| 365 |
+
await self.test_metadata_inclusion()
|
| 366 |
+
await self.test_rate_limiting()
|
| 367 |
+
|
| 368 |
+
# Print summary
|
| 369 |
+
print("\n" + "=" * 80)
|
| 370 |
+
print("VERIFICATION SUMMARY")
|
| 371 |
+
print("=" * 80)
|
| 372 |
+
print(f"Total Tests: {self.results['summary']['total']}")
|
| 373 |
+
print(f"✅ Passed: {self.results['summary']['passed']}")
|
| 374 |
+
print(f"❌ Failed: {self.results['summary']['failed']}")
|
| 375 |
+
print(f"⚠️ Warnings: {self.results['summary']['warnings']}")
|
| 376 |
+
|
| 377 |
+
success_rate = (
|
| 378 |
+
(self.results["summary"]["passed"] / self.results["summary"]["total"] * 100)
|
| 379 |
+
if self.results["summary"]["total"] > 0
|
| 380 |
+
else 0
|
| 381 |
+
)
|
| 382 |
+
print(f"\nSuccess Rate: {success_rate:.1f}%")
|
| 383 |
+
|
| 384 |
+
# Save results
|
| 385 |
+
output_file = Path.home() / ".ipfs_datasets" / "us_code" / "verification_results.json"
|
| 386 |
+
output_file.parent.mkdir(parents=True, exist_ok=True)
|
| 387 |
+
with open(output_file, "w") as f:
|
| 388 |
+
json.dump(self.results, f, indent=2)
|
| 389 |
+
print(f"\n📁 Results saved to: {output_file}")
|
| 390 |
+
|
| 391 |
+
# Return exit code
|
| 392 |
+
return 0 if self.results["summary"]["failed"] == 0 else 1
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/uscode_release_catalog.py
ADDED
|
@@ -0,0 +1,2022 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact all-title U.S. Code release catalog (USCIR-005).
|
| 2 |
+
|
| 3 |
+
Resolves one approved exact release point, enumerates every expected title
|
| 4 |
+
package in the sealed baseline span (Titles 1–52 and 54), acquires packages
|
| 5 |
+
deterministically from sealed fixtures, checkpoints resume receipts, and
|
| 6 |
+
reports missing/excluded packages.
|
| 7 |
+
|
| 8 |
+
Design invariants
|
| 9 |
+
-----------------
|
| 10 |
+
* Fixture acquisition is deterministic (no live network I/O by default).
|
| 11 |
+
* Title completeness is explicit: every required title is accepted, excluded,
|
| 12 |
+
or reported missing — never silently omitted.
|
| 13 |
+
* Resume does not redownload verified packages whose checkpoint receipt and
|
| 14 |
+
on-disk checksum still match.
|
| 15 |
+
* Every accepted package binds a content checksum and the approved release
|
| 16 |
+
point (or an explicitly approved mixed-vintage override).
|
| 17 |
+
* Proposed-latest discovery cannot mint final provenance; admission requires
|
| 18 |
+
an approved exact release (USCIR-004).
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import tempfile
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from enum import Enum
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any, Iterable, Mapping, Optional, Sequence, Union
|
| 30 |
+
|
| 31 |
+
from ipfs_datasets_py.processors.legal_data.uscode_source_policy import (
|
| 32 |
+
CANONICAL_USCODE_TITLES,
|
| 33 |
+
CURRENTNESS_DISCLAIMER,
|
| 34 |
+
DEFAULT_ACQUIRED_AT,
|
| 35 |
+
DEFAULT_APPROVED_AT,
|
| 36 |
+
DEFAULT_APPROVED_CONGRESS,
|
| 37 |
+
DEFAULT_APPROVED_RELEASE,
|
| 38 |
+
DEFAULT_APPROVED_RELEASE_POINT,
|
| 39 |
+
DEFAULT_DISCOVERED_AT,
|
| 40 |
+
DEFAULT_PROVIDER_OLRC,
|
| 41 |
+
EXPECTED_TITLE_COUNT,
|
| 42 |
+
USHOUSE_DOWNLOAD_PAGE,
|
| 43 |
+
AllTitleReleaseManifest,
|
| 44 |
+
ApprovedReleasePoint,
|
| 45 |
+
ExclusionKind,
|
| 46 |
+
HardCodedLatestEditionError,
|
| 47 |
+
MissingApprovedReleaseError,
|
| 48 |
+
ProposedReleasePoint,
|
| 49 |
+
ReleasePointRole,
|
| 50 |
+
ResumeReceiptError,
|
| 51 |
+
SourceProvider,
|
| 52 |
+
TitleExclusion,
|
| 53 |
+
TitlePackageProvenance,
|
| 54 |
+
TitlePackageStatus,
|
| 55 |
+
TitleResumeReceipt,
|
| 56 |
+
UnapprovedMixedVintageError,
|
| 57 |
+
UnapprovedProposedReleaseError,
|
| 58 |
+
UscodeSourcePolicy,
|
| 59 |
+
UscodeSourcePolicyError,
|
| 60 |
+
VerificationResult,
|
| 61 |
+
canonical_json_dumps,
|
| 62 |
+
content_sha256,
|
| 63 |
+
digest_mapping,
|
| 64 |
+
expected_title_package_sha256,
|
| 65 |
+
normalize_title,
|
| 66 |
+
parse_release_point_id,
|
| 67 |
+
require_approved_exact,
|
| 68 |
+
require_canonical_title,
|
| 69 |
+
titles_missing_from_manifest,
|
| 70 |
+
ushouse_releasepoint_zip_url,
|
| 71 |
+
ushouse_title_code,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
SCHEMA_VERSION = "uscode-release-catalog-v1"
|
| 75 |
+
FIXTURE_SCHEMA_VERSION = "uscode-release-catalog-fixture-v1"
|
| 76 |
+
|
| 77 |
+
# Fixture identity defaults (aligned with USCIR-004 sealed release).
|
| 78 |
+
DEFAULT_FIXTURE_ID = "uscode-catalog-us-pl-118-45"
|
| 79 |
+
DEFAULT_CATALOG_APPROVED_BY = "uscir-005-fixture-seal"
|
| 80 |
+
|
| 81 |
+
PathLike = Union[str, Path]
|
| 82 |
+
JsonMapping = Mapping[str, Any]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ---------------------------------------------------------------------------
|
| 86 |
+
# Errors
|
| 87 |
+
# ---------------------------------------------------------------------------
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class UscodeReleaseCatalogError(ValueError):
|
| 91 |
+
"""Base error for all-title release catalog failures."""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class CatalogFixtureSchemaError(UscodeReleaseCatalogError):
|
| 95 |
+
"""Raised when the sealed catalog fixture recipe is malformed."""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class CatalogCompletenessError(UscodeReleaseCatalogError):
|
| 99 |
+
"""Raised when title completeness fails closed and enforcement is requested."""
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class CatalogCheckpointError(UscodeReleaseCatalogError):
|
| 103 |
+
"""Raised when a catalog checkpoint is malformed or non-atomic write fails."""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class CatalogAcquisitionError(UscodeReleaseCatalogError):
|
| 107 |
+
"""Raised when package acquisition cannot bind checksum and release point."""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ---------------------------------------------------------------------------
|
| 111 |
+
# Enums
|
| 112 |
+
# ---------------------------------------------------------------------------
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class PackageDisposition(str, Enum):
|
| 116 |
+
"""Per-title disposition after catalog acquisition or resume."""
|
| 117 |
+
|
| 118 |
+
ACCEPTED = "accepted"
|
| 119 |
+
EXCLUDED = "excluded"
|
| 120 |
+
MISSING = "missing"
|
| 121 |
+
SKIPPED_VERIFIED = "skipped_verified"
|
| 122 |
+
REDOWNLOAD = "redownload"
|
| 123 |
+
VERIFY_FAILED = "verify_failed"
|
| 124 |
+
FAILED = "failed"
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
def coerce(cls, value: Any) -> "PackageDisposition":
|
| 128 |
+
if isinstance(value, PackageDisposition):
|
| 129 |
+
return value
|
| 130 |
+
text = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
|
| 131 |
+
for item in cls:
|
| 132 |
+
if item.value == text or item.name.lower() == text:
|
| 133 |
+
return item
|
| 134 |
+
raise UscodeReleaseCatalogError(f"unknown package disposition: {value!r}")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class CatalogAcquisitionMode(str, Enum):
|
| 138 |
+
"""How packages were obtained."""
|
| 139 |
+
|
| 140 |
+
FIXTURE = "fixture"
|
| 141 |
+
RESUME = "resume"
|
| 142 |
+
POLICY = "policy"
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def coerce(cls, value: Any) -> "CatalogAcquisitionMode":
|
| 146 |
+
if isinstance(value, CatalogAcquisitionMode):
|
| 147 |
+
return value
|
| 148 |
+
text = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
|
| 149 |
+
for item in cls:
|
| 150 |
+
if item.value == text or item.name.lower() == text:
|
| 151 |
+
return item
|
| 152 |
+
raise UscodeReleaseCatalogError(f"unknown acquisition mode: {value!r}")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
# Records
|
| 157 |
+
# ---------------------------------------------------------------------------
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@dataclass(frozen=True, slots=True)
|
| 161 |
+
class TitlePackageSpec:
|
| 162 |
+
"""Expected package descriptor for one title under the approved release."""
|
| 163 |
+
|
| 164 |
+
title: str
|
| 165 |
+
release_point: str
|
| 166 |
+
package_id: str
|
| 167 |
+
source_url: str
|
| 168 |
+
expected_sha256: str
|
| 169 |
+
provider: SourceProvider = SourceProvider.OLRC_HOUSE
|
| 170 |
+
format_kind: str = "xml"
|
| 171 |
+
required: bool = True
|
| 172 |
+
exclusion: Optional[TitleExclusion] = None
|
| 173 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 174 |
+
|
| 175 |
+
def __post_init__(self) -> None:
|
| 176 |
+
object.__setattr__(self, "title", require_canonical_title(self.title))
|
| 177 |
+
rp = str(self.release_point)
|
| 178 |
+
if not rp.upper().startswith("USCODE-"):
|
| 179 |
+
rp, _, _ = parse_release_point_id(rp)
|
| 180 |
+
object.__setattr__(self, "release_point", rp)
|
| 181 |
+
object.__setattr__(self, "package_id", str(self.package_id).strip())
|
| 182 |
+
if not self.package_id:
|
| 183 |
+
raise UscodeReleaseCatalogError("package_id must be non-empty")
|
| 184 |
+
object.__setattr__(self, "source_url", str(self.source_url).strip())
|
| 185 |
+
if not self.source_url:
|
| 186 |
+
raise UscodeReleaseCatalogError("source_url must be non-empty")
|
| 187 |
+
sha = str(self.expected_sha256).strip().lower()
|
| 188 |
+
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
| 189 |
+
raise UscodeReleaseCatalogError(
|
| 190 |
+
f"expected_sha256 must be a lowercase 64-char hex SHA-256, got {self.expected_sha256!r}"
|
| 191 |
+
)
|
| 192 |
+
object.__setattr__(self, "expected_sha256", sha)
|
| 193 |
+
object.__setattr__(
|
| 194 |
+
self, "provider", SourceProvider.coerce(self.provider).canonical()
|
| 195 |
+
)
|
| 196 |
+
object.__setattr__(
|
| 197 |
+
self, "format_kind", str(self.format_kind or "xml").strip().lower()
|
| 198 |
+
)
|
| 199 |
+
if self.exclusion is not None and not isinstance(self.exclusion, TitleExclusion):
|
| 200 |
+
if isinstance(self.exclusion, Mapping):
|
| 201 |
+
object.__setattr__(self, "exclusion", TitleExclusion.from_dict(self.exclusion))
|
| 202 |
+
else:
|
| 203 |
+
raise UscodeReleaseCatalogError("exclusion must be a TitleExclusion or mapping")
|
| 204 |
+
if not isinstance(self.metadata, Mapping):
|
| 205 |
+
raise UscodeReleaseCatalogError("metadata must be a mapping")
|
| 206 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 207 |
+
|
| 208 |
+
def to_dict(self) -> dict[str, Any]:
|
| 209 |
+
return {
|
| 210 |
+
"exclusion": None if self.exclusion is None else self.exclusion.to_dict(),
|
| 211 |
+
"expected_sha256": self.expected_sha256,
|
| 212 |
+
"format_kind": self.format_kind,
|
| 213 |
+
"metadata": dict(sorted(self.metadata.items(), key=lambda kv: str(kv[0]))),
|
| 214 |
+
"package_id": self.package_id,
|
| 215 |
+
"provider": self.provider.value,
|
| 216 |
+
"release_point": self.release_point,
|
| 217 |
+
"required": bool(self.required),
|
| 218 |
+
"source_url": self.source_url,
|
| 219 |
+
"title": self.title,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
@classmethod
|
| 223 |
+
def from_dict(cls, value: JsonMapping) -> "TitlePackageSpec":
|
| 224 |
+
if not isinstance(value, Mapping):
|
| 225 |
+
raise UscodeReleaseCatalogError("title package spec must be a mapping")
|
| 226 |
+
return cls(
|
| 227 |
+
title=str(value.get("title")),
|
| 228 |
+
release_point=str(value.get("release_point")),
|
| 229 |
+
package_id=str(value.get("package_id") or value.get("release_point")),
|
| 230 |
+
source_url=str(value.get("source_url")),
|
| 231 |
+
expected_sha256=str(
|
| 232 |
+
value.get("expected_sha256")
|
| 233 |
+
or value.get("content_sha256")
|
| 234 |
+
or value.get("artifact_sha256")
|
| 235 |
+
),
|
| 236 |
+
provider=SourceProvider.coerce(value.get("provider") or DEFAULT_PROVIDER_OLRC),
|
| 237 |
+
format_kind=str(value.get("format_kind") or value.get("format") or "xml"),
|
| 238 |
+
required=bool(value.get("required", True)),
|
| 239 |
+
exclusion=value.get("exclusion"),
|
| 240 |
+
metadata=value.get("metadata") or {},
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@dataclass(frozen=True, slots=True)
|
| 245 |
+
class TitlePackageAcquisition:
|
| 246 |
+
"""Result of acquiring (or skipping) one title package.
|
| 247 |
+
|
| 248 |
+
Accepted packages always bind ``content_sha256`` and ``release_point``.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
title: str
|
| 252 |
+
disposition: PackageDisposition
|
| 253 |
+
release_point: Optional[str]
|
| 254 |
+
content_sha256: Optional[str]
|
| 255 |
+
package_id: Optional[str] = None
|
| 256 |
+
source_url: Optional[str] = None
|
| 257 |
+
status: TitlePackageStatus = TitlePackageStatus.PENDING
|
| 258 |
+
verification: VerificationResult = VerificationResult.UNVERIFIED
|
| 259 |
+
provenance: Optional[TitlePackageProvenance] = None
|
| 260 |
+
resume_receipt: Optional[TitleResumeReceipt] = None
|
| 261 |
+
exclusion: Optional[TitleExclusion] = None
|
| 262 |
+
redownloaded: bool = False
|
| 263 |
+
notes: Optional[str] = None
|
| 264 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 265 |
+
|
| 266 |
+
def __post_init__(self) -> None:
|
| 267 |
+
object.__setattr__(self, "title", require_canonical_title(self.title))
|
| 268 |
+
object.__setattr__(self, "disposition", PackageDisposition.coerce(self.disposition))
|
| 269 |
+
object.__setattr__(self, "status", TitlePackageStatus.coerce(self.status))
|
| 270 |
+
object.__setattr__(
|
| 271 |
+
self, "verification", VerificationResult.coerce(self.verification)
|
| 272 |
+
)
|
| 273 |
+
if self.release_point is not None:
|
| 274 |
+
rp = str(self.release_point)
|
| 275 |
+
if not rp.upper().startswith("USCODE-"):
|
| 276 |
+
rp, _, _ = parse_release_point_id(rp)
|
| 277 |
+
object.__setattr__(self, "release_point", rp)
|
| 278 |
+
if self.content_sha256 is not None:
|
| 279 |
+
sha = str(self.content_sha256).strip().lower()
|
| 280 |
+
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
| 281 |
+
raise CatalogAcquisitionError(
|
| 282 |
+
f"content_sha256 must be a lowercase 64-char hex SHA-256 for title {self.title}"
|
| 283 |
+
)
|
| 284 |
+
object.__setattr__(self, "content_sha256", sha)
|
| 285 |
+
if not isinstance(self.metadata, Mapping):
|
| 286 |
+
raise UscodeReleaseCatalogError("metadata must be a mapping")
|
| 287 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 288 |
+
|
| 289 |
+
# Accepted packages must bind checksum + release point.
|
| 290 |
+
if self.disposition is PackageDisposition.ACCEPTED:
|
| 291 |
+
if not self.release_point:
|
| 292 |
+
raise CatalogAcquisitionError(
|
| 293 |
+
f"accepted package for title {self.title} must bind release_point"
|
| 294 |
+
)
|
| 295 |
+
if not self.content_sha256:
|
| 296 |
+
raise CatalogAcquisitionError(
|
| 297 |
+
f"accepted package for title {self.title} must bind content_sha256"
|
| 298 |
+
)
|
| 299 |
+
if self.verification is not VerificationResult.VERIFIED:
|
| 300 |
+
raise CatalogAcquisitionError(
|
| 301 |
+
f"accepted package for title {self.title} requires verification=verified"
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
if self.disposition is PackageDisposition.EXCLUDED and self.exclusion is None:
|
| 305 |
+
raise CatalogAcquisitionError(
|
| 306 |
+
f"excluded package for title {self.title} requires an exclusion record"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def is_accepted(self) -> bool:
|
| 311 |
+
return self.disposition is PackageDisposition.ACCEPTED
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def is_complete_slot(self) -> bool:
|
| 315 |
+
"""True when this title is accounted for (accepted, excluded, or skipped)."""
|
| 316 |
+
|
| 317 |
+
return self.disposition in {
|
| 318 |
+
PackageDisposition.ACCEPTED,
|
| 319 |
+
PackageDisposition.EXCLUDED,
|
| 320 |
+
PackageDisposition.SKIPPED_VERIFIED,
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
def to_dict(self) -> dict[str, Any]:
|
| 324 |
+
return {
|
| 325 |
+
"content_sha256": self.content_sha256,
|
| 326 |
+
"disposition": self.disposition.value,
|
| 327 |
+
"exclusion": None if self.exclusion is None else self.exclusion.to_dict(),
|
| 328 |
+
"metadata": dict(sorted(self.metadata.items(), key=lambda kv: str(kv[0]))),
|
| 329 |
+
"notes": self.notes,
|
| 330 |
+
"package_id": self.package_id,
|
| 331 |
+
"provenance": None if self.provenance is None else self.provenance.to_dict(),
|
| 332 |
+
"redownloaded": bool(self.redownloaded),
|
| 333 |
+
"release_point": self.release_point,
|
| 334 |
+
"resume_receipt": (
|
| 335 |
+
None if self.resume_receipt is None else self.resume_receipt.to_dict()
|
| 336 |
+
),
|
| 337 |
+
"source_url": self.source_url,
|
| 338 |
+
"status": self.status.value,
|
| 339 |
+
"title": self.title,
|
| 340 |
+
"verification": self.verification.value,
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
@classmethod
|
| 344 |
+
def from_dict(cls, value: JsonMapping) -> "TitlePackageAcquisition":
|
| 345 |
+
if not isinstance(value, Mapping):
|
| 346 |
+
raise UscodeReleaseCatalogError("title package acquisition must be a mapping")
|
| 347 |
+
provenance_raw = value.get("provenance")
|
| 348 |
+
receipt_raw = value.get("resume_receipt")
|
| 349 |
+
exclusion_raw = value.get("exclusion")
|
| 350 |
+
return cls(
|
| 351 |
+
title=str(value.get("title")),
|
| 352 |
+
disposition=PackageDisposition.coerce(value.get("disposition")),
|
| 353 |
+
release_point=value.get("release_point"),
|
| 354 |
+
content_sha256=value.get("content_sha256"),
|
| 355 |
+
package_id=value.get("package_id"),
|
| 356 |
+
source_url=value.get("source_url"),
|
| 357 |
+
status=TitlePackageStatus.coerce(
|
| 358 |
+
value.get("status") or TitlePackageStatus.PENDING
|
| 359 |
+
),
|
| 360 |
+
verification=VerificationResult.coerce(
|
| 361 |
+
value.get("verification") or VerificationResult.UNVERIFIED
|
| 362 |
+
),
|
| 363 |
+
provenance=(
|
| 364 |
+
None
|
| 365 |
+
if provenance_raw is None
|
| 366 |
+
else TitlePackageProvenance.from_dict(provenance_raw)
|
| 367 |
+
),
|
| 368 |
+
resume_receipt=(
|
| 369 |
+
None
|
| 370 |
+
if receipt_raw is None
|
| 371 |
+
else TitleResumeReceipt.from_dict(receipt_raw)
|
| 372 |
+
),
|
| 373 |
+
exclusion=(
|
| 374 |
+
None
|
| 375 |
+
if exclusion_raw is None
|
| 376 |
+
else TitleExclusion.from_dict(exclusion_raw)
|
| 377 |
+
),
|
| 378 |
+
redownloaded=bool(value.get("redownloaded", False)),
|
| 379 |
+
notes=value.get("notes"),
|
| 380 |
+
metadata=value.get("metadata") or {},
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@dataclass(frozen=True, slots=True)
|
| 385 |
+
class TitleCompletenessReport:
|
| 386 |
+
"""Explicit title completeness for one catalog acquisition.
|
| 387 |
+
|
| 388 |
+
Completeness is complete only when every required title is either accepted
|
| 389 |
+
(or skipped-verified on resume) or explicitly excluded — never when titles
|
| 390 |
+
are silently absent.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
expected_titles: tuple[str, ...]
|
| 394 |
+
expected_count: int
|
| 395 |
+
present_titles: tuple[str, ...]
|
| 396 |
+
accepted_titles: tuple[str, ...]
|
| 397 |
+
excluded_titles: tuple[str, ...]
|
| 398 |
+
missing_titles: tuple[str, ...]
|
| 399 |
+
failed_titles: tuple[str, ...]
|
| 400 |
+
skipped_verified_titles: tuple[str, ...]
|
| 401 |
+
is_complete: bool
|
| 402 |
+
notes: Optional[str] = None
|
| 403 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 404 |
+
|
| 405 |
+
def __post_init__(self) -> None:
|
| 406 |
+
object.__setattr__(
|
| 407 |
+
self, "expected_titles", tuple(str(t) for t in self.expected_titles)
|
| 408 |
+
)
|
| 409 |
+
object.__setattr__(
|
| 410 |
+
self, "present_titles", tuple(str(t) for t in self.present_titles)
|
| 411 |
+
)
|
| 412 |
+
object.__setattr__(
|
| 413 |
+
self, "accepted_titles", tuple(str(t) for t in self.accepted_titles)
|
| 414 |
+
)
|
| 415 |
+
object.__setattr__(
|
| 416 |
+
self, "excluded_titles", tuple(str(t) for t in self.excluded_titles)
|
| 417 |
+
)
|
| 418 |
+
object.__setattr__(
|
| 419 |
+
self, "missing_titles", tuple(str(t) for t in self.missing_titles)
|
| 420 |
+
)
|
| 421 |
+
object.__setattr__(
|
| 422 |
+
self, "failed_titles", tuple(str(t) for t in self.failed_titles)
|
| 423 |
+
)
|
| 424 |
+
object.__setattr__(
|
| 425 |
+
self,
|
| 426 |
+
"skipped_verified_titles",
|
| 427 |
+
tuple(str(t) for t in self.skipped_verified_titles),
|
| 428 |
+
)
|
| 429 |
+
if not isinstance(self.expected_count, int) or self.expected_count < 0:
|
| 430 |
+
raise UscodeReleaseCatalogError("expected_count must be a non-negative int")
|
| 431 |
+
if not isinstance(self.metadata, Mapping):
|
| 432 |
+
raise UscodeReleaseCatalogError("metadata must be a mapping")
|
| 433 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 434 |
+
|
| 435 |
+
def to_dict(self) -> dict[str, Any]:
|
| 436 |
+
return {
|
| 437 |
+
"accepted_titles": list(self.accepted_titles),
|
| 438 |
+
"excluded_titles": list(self.excluded_titles),
|
| 439 |
+
"expected_count": self.expected_count,
|
| 440 |
+
"expected_titles": list(self.expected_titles),
|
| 441 |
+
"failed_titles": list(self.failed_titles),
|
| 442 |
+
"is_complete": bool(self.is_complete),
|
| 443 |
+
"metadata": dict(sorted(self.metadata.items(), key=lambda kv: str(kv[0]))),
|
| 444 |
+
"missing_titles": list(self.missing_titles),
|
| 445 |
+
"notes": self.notes,
|
| 446 |
+
"present_titles": list(self.present_titles),
|
| 447 |
+
"skipped_verified_titles": list(self.skipped_verified_titles),
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
@classmethod
|
| 451 |
+
def from_dict(cls, value: JsonMapping) -> "TitleCompletenessReport":
|
| 452 |
+
if not isinstance(value, Mapping):
|
| 453 |
+
raise UscodeReleaseCatalogError("completeness report must be a mapping")
|
| 454 |
+
return cls(
|
| 455 |
+
expected_titles=tuple(value.get("expected_titles") or ()),
|
| 456 |
+
expected_count=int(value.get("expected_count") or 0),
|
| 457 |
+
present_titles=tuple(value.get("present_titles") or ()),
|
| 458 |
+
accepted_titles=tuple(value.get("accepted_titles") or ()),
|
| 459 |
+
excluded_titles=tuple(value.get("excluded_titles") or ()),
|
| 460 |
+
missing_titles=tuple(value.get("missing_titles") or ()),
|
| 461 |
+
failed_titles=tuple(value.get("failed_titles") or ()),
|
| 462 |
+
skipped_verified_titles=tuple(value.get("skipped_verified_titles") or ()),
|
| 463 |
+
is_complete=bool(value.get("is_complete")),
|
| 464 |
+
notes=value.get("notes"),
|
| 465 |
+
metadata=value.get("metadata") or {},
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
@dataclass(frozen=True, slots=True)
|
| 470 |
+
class CatalogAcquisitionResult:
|
| 471 |
+
"""Sealed outcome of an all-title catalog acquisition or resume pass."""
|
| 472 |
+
|
| 473 |
+
approved_release: ApprovedReleasePoint
|
| 474 |
+
packages: Mapping[str, TitlePackageAcquisition]
|
| 475 |
+
completeness: TitleCompletenessReport
|
| 476 |
+
mode: CatalogAcquisitionMode
|
| 477 |
+
resume_receipts: Mapping[str, TitleResumeReceipt] = field(default_factory=dict)
|
| 478 |
+
proposed_release: Optional[ProposedReleasePoint] = None
|
| 479 |
+
expected_packages: Mapping[str, TitlePackageSpec] = field(default_factory=dict)
|
| 480 |
+
currentness_disclaimer: str = CURRENTNESS_DISCLAIMER
|
| 481 |
+
schema_version: str = SCHEMA_VERSION
|
| 482 |
+
fixture_id: Optional[str] = None
|
| 483 |
+
notes: Optional[str] = None
|
| 484 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 485 |
+
download_count: int = 0
|
| 486 |
+
skip_count: int = 0
|
| 487 |
+
|
| 488 |
+
def __post_init__(self) -> None:
|
| 489 |
+
if not isinstance(self.approved_release, ApprovedReleasePoint):
|
| 490 |
+
object.__setattr__(
|
| 491 |
+
self, "approved_release", require_approved_exact(self.approved_release)
|
| 492 |
+
)
|
| 493 |
+
object.__setattr__(self, "mode", CatalogAcquisitionMode.coerce(self.mode))
|
| 494 |
+
|
| 495 |
+
package_map: dict[str, TitlePackageAcquisition] = {}
|
| 496 |
+
for key, pkg in (self.packages or {}).items():
|
| 497 |
+
if isinstance(pkg, TitlePackageAcquisition):
|
| 498 |
+
record = pkg
|
| 499 |
+
elif isinstance(pkg, Mapping):
|
| 500 |
+
record = TitlePackageAcquisition.from_dict(pkg)
|
| 501 |
+
else:
|
| 502 |
+
raise UscodeReleaseCatalogError(
|
| 503 |
+
"packages values must be TitlePackageAcquisition or mapping"
|
| 504 |
+
)
|
| 505 |
+
package_map[record.title] = record
|
| 506 |
+
object.__setattr__(self, "packages", package_map)
|
| 507 |
+
|
| 508 |
+
receipt_map: dict[str, TitleResumeReceipt] = {}
|
| 509 |
+
for key, receipt in (self.resume_receipts or {}).items():
|
| 510 |
+
if isinstance(receipt, TitleResumeReceipt):
|
| 511 |
+
record = receipt
|
| 512 |
+
elif isinstance(receipt, Mapping):
|
| 513 |
+
record = TitleResumeReceipt.from_dict(receipt)
|
| 514 |
+
else:
|
| 515 |
+
raise ResumeReceiptError(
|
| 516 |
+
"resume_receipts values must be TitleResumeReceipt or mapping"
|
| 517 |
+
)
|
| 518 |
+
receipt_map[record.title] = record
|
| 519 |
+
object.__setattr__(self, "resume_receipts", receipt_map)
|
| 520 |
+
|
| 521 |
+
spec_map: dict[str, TitlePackageSpec] = {}
|
| 522 |
+
for key, spec in (self.expected_packages or {}).items():
|
| 523 |
+
if isinstance(spec, TitlePackageSpec):
|
| 524 |
+
record = spec
|
| 525 |
+
elif isinstance(spec, Mapping):
|
| 526 |
+
record = TitlePackageSpec.from_dict(spec)
|
| 527 |
+
else:
|
| 528 |
+
raise UscodeReleaseCatalogError(
|
| 529 |
+
"expected_packages values must be TitlePackageSpec or mapping"
|
| 530 |
+
)
|
| 531 |
+
spec_map[record.title] = record
|
| 532 |
+
object.__setattr__(self, "expected_packages", spec_map)
|
| 533 |
+
|
| 534 |
+
if not isinstance(self.completeness, TitleCompletenessReport):
|
| 535 |
+
if isinstance(self.completeness, Mapping):
|
| 536 |
+
object.__setattr__(
|
| 537 |
+
self, "completeness", TitleCompletenessReport.from_dict(self.completeness)
|
| 538 |
+
)
|
| 539 |
+
else:
|
| 540 |
+
raise UscodeReleaseCatalogError(
|
| 541 |
+
"completeness must be a TitleCompletenessReport or mapping"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
if self.proposed_release is not None and not isinstance(
|
| 545 |
+
self.proposed_release, ProposedReleasePoint
|
| 546 |
+
):
|
| 547 |
+
if isinstance(self.proposed_release, Mapping):
|
| 548 |
+
object.__setattr__(
|
| 549 |
+
self,
|
| 550 |
+
"proposed_release",
|
| 551 |
+
ProposedReleasePoint.from_dict(self.proposed_release),
|
| 552 |
+
)
|
| 553 |
+
else:
|
| 554 |
+
raise UscodeReleaseCatalogError(
|
| 555 |
+
"proposed_release must be a ProposedReleasePoint or mapping"
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
object.__setattr__(
|
| 559 |
+
self,
|
| 560 |
+
"currentness_disclaimer",
|
| 561 |
+
str(self.currentness_disclaimer or CURRENTNESS_DISCLAIMER),
|
| 562 |
+
)
|
| 563 |
+
object.__setattr__(self, "schema_version", str(self.schema_version or SCHEMA_VERSION))
|
| 564 |
+
if not isinstance(self.metadata, Mapping):
|
| 565 |
+
raise UscodeReleaseCatalogError("metadata must be a mapping")
|
| 566 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 567 |
+
if not isinstance(self.download_count, int) or self.download_count < 0:
|
| 568 |
+
raise UscodeReleaseCatalogError("download_count must be a non-negative int")
|
| 569 |
+
if not isinstance(self.skip_count, int) or self.skip_count < 0:
|
| 570 |
+
raise UscodeReleaseCatalogError("skip_count must be a non-negative int")
|
| 571 |
+
|
| 572 |
+
# Fail closed: every accepted / skipped-verified package binds checksum + release point.
|
| 573 |
+
for title, pkg in self.packages.items():
|
| 574 |
+
if pkg.disposition in {
|
| 575 |
+
PackageDisposition.ACCEPTED,
|
| 576 |
+
PackageDisposition.SKIPPED_VERIFIED,
|
| 577 |
+
}:
|
| 578 |
+
if not pkg.content_sha256 or not pkg.release_point:
|
| 579 |
+
raise CatalogAcquisitionError(
|
| 580 |
+
f"accepted package for title {title} missing checksum or release_point"
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
@property
|
| 584 |
+
def accepted_packages(self) -> Mapping[str, TitlePackageAcquisition]:
|
| 585 |
+
return {
|
| 586 |
+
t: p
|
| 587 |
+
for t, p in self.packages.items()
|
| 588 |
+
if p.disposition
|
| 589 |
+
in {PackageDisposition.ACCEPTED, PackageDisposition.SKIPPED_VERIFIED}
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
def result_digest(self) -> str:
|
| 593 |
+
return digest_mapping(self.to_dict())
|
| 594 |
+
|
| 595 |
+
def to_manifest(self) -> AllTitleReleaseManifest:
|
| 596 |
+
"""Project accepted/excluded packages into an all-title release manifest."""
|
| 597 |
+
|
| 598 |
+
titles: dict[str, TitlePackageProvenance] = {}
|
| 599 |
+
receipts: dict[str, TitleResumeReceipt] = {}
|
| 600 |
+
for title, pkg in self.packages.items():
|
| 601 |
+
if pkg.provenance is not None:
|
| 602 |
+
titles[title] = pkg.provenance
|
| 603 |
+
if pkg.resume_receipt is not None:
|
| 604 |
+
receipts[title] = pkg.resume_receipt
|
| 605 |
+
elif title in self.resume_receipts:
|
| 606 |
+
receipts[title] = self.resume_receipts[title]
|
| 607 |
+
return AllTitleReleaseManifest(
|
| 608 |
+
approved_release=self.approved_release,
|
| 609 |
+
titles=titles,
|
| 610 |
+
resume_receipts=receipts,
|
| 611 |
+
proposed_release=self.proposed_release,
|
| 612 |
+
currentness_disclaimer=self.currentness_disclaimer,
|
| 613 |
+
schema_version=self.schema_version
|
| 614 |
+
if self.schema_version.startswith("uscode-source-policy")
|
| 615 |
+
else "uscode-source-policy-v1",
|
| 616 |
+
notes=self.notes,
|
| 617 |
+
metadata={
|
| 618 |
+
"catalog_schema_version": SCHEMA_VERSION,
|
| 619 |
+
"fixture_id": self.fixture_id,
|
| 620 |
+
"mode": self.mode.value,
|
| 621 |
+
**dict(self.metadata),
|
| 622 |
+
},
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
def to_dict(self) -> dict[str, Any]:
|
| 626 |
+
return {
|
| 627 |
+
"approved_release": self.approved_release.to_dict(),
|
| 628 |
+
"completeness": self.completeness.to_dict(),
|
| 629 |
+
"currentness_disclaimer": self.currentness_disclaimer,
|
| 630 |
+
"download_count": self.download_count,
|
| 631 |
+
"expected_packages": {
|
| 632 |
+
k: v.to_dict()
|
| 633 |
+
for k, v in sorted(self.expected_packages.items(), key=lambda kv: kv[0])
|
| 634 |
+
},
|
| 635 |
+
"fixture_id": self.fixture_id,
|
| 636 |
+
"metadata": dict(sorted(self.metadata.items(), key=lambda kv: str(kv[0]))),
|
| 637 |
+
"mode": self.mode.value,
|
| 638 |
+
"notes": self.notes,
|
| 639 |
+
"packages": {
|
| 640 |
+
k: v.to_dict() for k, v in sorted(self.packages.items(), key=lambda kv: kv[0])
|
| 641 |
+
},
|
| 642 |
+
"proposed_release": (
|
| 643 |
+
None if self.proposed_release is None else self.proposed_release.to_dict()
|
| 644 |
+
),
|
| 645 |
+
"resume_receipts": {
|
| 646 |
+
k: v.to_dict()
|
| 647 |
+
for k, v in sorted(self.resume_receipts.items(), key=lambda kv: kv[0])
|
| 648 |
+
},
|
| 649 |
+
"schema_version": self.schema_version,
|
| 650 |
+
"skip_count": self.skip_count,
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
@classmethod
|
| 654 |
+
def from_dict(cls, value: JsonMapping) -> "CatalogAcquisitionResult":
|
| 655 |
+
if not isinstance(value, Mapping):
|
| 656 |
+
raise UscodeReleaseCatalogError("catalog acquisition result must be a mapping")
|
| 657 |
+
approved_raw = value.get("approved_release") or value.get("approved")
|
| 658 |
+
if approved_raw is None:
|
| 659 |
+
raise MissingApprovedReleaseError("approved_release is required")
|
| 660 |
+
return cls(
|
| 661 |
+
approved_release=require_approved_exact(approved_raw),
|
| 662 |
+
packages=value.get("packages") or {},
|
| 663 |
+
completeness=value.get("completeness") or {},
|
| 664 |
+
mode=CatalogAcquisitionMode.coerce(
|
| 665 |
+
value.get("mode") or CatalogAcquisitionMode.FIXTURE
|
| 666 |
+
),
|
| 667 |
+
resume_receipts=value.get("resume_receipts") or {},
|
| 668 |
+
proposed_release=value.get("proposed_release"),
|
| 669 |
+
expected_packages=value.get("expected_packages") or {},
|
| 670 |
+
currentness_disclaimer=str(
|
| 671 |
+
value.get("currentness_disclaimer") or CURRENTNESS_DISCLAIMER
|
| 672 |
+
),
|
| 673 |
+
schema_version=str(value.get("schema_version") or SCHEMA_VERSION),
|
| 674 |
+
fixture_id=value.get("fixture_id"),
|
| 675 |
+
notes=value.get("notes"),
|
| 676 |
+
metadata=value.get("metadata") or {},
|
| 677 |
+
download_count=int(value.get("download_count") or 0),
|
| 678 |
+
skip_count=int(value.get("skip_count") or 0),
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
# ---------------------------------------------------------------------------
|
| 683 |
+
# Completeness helpers
|
| 684 |
+
# ---------------------------------------------------------------------------
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def build_completeness_report(
|
| 688 |
+
packages: Mapping[str, TitlePackageAcquisition] | Iterable[TitlePackageAcquisition],
|
| 689 |
+
*,
|
| 690 |
+
expected_titles: Sequence[str] = CANONICAL_USCODE_TITLES,
|
| 691 |
+
notes: Optional[str] = None,
|
| 692 |
+
metadata: Optional[Mapping[str, Any]] = None,
|
| 693 |
+
) -> TitleCompletenessReport:
|
| 694 |
+
"""Build an explicit title completeness report from package dispositions."""
|
| 695 |
+
|
| 696 |
+
expected = tuple(require_canonical_title(t) for t in expected_titles)
|
| 697 |
+
expected_set = set(expected)
|
| 698 |
+
|
| 699 |
+
if isinstance(packages, Mapping):
|
| 700 |
+
pkg_iter: Iterable[TitlePackageAcquisition] = packages.values()
|
| 701 |
+
else:
|
| 702 |
+
pkg_iter = packages
|
| 703 |
+
|
| 704 |
+
by_title: dict[str, TitlePackageAcquisition] = {}
|
| 705 |
+
for pkg in pkg_iter:
|
| 706 |
+
if not isinstance(pkg, TitlePackageAcquisition):
|
| 707 |
+
raise UscodeReleaseCatalogError(
|
| 708 |
+
"packages must be TitlePackageAcquisition records"
|
| 709 |
+
)
|
| 710 |
+
by_title[pkg.title] = pkg
|
| 711 |
+
|
| 712 |
+
accepted: list[str] = []
|
| 713 |
+
excluded: list[str] = []
|
| 714 |
+
missing: list[str] = []
|
| 715 |
+
failed: list[str] = []
|
| 716 |
+
skipped: list[str] = []
|
| 717 |
+
present: list[str] = []
|
| 718 |
+
|
| 719 |
+
for title in expected:
|
| 720 |
+
pkg = by_title.get(title)
|
| 721 |
+
if pkg is None:
|
| 722 |
+
missing.append(title)
|
| 723 |
+
continue
|
| 724 |
+
present.append(title)
|
| 725 |
+
if pkg.disposition is PackageDisposition.ACCEPTED:
|
| 726 |
+
accepted.append(title)
|
| 727 |
+
elif pkg.disposition is PackageDisposition.EXCLUDED:
|
| 728 |
+
excluded.append(title)
|
| 729 |
+
elif pkg.disposition is PackageDisposition.SKIPPED_VERIFIED:
|
| 730 |
+
skipped.append(title)
|
| 731 |
+
accepted.append(title) # accounted as present/verified
|
| 732 |
+
elif pkg.disposition is PackageDisposition.MISSING:
|
| 733 |
+
missing.append(title)
|
| 734 |
+
if title in present:
|
| 735 |
+
# Keep in present if explicitly reported as missing disposition
|
| 736 |
+
# after being listed — treat as not present for completeness.
|
| 737 |
+
present.remove(title)
|
| 738 |
+
elif pkg.disposition in {
|
| 739 |
+
PackageDisposition.FAILED,
|
| 740 |
+
PackageDisposition.VERIFY_FAILED,
|
| 741 |
+
PackageDisposition.REDOWNLOAD,
|
| 742 |
+
}:
|
| 743 |
+
failed.append(title)
|
| 744 |
+
else:
|
| 745 |
+
failed.append(title)
|
| 746 |
+
|
| 747 |
+
# Titles outside expected set are ignored for completeness, but recorded.
|
| 748 |
+
extra = sorted(t for t in by_title if t not in expected_set)
|
| 749 |
+
|
| 750 |
+
is_complete = (
|
| 751 |
+
len(missing) == 0
|
| 752 |
+
and len(failed) == 0
|
| 753 |
+
and (len(accepted) + len(excluded)) == len(expected)
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
return TitleCompletenessReport(
|
| 757 |
+
expected_titles=expected,
|
| 758 |
+
expected_count=len(expected),
|
| 759 |
+
present_titles=tuple(present),
|
| 760 |
+
accepted_titles=tuple(accepted),
|
| 761 |
+
excluded_titles=tuple(excluded),
|
| 762 |
+
missing_titles=tuple(missing),
|
| 763 |
+
failed_titles=tuple(failed),
|
| 764 |
+
skipped_verified_titles=tuple(skipped),
|
| 765 |
+
is_complete=is_complete,
|
| 766 |
+
notes=notes,
|
| 767 |
+
metadata={
|
| 768 |
+
**dict(metadata or {}),
|
| 769 |
+
"extra_titles": extra,
|
| 770 |
+
"accounted_count": len(accepted) + len(excluded),
|
| 771 |
+
},
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
# ---------------------------------------------------------------------------
|
| 776 |
+
# Fixture recipe / IO
|
| 777 |
+
# ---------------------------------------------------------------------------
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
def default_catalog_fixture_path() -> Path:
|
| 781 |
+
"""Return the sealed all-title release-catalog fixture path."""
|
| 782 |
+
|
| 783 |
+
here = Path(__file__).resolve()
|
| 784 |
+
# processors/legal_scrapers/federal_scrapers/thisfile → repo root is parents[4]
|
| 785 |
+
candidates = [
|
| 786 |
+
here.parents[4] / "tests" / "fixtures" / "legal_ir" / "uscode_release_catalog.json",
|
| 787 |
+
Path.cwd() / "tests" / "fixtures" / "legal_ir" / "uscode_release_catalog.json",
|
| 788 |
+
]
|
| 789 |
+
for path in candidates:
|
| 790 |
+
if path.is_file():
|
| 791 |
+
return path
|
| 792 |
+
return candidates[0]
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def build_default_catalog_fixture_payload(
|
| 796 |
+
*,
|
| 797 |
+
release_point: str = DEFAULT_APPROVED_RELEASE_POINT,
|
| 798 |
+
congress: str = DEFAULT_APPROVED_CONGRESS,
|
| 799 |
+
release: str = DEFAULT_APPROVED_RELEASE,
|
| 800 |
+
approved_by: str = DEFAULT_CATALOG_APPROVED_BY,
|
| 801 |
+
approved_at: str = DEFAULT_APPROVED_AT,
|
| 802 |
+
discovered_at: str = DEFAULT_DISCOVERED_AT,
|
| 803 |
+
acquired_at: str = DEFAULT_ACQUIRED_AT,
|
| 804 |
+
excluded_titles: Optional[Mapping[str, Mapping[str, Any]]] = None,
|
| 805 |
+
missing_titles: Optional[Sequence[str]] = None,
|
| 806 |
+
) -> dict[str, Any]:
|
| 807 |
+
"""Build a compact recipe for the sealed all-title catalog fixture.
|
| 808 |
+
|
| 809 |
+
Stores generators and shared release identity rather than 53 fully expanded
|
| 810 |
+
package envelopes, keeping the fixture under admission budgets.
|
| 811 |
+
"""
|
| 812 |
+
|
| 813 |
+
canonical, congress_s, release_s = parse_release_point_id(
|
| 814 |
+
release_point if release_point else f"{congress}/{release}"
|
| 815 |
+
)
|
| 816 |
+
# Recipe-level exclusions (title → exclusion mapping). Default happy-path
|
| 817 |
+
# fixture admits all 53 packages; callers/tests inject exclusions when
|
| 818 |
+
# exercising the excluded disposition path.
|
| 819 |
+
excluded: dict[str, dict[str, Any]] = {}
|
| 820 |
+
for title, excl in (excluded_titles or {}).items():
|
| 821 |
+
title_n = require_canonical_title(title)
|
| 822 |
+
payload = dict(excl)
|
| 823 |
+
payload.setdefault("title", title_n)
|
| 824 |
+
excluded[title_n] = payload
|
| 825 |
+
|
| 826 |
+
missing = [require_canonical_title(t) for t in (missing_titles or ())]
|
| 827 |
+
|
| 828 |
+
return {
|
| 829 |
+
"schema_version": FIXTURE_SCHEMA_VERSION,
|
| 830 |
+
"catalog_schema_version": SCHEMA_VERSION,
|
| 831 |
+
"fixture_id": DEFAULT_FIXTURE_ID
|
| 832 |
+
if canonical == DEFAULT_APPROVED_RELEASE_POINT
|
| 833 |
+
else f"uscode-catalog-{canonical.replace('/', '-')}",
|
| 834 |
+
"expected_title_count": EXPECTED_TITLE_COUNT,
|
| 835 |
+
"canonical_titles": list(CANONICAL_USCODE_TITLES),
|
| 836 |
+
"currentness_disclaimer": CURRENTNESS_DISCLAIMER,
|
| 837 |
+
"notes": (
|
| 838 |
+
"Compact all-title release catalog recipe (USCIR-005). "
|
| 839 |
+
"Resolves one approved exact release, enumerates all expected title "
|
| 840 |
+
"packages, binds checksum + release point per package, and supports "
|
| 841 |
+
"deterministic resume. Expand via expand_catalog_fixture()."
|
| 842 |
+
),
|
| 843 |
+
"proposed_release": {
|
| 844 |
+
"role": ReleasePointRole.PROPOSED_LATEST.value,
|
| 845 |
+
"release_point": canonical,
|
| 846 |
+
"provider": DEFAULT_PROVIDER_OLRC,
|
| 847 |
+
"congress": congress_s,
|
| 848 |
+
"release": release_s,
|
| 849 |
+
"discovered_at": discovered_at,
|
| 850 |
+
"discovery_source": USHOUSE_DOWNLOAD_PAGE,
|
| 851 |
+
"edition": f"olrc-proposed-{canonical.replace('/', '-')}",
|
| 852 |
+
"notes": (
|
| 853 |
+
"Catalog scrape candidate from the House OLRC download page; "
|
| 854 |
+
"not final provenance."
|
| 855 |
+
),
|
| 856 |
+
},
|
| 857 |
+
"approved_release": {
|
| 858 |
+
"role": ReleasePointRole.APPROVED_EXACT.value,
|
| 859 |
+
"release_point": canonical,
|
| 860 |
+
"provider": DEFAULT_PROVIDER_OLRC,
|
| 861 |
+
"congress": congress_s,
|
| 862 |
+
"release": release_s,
|
| 863 |
+
"approved_by": approved_by,
|
| 864 |
+
"approved_at": approved_at,
|
| 865 |
+
"edition": f"olrc-{canonical.replace('/', '-')}",
|
| 866 |
+
"notes": "Human-sealed exact release point for all-title catalog admission.",
|
| 867 |
+
},
|
| 868 |
+
"approved_mixed_overrides": {},
|
| 869 |
+
"generators": {
|
| 870 |
+
"title_package": {
|
| 871 |
+
"provider": DEFAULT_PROVIDER_OLRC,
|
| 872 |
+
"format_kind": "xml",
|
| 873 |
+
"status": TitlePackageStatus.VERIFIED.value,
|
| 874 |
+
"verification": VerificationResult.VERIFIED.value,
|
| 875 |
+
"acquired_at": acquired_at,
|
| 876 |
+
"media_type": "application/zip",
|
| 877 |
+
"checksum_seed_template": "{provider}|{release_point}|title-{title}|package",
|
| 878 |
+
"source_url_template": (
|
| 879 |
+
"https://uscode.house.gov/download/releasepoints/us/pl/"
|
| 880 |
+
"{congress}/{release}/xml_usc{title_code}@{congress}-{release}.zip"
|
| 881 |
+
),
|
| 882 |
+
},
|
| 883 |
+
"resume_receipt": {
|
| 884 |
+
"checkpoint_seq_start": 1,
|
| 885 |
+
},
|
| 886 |
+
},
|
| 887 |
+
"excluded_packages": excluded,
|
| 888 |
+
"missing_titles": missing,
|
| 889 |
+
"seed_overrides": {},
|
| 890 |
+
"sample_exclusions": [
|
| 891 |
+
{
|
| 892 |
+
"kind": ExclusionKind.CLASSIFICATION_GAP.value,
|
| 893 |
+
"title": "35",
|
| 894 |
+
"citation": "Pub. L. 117-328 div. W",
|
| 895 |
+
"public_law": "Pub. L. 117-328",
|
| 896 |
+
"reason": (
|
| 897 |
+
"Classification table records a pending editorial "
|
| 898 |
+
"reclassification affecting cross-references in Title 35; "
|
| 899 |
+
"package itself remains admitted."
|
| 900 |
+
),
|
| 901 |
+
}
|
| 902 |
+
],
|
| 903 |
+
}
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def expand_catalog_fixture(payload: JsonMapping) -> dict[str, Any]:
|
| 907 |
+
"""Expand a compact catalog recipe into structured catalog state.
|
| 908 |
+
|
| 909 |
+
Returns a mapping with keys:
|
| 910 |
+
``approved_release``, ``proposed_release``, ``expected_packages``,
|
| 911 |
+
``packages`` (fixture acquisitions), ``resume_receipts``,
|
| 912 |
+
``excluded_packages``, ``missing_titles``, ``fixture_id``, etc.
|
| 913 |
+
"""
|
| 914 |
+
|
| 915 |
+
if not isinstance(payload, Mapping):
|
| 916 |
+
raise CatalogFixtureSchemaError("fixture root must be a mapping")
|
| 917 |
+
schema = payload.get("schema_version")
|
| 918 |
+
if schema != FIXTURE_SCHEMA_VERSION:
|
| 919 |
+
raise CatalogFixtureSchemaError(
|
| 920 |
+
f"unsupported fixture schema_version {schema!r}; "
|
| 921 |
+
f"expected {FIXTURE_SCHEMA_VERSION!r}"
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
expected = int(payload.get("expected_title_count") or EXPECTED_TITLE_COUNT)
|
| 925 |
+
titles_list = payload.get("canonical_titles") or list(CANONICAL_USCODE_TITLES)
|
| 926 |
+
if len(titles_list) != expected:
|
| 927 |
+
raise CatalogFixtureSchemaError(
|
| 928 |
+
f"canonical_titles length {len(titles_list)} != expected_title_count {expected}"
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
proposed_raw = payload.get("proposed_release")
|
| 932 |
+
proposed = (
|
| 933 |
+
None if proposed_raw is None else ProposedReleasePoint.from_dict(proposed_raw)
|
| 934 |
+
)
|
| 935 |
+
approved = require_approved_exact(
|
| 936 |
+
payload.get("approved_release") or payload.get("approved")
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
gen = payload.get("generators") or {}
|
| 940 |
+
pkg_gen = gen.get("title_package") or gen.get("title_provenance") or {}
|
| 941 |
+
receipt_gen = gen.get("resume_receipt") or {}
|
| 942 |
+
seq_start = int(receipt_gen.get("checkpoint_seq_start", 1))
|
| 943 |
+
|
| 944 |
+
provider = SourceProvider.coerce(
|
| 945 |
+
pkg_gen.get("provider") or approved.provider
|
| 946 |
+
).canonical()
|
| 947 |
+
format_kind = str(pkg_gen.get("format_kind") or "xml")
|
| 948 |
+
acquired_at = pkg_gen.get("acquired_at") or DEFAULT_ACQUIRED_AT
|
| 949 |
+
status = TitlePackageStatus.coerce(
|
| 950 |
+
pkg_gen.get("status") or TitlePackageStatus.VERIFIED
|
| 951 |
+
)
|
| 952 |
+
verification = VerificationResult.coerce(
|
| 953 |
+
pkg_gen.get("verification") or VerificationResult.VERIFIED
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
seed_overrides = payload.get("seed_overrides") or {}
|
| 957 |
+
excluded_packages_raw = payload.get("excluded_packages") or {}
|
| 958 |
+
missing_titles = {
|
| 959 |
+
require_canonical_title(t) for t in (payload.get("missing_titles") or ())
|
| 960 |
+
}
|
| 961 |
+
inline_packages = payload.get("packages") or {}
|
| 962 |
+
inline_receipts = payload.get("resume_receipts") or {}
|
| 963 |
+
inline_specs = payload.get("expected_packages") or {}
|
| 964 |
+
|
| 965 |
+
congress = approved.congress or DEFAULT_APPROVED_CONGRESS
|
| 966 |
+
release = approved.release or DEFAULT_APPROVED_RELEASE
|
| 967 |
+
|
| 968 |
+
expected_packages: dict[str, TitlePackageSpec] = {}
|
| 969 |
+
packages: dict[str, TitlePackageAcquisition] = {}
|
| 970 |
+
receipts: dict[str, TitleResumeReceipt] = {}
|
| 971 |
+
excluded_map: dict[str, TitleExclusion] = {}
|
| 972 |
+
|
| 973 |
+
for index, title in enumerate(titles_list):
|
| 974 |
+
title_n = require_canonical_title(title)
|
| 975 |
+
override = seed_overrides.get(title_n) or {}
|
| 976 |
+
rp = str(override.get("release_point") or approved.release_point)
|
| 977 |
+
if not rp.upper().startswith("USCODE-"):
|
| 978 |
+
rp, _, _ = parse_release_point_id(rp)
|
| 979 |
+
|
| 980 |
+
checksum = str(
|
| 981 |
+
override.get("content_sha256")
|
| 982 |
+
or override.get("expected_sha256")
|
| 983 |
+
or expected_title_package_sha256(
|
| 984 |
+
release_point=rp, title=title_n, provider=provider
|
| 985 |
+
)
|
| 986 |
+
)
|
| 987 |
+
package_id = str(override.get("package_id") or rp)
|
| 988 |
+
source_url = str(
|
| 989 |
+
override.get("source_url")
|
| 990 |
+
or ushouse_releasepoint_zip_url(
|
| 991 |
+
congress=congress,
|
| 992 |
+
release=release,
|
| 993 |
+
title=title_n,
|
| 994 |
+
format_kind=format_kind,
|
| 995 |
+
)
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
excl_raw = excluded_packages_raw.get(title_n) or override.get("exclusion")
|
| 999 |
+
exclusion: Optional[TitleExclusion] = None
|
| 1000 |
+
if excl_raw is not None:
|
| 1001 |
+
if isinstance(excl_raw, TitleExclusion):
|
| 1002 |
+
exclusion = excl_raw
|
| 1003 |
+
elif isinstance(excl_raw, Mapping):
|
| 1004 |
+
excl_payload = dict(excl_raw)
|
| 1005 |
+
excl_payload.setdefault("title", title_n)
|
| 1006 |
+
exclusion = TitleExclusion.from_dict(excl_payload)
|
| 1007 |
+
else:
|
| 1008 |
+
raise CatalogFixtureSchemaError(
|
| 1009 |
+
f"excluded_packages[{title_n!r}] must be a mapping"
|
| 1010 |
+
)
|
| 1011 |
+
excluded_map[title_n] = exclusion
|
| 1012 |
+
|
| 1013 |
+
if title_n in inline_specs:
|
| 1014 |
+
spec = TitlePackageSpec.from_dict(inline_specs[title_n])
|
| 1015 |
+
else:
|
| 1016 |
+
spec = TitlePackageSpec(
|
| 1017 |
+
title=title_n,
|
| 1018 |
+
release_point=rp,
|
| 1019 |
+
package_id=package_id,
|
| 1020 |
+
source_url=source_url,
|
| 1021 |
+
expected_sha256=checksum,
|
| 1022 |
+
provider=provider,
|
| 1023 |
+
format_kind=str(override.get("format_kind") or format_kind),
|
| 1024 |
+
required=title_n not in missing_titles,
|
| 1025 |
+
exclusion=exclusion,
|
| 1026 |
+
metadata=override.get("metadata") or {},
|
| 1027 |
+
)
|
| 1028 |
+
expected_packages[title_n] = spec
|
| 1029 |
+
|
| 1030 |
+
if title_n in missing_titles:
|
| 1031 |
+
packages[title_n] = TitlePackageAcquisition(
|
| 1032 |
+
title=title_n,
|
| 1033 |
+
disposition=PackageDisposition.MISSING,
|
| 1034 |
+
release_point=None,
|
| 1035 |
+
content_sha256=None,
|
| 1036 |
+
package_id=None,
|
| 1037 |
+
source_url=source_url,
|
| 1038 |
+
status=TitlePackageStatus.FAILED,
|
| 1039 |
+
verification=VerificationResult.MISSING,
|
| 1040 |
+
notes=f"title {title_n} package missing from catalog fixture",
|
| 1041 |
+
metadata={"fixture_missing": True},
|
| 1042 |
+
)
|
| 1043 |
+
continue
|
| 1044 |
+
|
| 1045 |
+
if title_n in inline_packages:
|
| 1046 |
+
pkg = TitlePackageAcquisition.from_dict(inline_packages[title_n])
|
| 1047 |
+
packages[title_n] = pkg
|
| 1048 |
+
if pkg.resume_receipt is not None:
|
| 1049 |
+
receipts[title_n] = pkg.resume_receipt
|
| 1050 |
+
continue
|
| 1051 |
+
|
| 1052 |
+
if exclusion is not None:
|
| 1053 |
+
prov = TitlePackageProvenance(
|
| 1054 |
+
title=title_n,
|
| 1055 |
+
release_point=rp,
|
| 1056 |
+
provider=provider,
|
| 1057 |
+
package_id=package_id,
|
| 1058 |
+
source_url=source_url,
|
| 1059 |
+
content_sha256=checksum,
|
| 1060 |
+
acquired_at=override.get("acquired_at") or acquired_at,
|
| 1061 |
+
verification=VerificationResult.MISSING,
|
| 1062 |
+
status=TitlePackageStatus.EXCLUDED,
|
| 1063 |
+
format_kind=format_kind,
|
| 1064 |
+
exclusion=exclusion,
|
| 1065 |
+
notes=exclusion.reason,
|
| 1066 |
+
metadata=override.get("metadata") or {},
|
| 1067 |
+
)
|
| 1068 |
+
receipt = TitleResumeReceipt(
|
| 1069 |
+
title=title_n,
|
| 1070 |
+
release_point=rp,
|
| 1071 |
+
package_id=package_id,
|
| 1072 |
+
content_sha256=checksum,
|
| 1073 |
+
status=TitlePackageStatus.EXCLUDED,
|
| 1074 |
+
verification=VerificationResult.MISSING,
|
| 1075 |
+
source_url=source_url,
|
| 1076 |
+
acquired_at=prov.acquired_at,
|
| 1077 |
+
checkpoint_seq=seq_start + index,
|
| 1078 |
+
provider=provider,
|
| 1079 |
+
notes=exclusion.reason,
|
| 1080 |
+
metadata={"schema_version": SCHEMA_VERSION, "format_kind": format_kind},
|
| 1081 |
+
)
|
| 1082 |
+
packages[title_n] = TitlePackageAcquisition(
|
| 1083 |
+
title=title_n,
|
| 1084 |
+
disposition=PackageDisposition.EXCLUDED,
|
| 1085 |
+
release_point=rp,
|
| 1086 |
+
content_sha256=checksum,
|
| 1087 |
+
package_id=package_id,
|
| 1088 |
+
source_url=source_url,
|
| 1089 |
+
status=TitlePackageStatus.EXCLUDED,
|
| 1090 |
+
verification=VerificationResult.MISSING,
|
| 1091 |
+
provenance=prov,
|
| 1092 |
+
resume_receipt=receipt,
|
| 1093 |
+
exclusion=exclusion,
|
| 1094 |
+
redownloaded=False,
|
| 1095 |
+
notes=exclusion.reason,
|
| 1096 |
+
)
|
| 1097 |
+
receipts[title_n] = receipt
|
| 1098 |
+
continue
|
| 1099 |
+
|
| 1100 |
+
# Default admitted package: verified with bound checksum + release point.
|
| 1101 |
+
pkg_status = TitlePackageStatus.coerce(override.get("status") or status)
|
| 1102 |
+
pkg_verification = VerificationResult.coerce(
|
| 1103 |
+
override.get("verification") or verification
|
| 1104 |
+
)
|
| 1105 |
+
prov = TitlePackageProvenance(
|
| 1106 |
+
title=title_n,
|
| 1107 |
+
release_point=rp,
|
| 1108 |
+
provider=provider,
|
| 1109 |
+
package_id=package_id,
|
| 1110 |
+
source_url=source_url,
|
| 1111 |
+
content_sha256=checksum,
|
| 1112 |
+
acquired_at=override.get("acquired_at") or acquired_at,
|
| 1113 |
+
verification=pkg_verification,
|
| 1114 |
+
status=pkg_status,
|
| 1115 |
+
media_type=str(override.get("media_type") or "application/zip"),
|
| 1116 |
+
byte_size=override.get("byte_size"),
|
| 1117 |
+
format_kind=str(override.get("format_kind") or format_kind),
|
| 1118 |
+
notes=override.get("notes"),
|
| 1119 |
+
metadata=override.get("metadata") or {},
|
| 1120 |
+
)
|
| 1121 |
+
if title_n in inline_receipts:
|
| 1122 |
+
receipt = TitleResumeReceipt.from_dict(inline_receipts[title_n])
|
| 1123 |
+
else:
|
| 1124 |
+
receipt = TitleResumeReceipt(
|
| 1125 |
+
title=title_n,
|
| 1126 |
+
release_point=rp,
|
| 1127 |
+
package_id=package_id,
|
| 1128 |
+
content_sha256=checksum,
|
| 1129 |
+
status=pkg_status,
|
| 1130 |
+
verification=pkg_verification,
|
| 1131 |
+
source_url=source_url,
|
| 1132 |
+
acquired_at=prov.acquired_at,
|
| 1133 |
+
checkpoint_seq=seq_start + index,
|
| 1134 |
+
provider=provider,
|
| 1135 |
+
notes=prov.notes,
|
| 1136 |
+
metadata={"schema_version": SCHEMA_VERSION, "format_kind": prov.format_kind},
|
| 1137 |
+
)
|
| 1138 |
+
packages[title_n] = TitlePackageAcquisition(
|
| 1139 |
+
title=title_n,
|
| 1140 |
+
disposition=PackageDisposition.ACCEPTED,
|
| 1141 |
+
release_point=rp,
|
| 1142 |
+
content_sha256=checksum,
|
| 1143 |
+
package_id=package_id,
|
| 1144 |
+
source_url=source_url,
|
| 1145 |
+
status=pkg_status,
|
| 1146 |
+
verification=pkg_verification,
|
| 1147 |
+
provenance=prov,
|
| 1148 |
+
resume_receipt=receipt,
|
| 1149 |
+
redownloaded=True, # first acquisition counts as a download
|
| 1150 |
+
notes=prov.notes,
|
| 1151 |
+
metadata={"fixture_id": payload.get("fixture_id"), "acquired_from": "fixture"},
|
| 1152 |
+
)
|
| 1153 |
+
receipts[title_n] = receipt
|
| 1154 |
+
|
| 1155 |
+
return {
|
| 1156 |
+
"approved_release": approved,
|
| 1157 |
+
"proposed_release": proposed,
|
| 1158 |
+
"expected_packages": expected_packages,
|
| 1159 |
+
"packages": packages,
|
| 1160 |
+
"resume_receipts": receipts,
|
| 1161 |
+
"excluded_packages": excluded_map,
|
| 1162 |
+
"missing_titles": tuple(sorted(missing_titles)),
|
| 1163 |
+
"canonical_titles": tuple(require_canonical_title(t) for t in titles_list),
|
| 1164 |
+
"expected_title_count": expected,
|
| 1165 |
+
"fixture_id": payload.get("fixture_id"),
|
| 1166 |
+
"currentness_disclaimer": str(
|
| 1167 |
+
payload.get("currentness_disclaimer") or CURRENTNESS_DISCLAIMER
|
| 1168 |
+
),
|
| 1169 |
+
"notes": payload.get("notes"),
|
| 1170 |
+
"sample_exclusions": payload.get("sample_exclusions") or [],
|
| 1171 |
+
"approved_mixed_overrides": payload.get("approved_mixed_overrides") or {},
|
| 1172 |
+
"schema_version": SCHEMA_VERSION,
|
| 1173 |
+
"fixture_schema_version": FIXTURE_SCHEMA_VERSION,
|
| 1174 |
+
"metadata": {
|
| 1175 |
+
"fixture_id": payload.get("fixture_id"),
|
| 1176 |
+
"sample_exclusions": payload.get("sample_exclusions") or [],
|
| 1177 |
+
},
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
|
| 1181 |
+
def load_catalog_fixture_payload(path: PathLike | None = None) -> dict[str, Any]:
|
| 1182 |
+
"""Load the sealed compact catalog fixture recipe from disk."""
|
| 1183 |
+
|
| 1184 |
+
p = Path(path) if path is not None else default_catalog_fixture_path()
|
| 1185 |
+
with p.open("r", encoding="utf-8") as handle:
|
| 1186 |
+
payload = json.load(handle)
|
| 1187 |
+
if not isinstance(payload, Mapping):
|
| 1188 |
+
raise CatalogFixtureSchemaError(f"fixture root must be a mapping: {p}")
|
| 1189 |
+
return dict(payload)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
def load_catalog_fixture(path: PathLike | None = None) -> dict[str, Any]:
|
| 1193 |
+
"""Load and expand the sealed all-title release-catalog fixture."""
|
| 1194 |
+
|
| 1195 |
+
return expand_catalog_fixture(load_catalog_fixture_payload(path))
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
def write_default_catalog_fixture(path: PathLike | None = None) -> Path:
|
| 1199 |
+
"""Materialize the compact default catalog fixture recipe."""
|
| 1200 |
+
|
| 1201 |
+
p = Path(path) if path is not None else default_catalog_fixture_path()
|
| 1202 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 1203 |
+
payload = build_default_catalog_fixture_payload()
|
| 1204 |
+
p.write_text(
|
| 1205 |
+
json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
| 1206 |
+
encoding="utf-8",
|
| 1207 |
+
)
|
| 1208 |
+
return p
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
# ---------------------------------------------------------------------------
|
| 1212 |
+
# Checkpoint helpers
|
| 1213 |
+
# ---------------------------------------------------------------------------
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
|
| 1217 |
+
"""Write JSON atomically (temp file + os.replace)."""
|
| 1218 |
+
|
| 1219 |
+
path = Path(path)
|
| 1220 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 1221 |
+
text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
| 1222 |
+
fd, tmp_name = tempfile.mkstemp(
|
| 1223 |
+
prefix=f".{path.name}.",
|
| 1224 |
+
suffix=".tmp",
|
| 1225 |
+
dir=str(path.parent),
|
| 1226 |
+
)
|
| 1227 |
+
try:
|
| 1228 |
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
| 1229 |
+
handle.write(text)
|
| 1230 |
+
handle.flush()
|
| 1231 |
+
os.fsync(handle.fileno())
|
| 1232 |
+
os.replace(tmp_name, path)
|
| 1233 |
+
except Exception:
|
| 1234 |
+
try:
|
| 1235 |
+
os.unlink(tmp_name)
|
| 1236 |
+
except OSError:
|
| 1237 |
+
pass
|
| 1238 |
+
raise
|
| 1239 |
+
|
| 1240 |
+
|
| 1241 |
+
def default_checkpoint_directory() -> Path:
|
| 1242 |
+
"""Return the preferred catalog checkpoint directory.
|
| 1243 |
+
|
| 1244 |
+
Prefers ``$IPFS_ACCELERATE_AGENT_TASK_CHECKPOINT_DIR`` when set, otherwise
|
| 1245 |
+
a local ``.uscode_release_catalog_checkpoints`` directory under cwd.
|
| 1246 |
+
"""
|
| 1247 |
+
|
| 1248 |
+
env = os.environ.get("IPFS_ACCELERATE_AGENT_TASK_CHECKPOINT_DIR")
|
| 1249 |
+
if env:
|
| 1250 |
+
return Path(env)
|
| 1251 |
+
return Path.cwd() / ".uscode_release_catalog_checkpoints"
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
# ---------------------------------------------------------------------------
|
| 1255 |
+
# Catalog engine
|
| 1256 |
+
# ---------------------------------------------------------------------------
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
class UscodeReleaseCatalog:
|
| 1260 |
+
"""Exact all-title release catalog for the sealed US Code baseline.
|
| 1261 |
+
|
| 1262 |
+
Resolves one approved release, enumerates expected title packages,
|
| 1263 |
+
acquires packages from sealed fixtures (network opt-in is out of scope
|
| 1264 |
+
for unit tests), checkpoints resume receipts, and reports missing or
|
| 1265 |
+
excluded packages.
|
| 1266 |
+
"""
|
| 1267 |
+
|
| 1268 |
+
def __init__(
|
| 1269 |
+
self,
|
| 1270 |
+
*,
|
| 1271 |
+
policy: Optional[UscodeSourcePolicy] = None,
|
| 1272 |
+
fixture_path: PathLike | None = None,
|
| 1273 |
+
checkpoint_dir: PathLike | None = None,
|
| 1274 |
+
required_titles: Sequence[str] = CANONICAL_USCODE_TITLES,
|
| 1275 |
+
allow_network: bool = False,
|
| 1276 |
+
) -> None:
|
| 1277 |
+
self._policy = policy if policy is not None else UscodeSourcePolicy(
|
| 1278 |
+
required_titles=required_titles
|
| 1279 |
+
)
|
| 1280 |
+
self.fixture_path = (
|
| 1281 |
+
Path(fixture_path) if fixture_path is not None else default_catalog_fixture_path()
|
| 1282 |
+
)
|
| 1283 |
+
self.checkpoint_dir = (
|
| 1284 |
+
Path(checkpoint_dir)
|
| 1285 |
+
if checkpoint_dir is not None
|
| 1286 |
+
else default_checkpoint_directory()
|
| 1287 |
+
)
|
| 1288 |
+
self._required_titles: tuple[str, ...] = tuple(
|
| 1289 |
+
require_canonical_title(t) for t in required_titles
|
| 1290 |
+
)
|
| 1291 |
+
self.allow_network = bool(allow_network)
|
| 1292 |
+
self._last_result: Optional[CatalogAcquisitionResult] = None
|
| 1293 |
+
self._expected_packages: dict[str, TitlePackageSpec] = {}
|
| 1294 |
+
self._packages: dict[str, TitlePackageAcquisition] = {}
|
| 1295 |
+
self._receipts: dict[str, TitleResumeReceipt] = {}
|
| 1296 |
+
self._fixture_state: Optional[dict[str, Any]] = None
|
| 1297 |
+
|
| 1298 |
+
# -- properties --------------------------------------------------------
|
| 1299 |
+
|
| 1300 |
+
@property
|
| 1301 |
+
def policy(self) -> UscodeSourcePolicy:
|
| 1302 |
+
return self._policy
|
| 1303 |
+
|
| 1304 |
+
@property
|
| 1305 |
+
def required_titles(self) -> tuple[str, ...]:
|
| 1306 |
+
return self._required_titles
|
| 1307 |
+
|
| 1308 |
+
@property
|
| 1309 |
+
def last_result(self) -> Optional[CatalogAcquisitionResult]:
|
| 1310 |
+
return self._last_result
|
| 1311 |
+
|
| 1312 |
+
@property
|
| 1313 |
+
def expected_packages(self) -> Mapping[str, TitlePackageSpec]:
|
| 1314 |
+
return dict(self._expected_packages)
|
| 1315 |
+
|
| 1316 |
+
@property
|
| 1317 |
+
def packages(self) -> Mapping[str, TitlePackageAcquisition]:
|
| 1318 |
+
return dict(self._packages)
|
| 1319 |
+
|
| 1320 |
+
@property
|
| 1321 |
+
def resume_receipts(self) -> Mapping[str, TitleResumeReceipt]:
|
| 1322 |
+
return dict(self._receipts)
|
| 1323 |
+
|
| 1324 |
+
# -- release resolution ------------------------------------------------
|
| 1325 |
+
|
| 1326 |
+
def resolve_approved_release(
|
| 1327 |
+
self,
|
| 1328 |
+
*,
|
| 1329 |
+
release_point: Any | None = None,
|
| 1330 |
+
approved_by: str = DEFAULT_CATALOG_APPROVED_BY,
|
| 1331 |
+
approved_at: Any = DEFAULT_APPROVED_AT,
|
| 1332 |
+
provider: SourceProvider | str = SourceProvider.OLRC_HOUSE,
|
| 1333 |
+
edition: Optional[str] = None,
|
| 1334 |
+
notes: Optional[str] = None,
|
| 1335 |
+
from_fixture: bool = False,
|
| 1336 |
+
) -> ApprovedReleasePoint:
|
| 1337 |
+
"""Resolve and seal one approved exact release point for the catalog.
|
| 1338 |
+
|
| 1339 |
+
When *from_fixture* is True, the approved release is taken from the
|
| 1340 |
+
sealed catalog fixture. Proposed-latest discovery alone is never
|
| 1341 |
+
admitted as final provenance.
|
| 1342 |
+
"""
|
| 1343 |
+
|
| 1344 |
+
if from_fixture:
|
| 1345 |
+
state = self._ensure_fixture_state()
|
| 1346 |
+
approved = state["approved_release"]
|
| 1347 |
+
proposed = state.get("proposed_release")
|
| 1348 |
+
if proposed is not None:
|
| 1349 |
+
self._policy.propose_latest_from_discovery(
|
| 1350 |
+
release_point=proposed.release_point,
|
| 1351 |
+
provider=proposed.provider,
|
| 1352 |
+
discovered_at=proposed.discovered_at,
|
| 1353 |
+
discovery_source=proposed.discovery_source,
|
| 1354 |
+
edition=proposed.edition,
|
| 1355 |
+
notes=proposed.notes,
|
| 1356 |
+
)
|
| 1357 |
+
self._policy.approve_exact_release(
|
| 1358 |
+
approved,
|
| 1359 |
+
approved_by=approved.approved_by,
|
| 1360 |
+
approved_at=approved.approved_at,
|
| 1361 |
+
edition=approved.edition,
|
| 1362 |
+
notes=approved.notes,
|
| 1363 |
+
)
|
| 1364 |
+
for title, alt in (state.get("approved_mixed_overrides") or {}).items():
|
| 1365 |
+
self._policy.approve_mixed_override(title, alt)
|
| 1366 |
+
return self._policy.require_approved()
|
| 1367 |
+
|
| 1368 |
+
if release_point is None:
|
| 1369 |
+
if self._policy.approved_release is not None:
|
| 1370 |
+
return self._policy.require_approved()
|
| 1371 |
+
raise MissingApprovedReleaseError(
|
| 1372 |
+
"no approved exact release point; supply release_point or from_fixture=True"
|
| 1373 |
+
)
|
| 1374 |
+
|
| 1375 |
+
# Reject hard-coded latest before approval.
|
| 1376 |
+
if isinstance(release_point, str):
|
| 1377 |
+
try:
|
| 1378 |
+
parse_release_point_id(release_point)
|
| 1379 |
+
except HardCodedLatestEditionError:
|
| 1380 |
+
raise
|
| 1381 |
+
except UscodeSourcePolicyError:
|
| 1382 |
+
# Allow govinfo-style package ids through approve_exact_release.
|
| 1383 |
+
pass
|
| 1384 |
+
|
| 1385 |
+
if isinstance(release_point, ProposedReleasePoint):
|
| 1386 |
+
self._policy._proposed = release_point # record discovery
|
| 1387 |
+
return self._policy.approve_exact_release(
|
| 1388 |
+
release_point,
|
| 1389 |
+
approved_by=approved_by,
|
| 1390 |
+
approved_at=approved_at,
|
| 1391 |
+
provider=provider,
|
| 1392 |
+
edition=edition,
|
| 1393 |
+
notes=notes,
|
| 1394 |
+
)
|
| 1395 |
+
|
| 1396 |
+
return self._policy.approve_exact_release(
|
| 1397 |
+
release_point,
|
| 1398 |
+
approved_by=approved_by,
|
| 1399 |
+
approved_at=approved_at,
|
| 1400 |
+
provider=provider,
|
| 1401 |
+
edition=edition,
|
| 1402 |
+
notes=notes,
|
| 1403 |
+
)
|
| 1404 |
+
|
| 1405 |
+
def propose_latest_from_discovery(
|
| 1406 |
+
self,
|
| 1407 |
+
*,
|
| 1408 |
+
release_point: Any,
|
| 1409 |
+
provider: SourceProvider | str = SourceProvider.OLRC_HOUSE,
|
| 1410 |
+
discovered_at: Any = DEFAULT_DISCOVERED_AT,
|
| 1411 |
+
discovery_source: str = USHOUSE_DOWNLOAD_PAGE,
|
| 1412 |
+
edition: Optional[str] = None,
|
| 1413 |
+
notes: Optional[str] = None,
|
| 1414 |
+
) -> ProposedReleasePoint:
|
| 1415 |
+
"""Record a discovery-only proposed release (not final provenance)."""
|
| 1416 |
+
|
| 1417 |
+
return self._policy.propose_latest_from_discovery(
|
| 1418 |
+
release_point=release_point,
|
| 1419 |
+
provider=provider,
|
| 1420 |
+
discovered_at=discovered_at,
|
| 1421 |
+
discovery_source=discovery_source,
|
| 1422 |
+
edition=edition,
|
| 1423 |
+
notes=notes,
|
| 1424 |
+
)
|
| 1425 |
+
|
| 1426 |
+
# -- package enumeration -----------------------------------------------
|
| 1427 |
+
|
| 1428 |
+
def enumerate_expected_packages(
|
| 1429 |
+
self,
|
| 1430 |
+
*,
|
| 1431 |
+
format_kind: str = "xml",
|
| 1432 |
+
from_fixture: bool = False,
|
| 1433 |
+
) -> dict[str, TitlePackageSpec]:
|
| 1434 |
+
"""Enumerate every expected title package under the approved release."""
|
| 1435 |
+
|
| 1436 |
+
if from_fixture:
|
| 1437 |
+
state = self._ensure_fixture_state()
|
| 1438 |
+
self._expected_packages = dict(state["expected_packages"])
|
| 1439 |
+
return dict(self._expected_packages)
|
| 1440 |
+
|
| 1441 |
+
approved = self._policy.require_approved()
|
| 1442 |
+
specs: dict[str, TitlePackageSpec] = {}
|
| 1443 |
+
for title in self._required_titles:
|
| 1444 |
+
rp = self._policy.expected_release_for_title(title)
|
| 1445 |
+
if not str(rp).upper().startswith("USCODE-"):
|
| 1446 |
+
rp_n, congress, release = parse_release_point_id(rp)
|
| 1447 |
+
else:
|
| 1448 |
+
rp_n = rp
|
| 1449 |
+
congress = approved.congress or DEFAULT_APPROVED_CONGRESS
|
| 1450 |
+
release = approved.release or DEFAULT_APPROVED_RELEASE
|
| 1451 |
+
provider = approved.provider
|
| 1452 |
+
checksum = expected_title_package_sha256(
|
| 1453 |
+
release_point=rp_n, title=title, provider=provider
|
| 1454 |
+
)
|
| 1455 |
+
source_url = ushouse_releasepoint_zip_url(
|
| 1456 |
+
congress=congress or approved.congress or DEFAULT_APPROVED_CONGRESS,
|
| 1457 |
+
release=release or approved.release or DEFAULT_APPROVED_RELEASE,
|
| 1458 |
+
title=title,
|
| 1459 |
+
format_kind=format_kind,
|
| 1460 |
+
)
|
| 1461 |
+
specs[title] = TitlePackageSpec(
|
| 1462 |
+
title=title,
|
| 1463 |
+
release_point=rp_n,
|
| 1464 |
+
package_id=rp_n,
|
| 1465 |
+
source_url=source_url,
|
| 1466 |
+
expected_sha256=checksum,
|
| 1467 |
+
provider=provider,
|
| 1468 |
+
format_kind=format_kind,
|
| 1469 |
+
required=True,
|
| 1470 |
+
)
|
| 1471 |
+
self._expected_packages = specs
|
| 1472 |
+
return dict(specs)
|
| 1473 |
+
|
| 1474 |
+
# -- fixture acquisition -----------------------------------------------
|
| 1475 |
+
|
| 1476 |
+
def _ensure_fixture_state(self) -> dict[str, Any]:
|
| 1477 |
+
if self._fixture_state is None:
|
| 1478 |
+
self._fixture_state = load_catalog_fixture(self.fixture_path)
|
| 1479 |
+
return self._fixture_state
|
| 1480 |
+
|
| 1481 |
+
def load_fixture(self, path: PathLike | None = None) -> dict[str, Any]:
|
| 1482 |
+
"""Load and expand a catalog fixture, updating fixture_path when given."""
|
| 1483 |
+
|
| 1484 |
+
if path is not None:
|
| 1485 |
+
self.fixture_path = Path(path)
|
| 1486 |
+
self._fixture_state = None
|
| 1487 |
+
state = self._ensure_fixture_state()
|
| 1488 |
+
return state
|
| 1489 |
+
|
| 1490 |
+
def acquire_from_fixture(
|
| 1491 |
+
self,
|
| 1492 |
+
path: PathLike | None = None,
|
| 1493 |
+
*,
|
| 1494 |
+
checkpoint: bool = True,
|
| 1495 |
+
require_complete: bool = False,
|
| 1496 |
+
) -> CatalogAcquisitionResult:
|
| 1497 |
+
"""Acquire all title packages deterministically from a sealed fixture.
|
| 1498 |
+
|
| 1499 |
+
Every accepted package binds ``content_sha256`` and ``release_point``.
|
| 1500 |
+
Title completeness is reported explicitly (missing/excluded listed).
|
| 1501 |
+
"""
|
| 1502 |
+
|
| 1503 |
+
if path is not None:
|
| 1504 |
+
self.fixture_path = Path(path)
|
| 1505 |
+
self._fixture_state = None
|
| 1506 |
+
|
| 1507 |
+
state = self._ensure_fixture_state()
|
| 1508 |
+
approved = self.resolve_approved_release(from_fixture=True)
|
| 1509 |
+
expected = self.enumerate_expected_packages(from_fixture=True)
|
| 1510 |
+
|
| 1511 |
+
packages: dict[str, TitlePackageAcquisition] = {}
|
| 1512 |
+
receipts: dict[str, TitleResumeReceipt] = {}
|
| 1513 |
+
download_count = 0
|
| 1514 |
+
|
| 1515 |
+
for title in self._required_titles:
|
| 1516 |
+
pkg = state["packages"].get(title)
|
| 1517 |
+
if pkg is None:
|
| 1518 |
+
packages[title] = TitlePackageAcquisition(
|
| 1519 |
+
title=title,
|
| 1520 |
+
disposition=PackageDisposition.MISSING,
|
| 1521 |
+
release_point=None,
|
| 1522 |
+
content_sha256=None,
|
| 1523 |
+
status=TitlePackageStatus.FAILED,
|
| 1524 |
+
verification=VerificationResult.MISSING,
|
| 1525 |
+
notes=f"title {title} absent from fixture expansion",
|
| 1526 |
+
)
|
| 1527 |
+
continue
|
| 1528 |
+
|
| 1529 |
+
# Re-validate accepted packages bind checksum + release point.
|
| 1530 |
+
if pkg.disposition is PackageDisposition.ACCEPTED:
|
| 1531 |
+
if not pkg.content_sha256 or not pkg.release_point:
|
| 1532 |
+
raise CatalogAcquisitionError(
|
| 1533 |
+
f"fixture package for title {title} missing checksum or release_point"
|
| 1534 |
+
)
|
| 1535 |
+
# Admit into policy for mixed-vintage checks.
|
| 1536 |
+
if pkg.provenance is not None:
|
| 1537 |
+
self._policy.record_title_provenance(
|
| 1538 |
+
pkg.provenance, build_receipt=False
|
| 1539 |
+
)
|
| 1540 |
+
download_count += 1 if pkg.redownloaded else 0
|
| 1541 |
+
elif pkg.disposition is PackageDisposition.EXCLUDED:
|
| 1542 |
+
if pkg.provenance is not None:
|
| 1543 |
+
self._policy.record_title_provenance(
|
| 1544 |
+
pkg.provenance, build_receipt=False
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
packages[title] = pkg
|
| 1548 |
+
if pkg.resume_receipt is not None:
|
| 1549 |
+
receipts[title] = pkg.resume_receipt
|
| 1550 |
+
self._receipts[title] = pkg.resume_receipt
|
| 1551 |
+
self._packages[title] = pkg
|
| 1552 |
+
|
| 1553 |
+
# Ensure every expected title has an entry (explicit completeness).
|
| 1554 |
+
for title in self._required_titles:
|
| 1555 |
+
if title not in packages:
|
| 1556 |
+
packages[title] = TitlePackageAcquisition(
|
| 1557 |
+
title=title,
|
| 1558 |
+
disposition=PackageDisposition.MISSING,
|
| 1559 |
+
release_point=None,
|
| 1560 |
+
content_sha256=None,
|
| 1561 |
+
status=TitlePackageStatus.FAILED,
|
| 1562 |
+
verification=VerificationResult.MISSING,
|
| 1563 |
+
notes=f"title {title} not enumerated in acquisition",
|
| 1564 |
+
)
|
| 1565 |
+
|
| 1566 |
+
completeness = build_completeness_report(
|
| 1567 |
+
packages,
|
| 1568 |
+
expected_titles=self._required_titles,
|
| 1569 |
+
notes="Fixture acquisition completeness",
|
| 1570 |
+
metadata={"mode": CatalogAcquisitionMode.FIXTURE.value},
|
| 1571 |
+
)
|
| 1572 |
+
if require_complete and not completeness.is_complete:
|
| 1573 |
+
raise CatalogCompletenessError(
|
| 1574 |
+
"catalog acquisition incomplete: "
|
| 1575 |
+
f"missing={list(completeness.missing_titles)} "
|
| 1576 |
+
f"failed={list(completeness.failed_titles)}"
|
| 1577 |
+
)
|
| 1578 |
+
|
| 1579 |
+
result = CatalogAcquisitionResult(
|
| 1580 |
+
approved_release=approved,
|
| 1581 |
+
packages=packages,
|
| 1582 |
+
completeness=completeness,
|
| 1583 |
+
mode=CatalogAcquisitionMode.FIXTURE,
|
| 1584 |
+
resume_receipts=receipts,
|
| 1585 |
+
proposed_release=state.get("proposed_release"),
|
| 1586 |
+
expected_packages=expected,
|
| 1587 |
+
currentness_disclaimer=state.get(
|
| 1588 |
+
"currentness_disclaimer", CURRENTNESS_DISCLAIMER
|
| 1589 |
+
),
|
| 1590 |
+
schema_version=SCHEMA_VERSION,
|
| 1591 |
+
fixture_id=state.get("fixture_id"),
|
| 1592 |
+
notes=state.get("notes"),
|
| 1593 |
+
metadata={
|
| 1594 |
+
"fixture_schema_version": FIXTURE_SCHEMA_VERSION,
|
| 1595 |
+
"sample_exclusions": state.get("sample_exclusions") or [],
|
| 1596 |
+
},
|
| 1597 |
+
download_count=download_count,
|
| 1598 |
+
skip_count=0,
|
| 1599 |
+
)
|
| 1600 |
+
self._last_result = result
|
| 1601 |
+
|
| 1602 |
+
if checkpoint:
|
| 1603 |
+
self.checkpoint_receipts(result)
|
| 1604 |
+
|
| 1605 |
+
return result
|
| 1606 |
+
|
| 1607 |
+
def acquire_title_from_fixture(
|
| 1608 |
+
self,
|
| 1609 |
+
title: Any,
|
| 1610 |
+
*,
|
| 1611 |
+
path: PathLike | None = None,
|
| 1612 |
+
) -> TitlePackageAcquisition:
|
| 1613 |
+
"""Acquire a single title package from the sealed fixture."""
|
| 1614 |
+
|
| 1615 |
+
title_n = require_canonical_title(title)
|
| 1616 |
+
if path is not None or self._fixture_state is None:
|
| 1617 |
+
self.load_fixture(path)
|
| 1618 |
+
state = self._ensure_fixture_state()
|
| 1619 |
+
if self._policy.approved_release is None:
|
| 1620 |
+
self.resolve_approved_release(from_fixture=True)
|
| 1621 |
+
pkg = state["packages"].get(title_n)
|
| 1622 |
+
if pkg is None:
|
| 1623 |
+
acq = TitlePackageAcquisition(
|
| 1624 |
+
title=title_n,
|
| 1625 |
+
disposition=PackageDisposition.MISSING,
|
| 1626 |
+
release_point=None,
|
| 1627 |
+
content_sha256=None,
|
| 1628 |
+
status=TitlePackageStatus.FAILED,
|
| 1629 |
+
verification=VerificationResult.MISSING,
|
| 1630 |
+
notes=f"title {title_n} absent from fixture",
|
| 1631 |
+
)
|
| 1632 |
+
else:
|
| 1633 |
+
acq = pkg
|
| 1634 |
+
if acq.provenance is not None and acq.disposition in {
|
| 1635 |
+
PackageDisposition.ACCEPTED,
|
| 1636 |
+
PackageDisposition.EXCLUDED,
|
| 1637 |
+
}:
|
| 1638 |
+
self._policy.record_title_provenance(acq.provenance, build_receipt=False)
|
| 1639 |
+
if acq.resume_receipt is not None:
|
| 1640 |
+
self._receipts[title_n] = acq.resume_receipt
|
| 1641 |
+
self._packages[title_n] = acq
|
| 1642 |
+
return acq
|
| 1643 |
+
|
| 1644 |
+
# -- resume ------------------------------------------------------------
|
| 1645 |
+
|
| 1646 |
+
def resume(
|
| 1647 |
+
self,
|
| 1648 |
+
*,
|
| 1649 |
+
prior: CatalogAcquisitionResult | Mapping[str, Any] | None = None,
|
| 1650 |
+
checkpoint_path: PathLike | None = None,
|
| 1651 |
+
on_disk_checksums: Optional[Mapping[str, str]] = None,
|
| 1652 |
+
redownload_missing: bool = True,
|
| 1653 |
+
require_complete: bool = False,
|
| 1654 |
+
) -> CatalogAcquisitionResult:
|
| 1655 |
+
"""Resume catalog acquisition without redownloading verified packages.
|
| 1656 |
+
|
| 1657 |
+
For each title with a verified resume receipt whose on-disk checksum
|
| 1658 |
+
still matches (or is trusted when no on-disk hash is supplied), the
|
| 1659 |
+
package is marked ``skipped_verified`` and is **not** redownloaded.
|
| 1660 |
+
"""
|
| 1661 |
+
|
| 1662 |
+
if prior is None and checkpoint_path is None:
|
| 1663 |
+
# Fall back to last in-memory result or default checkpoint file.
|
| 1664 |
+
if self._last_result is not None:
|
| 1665 |
+
prior = self._last_result
|
| 1666 |
+
else:
|
| 1667 |
+
checkpoint_path = self.checkpoint_dir / "catalog_checkpoint.json"
|
| 1668 |
+
|
| 1669 |
+
if prior is None:
|
| 1670 |
+
prior = self.load_checkpoint(checkpoint_path)
|
| 1671 |
+
|
| 1672 |
+
if isinstance(prior, Mapping):
|
| 1673 |
+
# Accept either a full result or a checkpoint envelope.
|
| 1674 |
+
if "packages" in prior and "approved_release" in prior:
|
| 1675 |
+
prior_result = CatalogAcquisitionResult.from_dict(prior)
|
| 1676 |
+
elif "result" in prior:
|
| 1677 |
+
prior_result = CatalogAcquisitionResult.from_dict(prior["result"])
|
| 1678 |
+
else:
|
| 1679 |
+
raise CatalogCheckpointError(
|
| 1680 |
+
"checkpoint payload must contain packages/approved_release or result"
|
| 1681 |
+
)
|
| 1682 |
+
else:
|
| 1683 |
+
prior_result = prior
|
| 1684 |
+
|
| 1685 |
+
approved = prior_result.approved_release
|
| 1686 |
+
self._policy.approve_exact_release(
|
| 1687 |
+
approved,
|
| 1688 |
+
approved_by=approved.approved_by,
|
| 1689 |
+
approved_at=approved.approved_at,
|
| 1690 |
+
edition=approved.edition,
|
| 1691 |
+
notes=approved.notes,
|
| 1692 |
+
)
|
| 1693 |
+
if prior_result.proposed_release is not None:
|
| 1694 |
+
self._policy._proposed = prior_result.proposed_release
|
| 1695 |
+
|
| 1696 |
+
disk = {
|
| 1697 |
+
require_canonical_title(t): str(h).lower()
|
| 1698 |
+
for t, h in (on_disk_checksums or {}).items()
|
| 1699 |
+
}
|
| 1700 |
+
packages: dict[str, TitlePackageAcquisition] = {}
|
| 1701 |
+
receipts: dict[str, TitleResumeReceipt] = {}
|
| 1702 |
+
download_count = 0
|
| 1703 |
+
skip_count = 0
|
| 1704 |
+
|
| 1705 |
+
# Ensure fixture state is available for redownload of non-verified titles.
|
| 1706 |
+
fixture_packages: Mapping[str, TitlePackageAcquisition] = {}
|
| 1707 |
+
if redownload_missing:
|
| 1708 |
+
try:
|
| 1709 |
+
fixture_packages = self._ensure_fixture_state()["packages"]
|
| 1710 |
+
except (OSError, CatalogFixtureSchemaError, FileNotFoundError):
|
| 1711 |
+
fixture_packages = {}
|
| 1712 |
+
|
| 1713 |
+
for title in self._required_titles:
|
| 1714 |
+
prior_pkg = prior_result.packages.get(title)
|
| 1715 |
+
prior_receipt = prior_result.resume_receipts.get(title)
|
| 1716 |
+
if prior_receipt is None and prior_pkg is not None:
|
| 1717 |
+
prior_receipt = prior_pkg.resume_receipt
|
| 1718 |
+
|
| 1719 |
+
if prior_receipt is not None and prior_receipt.is_verified:
|
| 1720 |
+
on_disk = disk.get(title)
|
| 1721 |
+
disposition_map = self._policy.resume_from_receipt(
|
| 1722 |
+
prior_receipt, on_disk_sha256=on_disk
|
| 1723 |
+
)
|
| 1724 |
+
if disposition_map["should_skip_redownload"]:
|
| 1725 |
+
# Reconstruct skipped acquisition from prior without redownload.
|
| 1726 |
+
base = prior_pkg
|
| 1727 |
+
packages[title] = TitlePackageAcquisition(
|
| 1728 |
+
title=title,
|
| 1729 |
+
disposition=PackageDisposition.SKIPPED_VERIFIED,
|
| 1730 |
+
release_point=prior_receipt.release_point,
|
| 1731 |
+
content_sha256=prior_receipt.content_sha256,
|
| 1732 |
+
package_id=prior_receipt.package_id,
|
| 1733 |
+
source_url=prior_receipt.source_url,
|
| 1734 |
+
status=TitlePackageStatus.VERIFIED,
|
| 1735 |
+
verification=VerificationResult.VERIFIED,
|
| 1736 |
+
provenance=None if base is None else base.provenance,
|
| 1737 |
+
resume_receipt=prior_receipt,
|
| 1738 |
+
redownloaded=False,
|
| 1739 |
+
notes="resume: verified package skipped (no redownload)",
|
| 1740 |
+
metadata={
|
| 1741 |
+
"resume_action": "skip",
|
| 1742 |
+
"receipt_digest": prior_receipt.receipt_digest,
|
| 1743 |
+
},
|
| 1744 |
+
)
|
| 1745 |
+
receipts[title] = prior_receipt
|
| 1746 |
+
skip_count += 1
|
| 1747 |
+
self._packages[title] = packages[title]
|
| 1748 |
+
self._receipts[title] = prior_receipt
|
| 1749 |
+
continue
|
| 1750 |
+
# verify_failed or redownload: fall through to fixture re-acquire.
|
| 1751 |
+
|
| 1752 |
+
# Not verified / needs redownload — re-acquire from fixture if available.
|
| 1753 |
+
if redownload_missing and title in fixture_packages:
|
| 1754 |
+
fresh = fixture_packages[title]
|
| 1755 |
+
if fresh.disposition is PackageDisposition.ACCEPTED:
|
| 1756 |
+
# Count as a redownload.
|
| 1757 |
+
packages[title] = TitlePackageAcquisition(
|
| 1758 |
+
title=title,
|
| 1759 |
+
disposition=PackageDisposition.ACCEPTED,
|
| 1760 |
+
release_point=fresh.release_point,
|
| 1761 |
+
content_sha256=fresh.content_sha256,
|
| 1762 |
+
package_id=fresh.package_id,
|
| 1763 |
+
source_url=fresh.source_url,
|
| 1764 |
+
status=fresh.status,
|
| 1765 |
+
verification=fresh.verification,
|
| 1766 |
+
provenance=fresh.provenance,
|
| 1767 |
+
resume_receipt=fresh.resume_receipt,
|
| 1768 |
+
exclusion=fresh.exclusion,
|
| 1769 |
+
redownloaded=True,
|
| 1770 |
+
notes="resume: redownloaded from fixture",
|
| 1771 |
+
metadata={"resume_action": "redownload"},
|
| 1772 |
+
)
|
| 1773 |
+
download_count += 1
|
| 1774 |
+
if fresh.resume_receipt is not None:
|
| 1775 |
+
receipts[title] = fresh.resume_receipt
|
| 1776 |
+
self._receipts[title] = fresh.resume_receipt
|
| 1777 |
+
else:
|
| 1778 |
+
packages[title] = fresh
|
| 1779 |
+
if fresh.resume_receipt is not None:
|
| 1780 |
+
receipts[title] = fresh.resume_receipt
|
| 1781 |
+
self._packages[title] = packages[title]
|
| 1782 |
+
continue
|
| 1783 |
+
|
| 1784 |
+
if prior_pkg is not None:
|
| 1785 |
+
packages[title] = prior_pkg
|
| 1786 |
+
if prior_receipt is not None:
|
| 1787 |
+
receipts[title] = prior_receipt
|
| 1788 |
+
self._packages[title] = packages[title]
|
| 1789 |
+
else:
|
| 1790 |
+
packages[title] = TitlePackageAcquisition(
|
| 1791 |
+
title=title,
|
| 1792 |
+
disposition=PackageDisposition.MISSING,
|
| 1793 |
+
release_point=None,
|
| 1794 |
+
content_sha256=None,
|
| 1795 |
+
status=TitlePackageStatus.FAILED,
|
| 1796 |
+
verification=VerificationResult.MISSING,
|
| 1797 |
+
notes="resume: no prior package and no fixture redownload",
|
| 1798 |
+
)
|
| 1799 |
+
self._packages[title] = packages[title]
|
| 1800 |
+
|
| 1801 |
+
expected = prior_result.expected_packages or self.enumerate_expected_packages(
|
| 1802 |
+
from_fixture=bool(fixture_packages)
|
| 1803 |
+
)
|
| 1804 |
+
completeness = build_completeness_report(
|
| 1805 |
+
packages,
|
| 1806 |
+
expected_titles=self._required_titles,
|
| 1807 |
+
notes="Resume acquisition completeness",
|
| 1808 |
+
metadata={"mode": CatalogAcquisitionMode.RESUME.value},
|
| 1809 |
+
)
|
| 1810 |
+
if require_complete and not completeness.is_complete:
|
| 1811 |
+
raise CatalogCompletenessError(
|
| 1812 |
+
"catalog resume incomplete: "
|
| 1813 |
+
f"missing={list(completeness.missing_titles)} "
|
| 1814 |
+
f"failed={list(completeness.failed_titles)}"
|
| 1815 |
+
)
|
| 1816 |
+
|
| 1817 |
+
result = CatalogAcquisitionResult(
|
| 1818 |
+
approved_release=approved,
|
| 1819 |
+
packages=packages,
|
| 1820 |
+
completeness=completeness,
|
| 1821 |
+
mode=CatalogAcquisitionMode.RESUME,
|
| 1822 |
+
resume_receipts=receipts,
|
| 1823 |
+
proposed_release=prior_result.proposed_release,
|
| 1824 |
+
expected_packages=expected,
|
| 1825 |
+
currentness_disclaimer=prior_result.currentness_disclaimer,
|
| 1826 |
+
schema_version=SCHEMA_VERSION,
|
| 1827 |
+
fixture_id=prior_result.fixture_id,
|
| 1828 |
+
notes="Resumed catalog acquisition; verified packages not redownloaded",
|
| 1829 |
+
metadata={
|
| 1830 |
+
"prior_mode": prior_result.mode.value,
|
| 1831 |
+
"prior_download_count": prior_result.download_count,
|
| 1832 |
+
},
|
| 1833 |
+
download_count=download_count,
|
| 1834 |
+
skip_count=skip_count,
|
| 1835 |
+
)
|
| 1836 |
+
self._last_result = result
|
| 1837 |
+
self.checkpoint_receipts(result)
|
| 1838 |
+
return result
|
| 1839 |
+
|
| 1840 |
+
# -- completeness ------------------------------------------------------
|
| 1841 |
+
|
| 1842 |
+
def completeness_report(
|
| 1843 |
+
self,
|
| 1844 |
+
packages: Mapping[str, TitlePackageAcquisition] | None = None,
|
| 1845 |
+
*,
|
| 1846 |
+
require_complete: bool = False,
|
| 1847 |
+
) -> TitleCompletenessReport:
|
| 1848 |
+
"""Return an explicit title completeness report."""
|
| 1849 |
+
|
| 1850 |
+
if packages is None:
|
| 1851 |
+
if self._last_result is not None:
|
| 1852 |
+
packages = self._last_result.packages
|
| 1853 |
+
else:
|
| 1854 |
+
packages = self._packages
|
| 1855 |
+
report = build_completeness_report(
|
| 1856 |
+
packages, expected_titles=self._required_titles
|
| 1857 |
+
)
|
| 1858 |
+
if require_complete and not report.is_complete:
|
| 1859 |
+
raise CatalogCompletenessError(
|
| 1860 |
+
"title completeness failed: "
|
| 1861 |
+
f"missing={list(report.missing_titles)} "
|
| 1862 |
+
f"failed={list(report.failed_titles)} "
|
| 1863 |
+
f"excluded={list(report.excluded_titles)}"
|
| 1864 |
+
)
|
| 1865 |
+
return report
|
| 1866 |
+
|
| 1867 |
+
def report_missing_and_excluded(
|
| 1868 |
+
self,
|
| 1869 |
+
packages: Mapping[str, TitlePackageAcquisition] | None = None,
|
| 1870 |
+
) -> dict[str, tuple[str, ...]]:
|
| 1871 |
+
"""Return ``{"missing": (...), "excluded": (...)}`` title lists."""
|
| 1872 |
+
|
| 1873 |
+
report = self.completeness_report(packages)
|
| 1874 |
+
return {
|
| 1875 |
+
"missing": report.missing_titles,
|
| 1876 |
+
"excluded": report.excluded_titles,
|
| 1877 |
+
"failed": report.failed_titles,
|
| 1878 |
+
}
|
| 1879 |
+
|
| 1880 |
+
# -- checkpoints -------------------------------------------------------
|
| 1881 |
+
|
| 1882 |
+
def checkpoint_path(self, name: str = "catalog_checkpoint.json") -> Path:
|
| 1883 |
+
return Path(self.checkpoint_dir) / name
|
| 1884 |
+
|
| 1885 |
+
def checkpoint_receipts(
|
| 1886 |
+
self,
|
| 1887 |
+
result: CatalogAcquisitionResult | None = None,
|
| 1888 |
+
*,
|
| 1889 |
+
path: PathLike | None = None,
|
| 1890 |
+
) -> Path:
|
| 1891 |
+
"""Atomically write resume receipts and acquisition result to disk."""
|
| 1892 |
+
|
| 1893 |
+
if result is None:
|
| 1894 |
+
if self._last_result is None:
|
| 1895 |
+
raise CatalogCheckpointError("no acquisition result to checkpoint")
|
| 1896 |
+
result = self._last_result
|
| 1897 |
+
|
| 1898 |
+
target = Path(path) if path is not None else self.checkpoint_path()
|
| 1899 |
+
envelope = {
|
| 1900 |
+
"schema_version": SCHEMA_VERSION,
|
| 1901 |
+
"checkpoint_kind": "uscode-release-catalog",
|
| 1902 |
+
"approved_release": result.approved_release.to_dict(),
|
| 1903 |
+
"completeness": result.completeness.to_dict(),
|
| 1904 |
+
"download_count": result.download_count,
|
| 1905 |
+
"skip_count": result.skip_count,
|
| 1906 |
+
"fixture_id": result.fixture_id,
|
| 1907 |
+
"mode": result.mode.value,
|
| 1908 |
+
"resume_receipts": {
|
| 1909 |
+
k: v.to_dict()
|
| 1910 |
+
for k, v in sorted(result.resume_receipts.items(), key=lambda kv: kv[0])
|
| 1911 |
+
},
|
| 1912 |
+
"packages": {
|
| 1913 |
+
k: {
|
| 1914 |
+
"title": v.title,
|
| 1915 |
+
"disposition": v.disposition.value,
|
| 1916 |
+
"release_point": v.release_point,
|
| 1917 |
+
"content_sha256": v.content_sha256,
|
| 1918 |
+
"package_id": v.package_id,
|
| 1919 |
+
"source_url": v.source_url,
|
| 1920 |
+
"status": v.status.value,
|
| 1921 |
+
"verification": v.verification.value,
|
| 1922 |
+
"redownloaded": v.redownloaded,
|
| 1923 |
+
"resume_receipt": (
|
| 1924 |
+
None if v.resume_receipt is None else v.resume_receipt.to_dict()
|
| 1925 |
+
),
|
| 1926 |
+
"exclusion": None if v.exclusion is None else v.exclusion.to_dict(),
|
| 1927 |
+
"notes": v.notes,
|
| 1928 |
+
}
|
| 1929 |
+
for k, v in sorted(result.packages.items(), key=lambda kv: kv[0])
|
| 1930 |
+
},
|
| 1931 |
+
"result": result.to_dict(),
|
| 1932 |
+
"result_digest": result.result_digest(),
|
| 1933 |
+
}
|
| 1934 |
+
_atomic_write_json(target, envelope)
|
| 1935 |
+
return target
|
| 1936 |
+
|
| 1937 |
+
def load_checkpoint(self, path: PathLike | None = None) -> CatalogAcquisitionResult:
|
| 1938 |
+
"""Load a previously written catalog checkpoint."""
|
| 1939 |
+
|
| 1940 |
+
target = Path(path) if path is not None else self.checkpoint_path()
|
| 1941 |
+
if not target.is_file():
|
| 1942 |
+
raise CatalogCheckpointError(f"checkpoint not found: {target}")
|
| 1943 |
+
with target.open("r", encoding="utf-8") as handle:
|
| 1944 |
+
payload = json.load(handle)
|
| 1945 |
+
if not isinstance(payload, Mapping):
|
| 1946 |
+
raise CatalogCheckpointError(f"checkpoint root must be a mapping: {target}")
|
| 1947 |
+
if "result" in payload:
|
| 1948 |
+
return CatalogAcquisitionResult.from_dict(payload["result"])
|
| 1949 |
+
return CatalogAcquisitionResult.from_dict(payload)
|
| 1950 |
+
|
| 1951 |
+
# -- binding validation ------------------------------------------------
|
| 1952 |
+
|
| 1953 |
+
def assert_accepted_packages_bound(
|
| 1954 |
+
self,
|
| 1955 |
+
packages: Mapping[str, TitlePackageAcquisition] | None = None,
|
| 1956 |
+
) -> None:
|
| 1957 |
+
"""Fail closed when any accepted package lacks checksum or release point."""
|
| 1958 |
+
|
| 1959 |
+
if packages is None:
|
| 1960 |
+
packages = self._packages if self._packages else (
|
| 1961 |
+
self._last_result.packages if self._last_result else {}
|
| 1962 |
+
)
|
| 1963 |
+
for title, pkg in packages.items():
|
| 1964 |
+
if pkg.disposition in {
|
| 1965 |
+
PackageDisposition.ACCEPTED,
|
| 1966 |
+
PackageDisposition.SKIPPED_VERIFIED,
|
| 1967 |
+
}:
|
| 1968 |
+
if not pkg.content_sha256:
|
| 1969 |
+
raise CatalogAcquisitionError(
|
| 1970 |
+
f"accepted package for title {title} missing content_sha256"
|
| 1971 |
+
)
|
| 1972 |
+
if not pkg.release_point:
|
| 1973 |
+
raise CatalogAcquisitionError(
|
| 1974 |
+
f"accepted package for title {title} missing release_point"
|
| 1975 |
+
)
|
| 1976 |
+
|
| 1977 |
+
|
| 1978 |
+
__all__ = [
|
| 1979 |
+
"CANONICAL_USCODE_TITLES",
|
| 1980 |
+
"CURRENTNESS_DISCLAIMER",
|
| 1981 |
+
"DEFAULT_APPROVED_RELEASE_POINT",
|
| 1982 |
+
"DEFAULT_CATALOG_APPROVED_BY",
|
| 1983 |
+
"DEFAULT_FIXTURE_ID",
|
| 1984 |
+
"EXPECTED_TITLE_COUNT",
|
| 1985 |
+
"FIXTURE_SCHEMA_VERSION",
|
| 1986 |
+
"SCHEMA_VERSION",
|
| 1987 |
+
"CatalogAcquisitionError",
|
| 1988 |
+
"CatalogAcquisitionMode",
|
| 1989 |
+
"CatalogAcquisitionResult",
|
| 1990 |
+
"CatalogCheckpointError",
|
| 1991 |
+
"CatalogCompletenessError",
|
| 1992 |
+
"CatalogFixtureSchemaError",
|
| 1993 |
+
"HardCodedLatestEditionError",
|
| 1994 |
+
"MissingApprovedReleaseError",
|
| 1995 |
+
"PackageDisposition",
|
| 1996 |
+
"TitleCompletenessReport",
|
| 1997 |
+
"TitlePackageAcquisition",
|
| 1998 |
+
"TitlePackageSpec",
|
| 1999 |
+
"UnapprovedMixedVintageError",
|
| 2000 |
+
"UnapprovedProposedReleaseError",
|
| 2001 |
+
"UscodeReleaseCatalog",
|
| 2002 |
+
"UscodeReleaseCatalogError",
|
| 2003 |
+
"UscodeSourcePolicy",
|
| 2004 |
+
"build_completeness_report",
|
| 2005 |
+
"build_default_catalog_fixture_payload",
|
| 2006 |
+
"canonical_json_dumps",
|
| 2007 |
+
"content_sha256",
|
| 2008 |
+
"default_catalog_fixture_path",
|
| 2009 |
+
"default_checkpoint_directory",
|
| 2010 |
+
"digest_mapping",
|
| 2011 |
+
"expand_catalog_fixture",
|
| 2012 |
+
"expected_title_package_sha256",
|
| 2013 |
+
"load_catalog_fixture",
|
| 2014 |
+
"load_catalog_fixture_payload",
|
| 2015 |
+
"normalize_title",
|
| 2016 |
+
"parse_release_point_id",
|
| 2017 |
+
"require_canonical_title",
|
| 2018 |
+
"titles_missing_from_manifest",
|
| 2019 |
+
"ushouse_releasepoint_zip_url",
|
| 2020 |
+
"ushouse_title_code",
|
| 2021 |
+
"write_default_catalog_fixture",
|
| 2022 |
+
]
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/federal_scrapers/uscode_release_processor.py
ADDED
|
@@ -0,0 +1,1539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Title 35 U.S. Code release-point acquisition (PATLAW-013).
|
| 2 |
+
|
| 3 |
+
Acquires exact House OLRC / GovInfo U.S. Code release points for Title 35
|
| 4 |
+
(Patents), records USLM/XML/HTML/PDF identities and source receipts, and
|
| 5 |
+
exposes uncodified / slip-law classification gaps instead of pretending the
|
| 6 |
+
current codification is complete.
|
| 7 |
+
|
| 8 |
+
Design invariants:
|
| 9 |
+
|
| 10 |
+
* Edition identity is never the hard-coded token ``"latest"``; connectors
|
| 11 |
+
record concrete release-point / package identifiers.
|
| 12 |
+
* Stable section identity is independent of source format (USLM, XML, HTML,
|
| 13 |
+
PDF): ``usc:{title}:{section}``.
|
| 14 |
+
* Missing release-point data yields status ``unknown`` (fail-closed).
|
| 15 |
+
* Official artifact identity and derived presentation identity remain
|
| 16 |
+
distinct via :mod:`patent_authority_sources`.
|
| 17 |
+
* Live network I/O is opt-in; unit tests use recorded fixtures only.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import hashlib
|
| 23 |
+
import json
|
| 24 |
+
import re
|
| 25 |
+
from dataclasses import dataclass, field
|
| 26 |
+
from datetime import date, datetime, timezone
|
| 27 |
+
from enum import Enum
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any, Iterable, Iterator, Mapping, MutableMapping, Optional, Sequence, Union
|
| 30 |
+
|
| 31 |
+
from ipfs_datasets_py.processors.legal_data.patent_authority_sources import (
|
| 32 |
+
SCHEMA_VERSION as AUTHORITY_SCHEMA_VERSION,
|
| 33 |
+
AuthoritySourceRecord,
|
| 34 |
+
AuthoritySourceRegistry,
|
| 35 |
+
AuthorityTier,
|
| 36 |
+
ArtifactIdentity,
|
| 37 |
+
HardCodedLatestEditionError,
|
| 38 |
+
IdentityRole,
|
| 39 |
+
RetryCachePolicy,
|
| 40 |
+
SourceReceipt,
|
| 41 |
+
VerificationState,
|
| 42 |
+
canonical_json_dumps,
|
| 43 |
+
reject_hard_coded_latest,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
SCHEMA_VERSION = "uscode-release-processor-v1"
|
| 47 |
+
FIXTURE_SCHEMA_VERSION = "uscode-release-fixture-v1"
|
| 48 |
+
|
| 49 |
+
DEFAULT_TITLE = "35"
|
| 50 |
+
DEFAULT_JURISDICTION = "US"
|
| 51 |
+
COLLECTION_USCODE = "USCODE"
|
| 52 |
+
|
| 53 |
+
# Patent-sensitive Title 35 sections required by PATLAW-013 / privacy gate.
|
| 54 |
+
CONFIDENTIALITY_SECTION = "122"
|
| 55 |
+
SECRECY_ORDER_SECTIONS = tuple(str(n) for n in range(181, 189)) # 181–188 inclusive
|
| 56 |
+
PATENT_SENSITIVE_SECTIONS = (CONFIDENTIALITY_SECTION, *SECRECY_ORDER_SECTIONS)
|
| 57 |
+
|
| 58 |
+
USHOUSE_DOWNLOAD_PAGE = "https://uscode.house.gov/download/download.shtml"
|
| 59 |
+
USHOUSE_RELEASEPOINT_BASE = "https://uscode.house.gov/download/releasepoints"
|
| 60 |
+
GOVINFO_CONTENT_BASE = "https://www.govinfo.gov/content/pkg"
|
| 61 |
+
|
| 62 |
+
_SECTION_TOKEN_RE = re.compile(
|
| 63 |
+
r"(?:§+\s*)?(?:sec(?:tion)?\.?\s*)?(?P<section>\d+[A-Za-z0-9.\-]*(?:\([a-zA-Z0-9]+\))*)",
|
| 64 |
+
re.IGNORECASE,
|
| 65 |
+
)
|
| 66 |
+
_RELEASE_POINT_RE = re.compile(
|
| 67 |
+
r"(?:us/pl/)?(?P<congress>\d+)(?:[/\-])(?P<release>[A-Za-z0-9]+)",
|
| 68 |
+
re.IGNORECASE,
|
| 69 |
+
)
|
| 70 |
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
| 71 |
+
|
| 72 |
+
PathLike = Union[str, Path]
|
| 73 |
+
JsonMapping = Mapping[str, Any]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class UscodeReleaseError(ValueError):
|
| 77 |
+
"""Base error for Title 35 release-point acquisition failures."""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class MissingReleasePointError(UscodeReleaseError):
|
| 81 |
+
"""Raised when release-point identity cannot be established."""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class FixtureSchemaError(UscodeReleaseError):
|
| 85 |
+
"""Raised when a fixture package is malformed."""
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SectionNotFoundError(UscodeReleaseError):
|
| 89 |
+
"""Raised when a requested section is not present in the acquisition."""
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class ResolutionStatus(str, Enum):
|
| 93 |
+
"""Outcome of release-point or section resolution."""
|
| 94 |
+
|
| 95 |
+
RESOLVED = "resolved"
|
| 96 |
+
UNKNOWN = "unknown"
|
| 97 |
+
PARTIAL = "partial"
|
| 98 |
+
ERROR = "error"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class SourceFormat(str, Enum):
|
| 102 |
+
"""Supported U.S. Code source packaging formats."""
|
| 103 |
+
|
| 104 |
+
USLM = "uslm"
|
| 105 |
+
XML = "xml"
|
| 106 |
+
HTML = "html"
|
| 107 |
+
HTM = "htm"
|
| 108 |
+
PDF = "pdf"
|
| 109 |
+
ZIP = "zip"
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def coerce(cls, value: Any) -> "SourceFormat":
|
| 113 |
+
if isinstance(value, SourceFormat):
|
| 114 |
+
return value
|
| 115 |
+
text = str(value or "").strip().lower()
|
| 116 |
+
aliases = {
|
| 117 |
+
"uslm": cls.USLM,
|
| 118 |
+
"uslm+xml": cls.USLM,
|
| 119 |
+
"application/uslm+xml": cls.USLM,
|
| 120 |
+
"xml": cls.XML,
|
| 121 |
+
"application/xml": cls.XML,
|
| 122 |
+
"text/xml": cls.XML,
|
| 123 |
+
"html": cls.HTML,
|
| 124 |
+
"htm": cls.HTM,
|
| 125 |
+
"text/html": cls.HTML,
|
| 126 |
+
"pdf": cls.PDF,
|
| 127 |
+
"application/pdf": cls.PDF,
|
| 128 |
+
"zip": cls.ZIP,
|
| 129 |
+
"application/zip": cls.ZIP,
|
| 130 |
+
}
|
| 131 |
+
if text not in aliases:
|
| 132 |
+
raise UscodeReleaseError(f"unsupported source format: {value!r}")
|
| 133 |
+
return aliases[text]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class ExclusionKind(str, Enum):
|
| 137 |
+
"""Kinds of release-point exclusions / classification gaps."""
|
| 138 |
+
|
| 139 |
+
UNCODIFIED_SLIP_LAW = "uncodified_slip_law"
|
| 140 |
+
CLASSIFICATION_GAP = "classification_gap"
|
| 141 |
+
POSITIVE_LAW_PENDING = "positive_law_pending"
|
| 142 |
+
EDITORIAL_NOTE = "editorial_note"
|
| 143 |
+
OMITTED = "omitted"
|
| 144 |
+
TRANSFERRED = "transferred"
|
| 145 |
+
OTHER = "other"
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def coerce(cls, value: Any) -> "ExclusionKind":
|
| 149 |
+
if isinstance(value, ExclusionKind):
|
| 150 |
+
return value
|
| 151 |
+
text = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
|
| 152 |
+
for kind in cls:
|
| 153 |
+
if kind.value == text or kind.name.lower() == text:
|
| 154 |
+
return kind
|
| 155 |
+
return cls.OTHER
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _require_non_empty_str(value: Any, name: str) -> str:
|
| 159 |
+
if not isinstance(value, str) or not value.strip():
|
| 160 |
+
raise UscodeReleaseError(f"{name} must be a non-empty string")
|
| 161 |
+
if "\x00" in value:
|
| 162 |
+
raise UscodeReleaseError(f"{name} must not contain NUL")
|
| 163 |
+
return value.strip()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _optional_str(value: Any) -> Optional[str]:
|
| 167 |
+
if value is None or value == "":
|
| 168 |
+
return None
|
| 169 |
+
return _require_non_empty_str(value, "value")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _require_sha256(value: Any, name: str = "sha256") -> str:
|
| 173 |
+
text = _require_non_empty_str(value, name).lower()
|
| 174 |
+
if not _SHA256_RE.fullmatch(text):
|
| 175 |
+
raise UscodeReleaseError(f"{name} must be a lowercase 64-char hex SHA-256")
|
| 176 |
+
return text
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _parse_utc(value: Any, *, name: str = "retrieved_at") -> datetime:
|
| 180 |
+
if isinstance(value, datetime):
|
| 181 |
+
dt = value
|
| 182 |
+
elif isinstance(value, str):
|
| 183 |
+
text = value.strip()
|
| 184 |
+
if text.endswith("Z"):
|
| 185 |
+
text = text[:-1] + "+00:00"
|
| 186 |
+
try:
|
| 187 |
+
dt = datetime.fromisoformat(text)
|
| 188 |
+
except ValueError as exc:
|
| 189 |
+
raise UscodeReleaseError(f"{name} must be ISO-8601 datetime") from exc
|
| 190 |
+
else:
|
| 191 |
+
raise UscodeReleaseError(f"{name} must be a datetime or ISO-8601 string")
|
| 192 |
+
if dt.tzinfo is None:
|
| 193 |
+
dt = dt.replace(tzinfo=timezone.utc)
|
| 194 |
+
else:
|
| 195 |
+
dt = dt.astimezone(timezone.utc)
|
| 196 |
+
return dt
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _format_utc(dt: datetime) -> str:
|
| 200 |
+
normalized = dt.astimezone(timezone.utc).replace(microsecond=(dt.microsecond // 1000) * 1000)
|
| 201 |
+
return normalized.isoformat().replace("+00:00", "Z")
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _parse_optional_date(value: Any) -> Optional[date]:
|
| 205 |
+
if value is None or value == "":
|
| 206 |
+
return None
|
| 207 |
+
if isinstance(value, date) and not isinstance(value, datetime):
|
| 208 |
+
return value
|
| 209 |
+
if isinstance(value, datetime):
|
| 210 |
+
return value.date()
|
| 211 |
+
if isinstance(value, str):
|
| 212 |
+
return date.fromisoformat(value.strip()[:10])
|
| 213 |
+
raise UscodeReleaseError(f"invalid date value: {value!r}")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _date_to_str(value: Optional[date]) -> Optional[str]:
|
| 217 |
+
return None if value is None else value.isoformat()
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _deep_sorted(value: Any) -> Any:
|
| 221 |
+
if isinstance(value, Mapping):
|
| 222 |
+
return {str(k): _deep_sorted(value[k]) for k in sorted(value.keys(), key=lambda x: str(x))}
|
| 223 |
+
if isinstance(value, (list, tuple)):
|
| 224 |
+
return [_deep_sorted(v) for v in value]
|
| 225 |
+
return value
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def normalize_title(title: Any) -> str:
|
| 229 |
+
"""Normalize a U.S. Code title number to a stable string (e.g. ``\"35\"``)."""
|
| 230 |
+
|
| 231 |
+
text = str(title if title is not None else "").strip()
|
| 232 |
+
if not text:
|
| 233 |
+
raise UscodeReleaseError("title must be non-empty")
|
| 234 |
+
if text.isdigit():
|
| 235 |
+
return str(int(text))
|
| 236 |
+
# Preserve lettered titles (e.g. 10a) in lowercase.
|
| 237 |
+
return text.lower()
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def normalize_section_token(section: Any) -> str:
|
| 241 |
+
"""Normalize a section citation token to a stable section number.
|
| 242 |
+
|
| 243 |
+
Accepts ``122``, ``§ 122``, ``section 122``, ``35 U.S.C. § 122``, etc.
|
| 244 |
+
Parenthetical subsections on the section number (``181(a)``) are preserved
|
| 245 |
+
when present; bare integers are returned without leading zeros.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
if section is None:
|
| 249 |
+
raise UscodeReleaseError("section must be non-empty")
|
| 250 |
+
text = str(section).strip()
|
| 251 |
+
if not text:
|
| 252 |
+
raise UscodeReleaseError("section must be non-empty")
|
| 253 |
+
|
| 254 |
+
# Prefer the last § / section-like token when a full citation is supplied.
|
| 255 |
+
candidates = list(_SECTION_TOKEN_RE.finditer(text))
|
| 256 |
+
if candidates:
|
| 257 |
+
raw = candidates[-1].group("section")
|
| 258 |
+
else:
|
| 259 |
+
raw = text
|
| 260 |
+
|
| 261 |
+
raw = raw.strip().lstrip("§").strip()
|
| 262 |
+
# Collapse whitespace inside parentheticals already stripped by the regex.
|
| 263 |
+
raw = re.sub(r"\s+", "", raw)
|
| 264 |
+
|
| 265 |
+
# Numeric base without leading zeros: 0122 -> 122, keep lettered tails.
|
| 266 |
+
m = re.match(r"^0*(\d+)([A-Za-z0-9.\-()]*)$", raw)
|
| 267 |
+
if m:
|
| 268 |
+
return f"{int(m.group(1))}{m.group(2)}"
|
| 269 |
+
return raw
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def stable_section_identity(
|
| 273 |
+
*,
|
| 274 |
+
title: Any = DEFAULT_TITLE,
|
| 275 |
+
section: Any,
|
| 276 |
+
jurisdiction: str = DEFAULT_JURISDICTION,
|
| 277 |
+
) -> str:
|
| 278 |
+
"""Return a format-independent stable section identity.
|
| 279 |
+
|
| 280 |
+
Shape: ``usc:{jurisdiction}:{title}:{section}`` (lower-case jurisdiction).
|
| 281 |
+
Source packaging format (USLM/XML/HTML/PDF) is intentionally excluded so
|
| 282 |
+
dual-format acquisitions of the same statute share one identity.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
title_n = normalize_title(title)
|
| 286 |
+
section_n = normalize_section_token(section)
|
| 287 |
+
jur = _require_non_empty_str(jurisdiction, "jurisdiction").lower()
|
| 288 |
+
return f"usc:{jur}:{title_n}:{section_n}"
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def parse_release_point_id(value: Any) -> tuple[str, str, str]:
|
| 292 |
+
"""Parse a release-point token into ``(canonical_id, congress, release)``.
|
| 293 |
+
|
| 294 |
+
Accepts ``us/pl/118/45``, ``118-45``, ``118/45``. Rejects ``latest``.
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
text = _require_non_empty_str(value, "release_point")
|
| 298 |
+
reject_hard_coded_latest(text, field_name="release_point")
|
| 299 |
+
match = _RELEASE_POINT_RE.fullmatch(text.replace(" ", ""))
|
| 300 |
+
if not match:
|
| 301 |
+
# Also accept already-canonical paths with us/pl/ prefix only partially.
|
| 302 |
+
match = _RELEASE_POINT_RE.search(text)
|
| 303 |
+
if not match:
|
| 304 |
+
raise UscodeReleaseError(f"unrecognized release_point: {value!r}")
|
| 305 |
+
congress = str(int(match.group("congress")))
|
| 306 |
+
release = str(match.group("release")).strip()
|
| 307 |
+
if not release or release.lower() == "latest":
|
| 308 |
+
raise HardCodedLatestEditionError(
|
| 309 |
+
"release_point must not use the hard-coded token 'latest'"
|
| 310 |
+
)
|
| 311 |
+
canonical = f"us/pl/{congress}/{release}"
|
| 312 |
+
return canonical, congress, release
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def ushouse_title_code(title: Any) -> str:
|
| 316 |
+
"""Return the two-digit (or lettered) House OLRC title code."""
|
| 317 |
+
|
| 318 |
+
text = normalize_title(title)
|
| 319 |
+
if text.isdigit():
|
| 320 |
+
return f"{int(text):02d}"
|
| 321 |
+
return text.lower()
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def ushouse_releasepoint_zip_url(
|
| 325 |
+
*,
|
| 326 |
+
congress: Any,
|
| 327 |
+
release: Any,
|
| 328 |
+
title: Any = DEFAULT_TITLE,
|
| 329 |
+
format_kind: SourceFormat | str = SourceFormat.HTML,
|
| 330 |
+
) -> str:
|
| 331 |
+
"""Build a House OLRC release-point zip URL for one title package."""
|
| 332 |
+
|
| 333 |
+
canonical, congress_s, release_s = parse_release_point_id(f"{congress}/{release}")
|
| 334 |
+
del canonical # used only for validation
|
| 335 |
+
code = ushouse_title_code(title)
|
| 336 |
+
fmt = SourceFormat.coerce(format_kind)
|
| 337 |
+
prefix = {
|
| 338 |
+
SourceFormat.HTML: "htm",
|
| 339 |
+
SourceFormat.HTM: "htm",
|
| 340 |
+
SourceFormat.XML: "xml",
|
| 341 |
+
SourceFormat.USLM: "xml",
|
| 342 |
+
SourceFormat.PDF: "pdf",
|
| 343 |
+
SourceFormat.ZIP: "htm",
|
| 344 |
+
}[fmt]
|
| 345 |
+
return (
|
| 346 |
+
f"{USHOUSE_RELEASEPOINT_BASE}/us/pl/{congress_s}/{release_s}/"
|
| 347 |
+
f"{prefix}_usc{code}@{congress_s}-{release_s}.zip"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def govinfo_title_package_id(*, year: Any, title: Any = DEFAULT_TITLE) -> str:
|
| 352 |
+
"""Return a concrete GovInfo USCODE package id (never ``latest``)."""
|
| 353 |
+
|
| 354 |
+
year_s = _require_non_empty_str(str(year), "year")
|
| 355 |
+
reject_hard_coded_latest(year_s, field_name="year")
|
| 356 |
+
if not year_s.isdigit():
|
| 357 |
+
raise UscodeReleaseError(f"year must be numeric, got {year!r}")
|
| 358 |
+
title_n = normalize_title(title)
|
| 359 |
+
return f"USCODE-{year_s}-title{title_n}"
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def govinfo_title_zip_url(*, year: Any, title: Any = DEFAULT_TITLE) -> str:
|
| 363 |
+
package = govinfo_title_package_id(year=year, title=title)
|
| 364 |
+
return f"{GOVINFO_CONTENT_BASE}/{package}/zip/{package}.zip"
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def content_sha256(data: bytes | str) -> str:
|
| 368 |
+
if isinstance(data, str):
|
| 369 |
+
data = data.encode("utf-8")
|
| 370 |
+
return hashlib.sha256(data).hexdigest()
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@dataclass(frozen=True, slots=True)
|
| 374 |
+
class ReleasePoint:
|
| 375 |
+
"""Exact House OLRC or GovInfo U.S. Code release identity."""
|
| 376 |
+
|
| 377 |
+
release_point: str
|
| 378 |
+
provider: str
|
| 379 |
+
title: str = DEFAULT_TITLE
|
| 380 |
+
congress: Optional[str] = None
|
| 381 |
+
release: Optional[str] = None
|
| 382 |
+
govinfo_package_id: Optional[str] = None
|
| 383 |
+
edition: Optional[str] = None
|
| 384 |
+
year: Optional[str] = None
|
| 385 |
+
source_url: Optional[str] = None
|
| 386 |
+
content_sha256: Optional[str] = None
|
| 387 |
+
retrieved_at: Optional[datetime] = None
|
| 388 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 389 |
+
|
| 390 |
+
def __post_init__(self) -> None:
|
| 391 |
+
object.__setattr__(
|
| 392 |
+
self, "release_point", _require_non_empty_str(self.release_point, "release_point")
|
| 393 |
+
)
|
| 394 |
+
reject_hard_coded_latest(self.release_point, field_name="release_point")
|
| 395 |
+
object.__setattr__(self, "provider", _require_non_empty_str(self.provider, "provider"))
|
| 396 |
+
object.__setattr__(self, "title", normalize_title(self.title))
|
| 397 |
+
if self.congress is not None:
|
| 398 |
+
object.__setattr__(self, "congress", str(int(str(self.congress).strip())))
|
| 399 |
+
if self.release is not None:
|
| 400 |
+
rel = _require_non_empty_str(str(self.release), "release")
|
| 401 |
+
reject_hard_coded_latest(rel, field_name="release")
|
| 402 |
+
object.__setattr__(self, "release", rel)
|
| 403 |
+
if self.govinfo_package_id is not None:
|
| 404 |
+
pkg = _require_non_empty_str(self.govinfo_package_id, "govinfo_package_id")
|
| 405 |
+
reject_hard_coded_latest(pkg, field_name="govinfo_package_id")
|
| 406 |
+
object.__setattr__(self, "govinfo_package_id", pkg)
|
| 407 |
+
if self.edition is not None:
|
| 408 |
+
ed = _require_non_empty_str(self.edition, "edition")
|
| 409 |
+
reject_hard_coded_latest(ed, field_name="edition")
|
| 410 |
+
object.__setattr__(self, "edition", ed)
|
| 411 |
+
if self.year is not None:
|
| 412 |
+
object.__setattr__(self, "year", _require_non_empty_str(str(self.year), "year"))
|
| 413 |
+
reject_hard_coded_latest(self.year, field_name="year")
|
| 414 |
+
if self.source_url is not None:
|
| 415 |
+
object.__setattr__(
|
| 416 |
+
self, "source_url", _require_non_empty_str(self.source_url, "source_url")
|
| 417 |
+
)
|
| 418 |
+
if self.content_sha256 is not None:
|
| 419 |
+
object.__setattr__(
|
| 420 |
+
self, "content_sha256", _require_sha256(self.content_sha256, "content_sha256")
|
| 421 |
+
)
|
| 422 |
+
if self.retrieved_at is not None:
|
| 423 |
+
object.__setattr__(
|
| 424 |
+
self, "retrieved_at", _parse_utc(self.retrieved_at, name="retrieved_at")
|
| 425 |
+
)
|
| 426 |
+
if not isinstance(self.metadata, Mapping):
|
| 427 |
+
raise UscodeReleaseError("metadata must be a mapping")
|
| 428 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 429 |
+
|
| 430 |
+
@property
|
| 431 |
+
def canonical_id(self) -> str:
|
| 432 |
+
return self.release_point
|
| 433 |
+
|
| 434 |
+
def to_dict(self) -> dict[str, Any]:
|
| 435 |
+
return {
|
| 436 |
+
"congress": self.congress,
|
| 437 |
+
"content_sha256": self.content_sha256,
|
| 438 |
+
"edition": self.edition,
|
| 439 |
+
"govinfo_package_id": self.govinfo_package_id,
|
| 440 |
+
"metadata": _deep_sorted(self.metadata),
|
| 441 |
+
"provider": self.provider,
|
| 442 |
+
"release": self.release,
|
| 443 |
+
"release_point": self.release_point,
|
| 444 |
+
"retrieved_at": None if self.retrieved_at is None else _format_utc(self.retrieved_at),
|
| 445 |
+
"source_url": self.source_url,
|
| 446 |
+
"title": self.title,
|
| 447 |
+
"year": self.year,
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
@classmethod
|
| 451 |
+
def from_dict(cls, value: JsonMapping) -> "ReleasePoint":
|
| 452 |
+
if not isinstance(value, Mapping):
|
| 453 |
+
raise UscodeReleaseError("release point must be a mapping")
|
| 454 |
+
release_point = value.get("release_point")
|
| 455 |
+
congress = value.get("congress")
|
| 456 |
+
release = value.get("release")
|
| 457 |
+
if release_point:
|
| 458 |
+
canonical, c, r = parse_release_point_id(release_point)
|
| 459 |
+
congress = congress or c
|
| 460 |
+
release = release or r
|
| 461 |
+
release_point = canonical
|
| 462 |
+
elif congress is not None and release is not None:
|
| 463 |
+
release_point, congress, release = parse_release_point_id(f"{congress}/{release}")
|
| 464 |
+
elif value.get("govinfo_package_id"):
|
| 465 |
+
# GovInfo annual package used as the release identity.
|
| 466 |
+
pkg = _require_non_empty_str(value.get("govinfo_package_id"), "govinfo_package_id")
|
| 467 |
+
reject_hard_coded_latest(pkg, field_name="govinfo_package_id")
|
| 468 |
+
release_point = pkg
|
| 469 |
+
else:
|
| 470 |
+
raise MissingReleasePointError(
|
| 471 |
+
"release_point, congress/release, or govinfo_package_id is required"
|
| 472 |
+
)
|
| 473 |
+
return cls(
|
| 474 |
+
release_point=str(release_point),
|
| 475 |
+
provider=str(value.get("provider") or "ushouse"),
|
| 476 |
+
title=value.get("title", DEFAULT_TITLE),
|
| 477 |
+
congress=None if congress is None else str(congress),
|
| 478 |
+
release=None if release is None else str(release),
|
| 479 |
+
govinfo_package_id=value.get("govinfo_package_id"),
|
| 480 |
+
edition=value.get("edition"),
|
| 481 |
+
year=value.get("year"),
|
| 482 |
+
source_url=value.get("source_url"),
|
| 483 |
+
content_sha256=value.get("content_sha256"),
|
| 484 |
+
retrieved_at=value.get("retrieved_at"),
|
| 485 |
+
metadata=value.get("metadata") or {},
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
@dataclass(frozen=True, slots=True)
|
| 490 |
+
class ReleaseExclusion:
|
| 491 |
+
"""An uncodified, classification-gap, or related exclusion for a release."""
|
| 492 |
+
|
| 493 |
+
kind: ExclusionKind
|
| 494 |
+
citation: str
|
| 495 |
+
reason: str
|
| 496 |
+
affects_sections: tuple[str, ...] = ()
|
| 497 |
+
public_law: Optional[str] = None
|
| 498 |
+
notes: Optional[str] = None
|
| 499 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 500 |
+
|
| 501 |
+
def __post_init__(self) -> None:
|
| 502 |
+
object.__setattr__(self, "kind", ExclusionKind.coerce(self.kind))
|
| 503 |
+
object.__setattr__(self, "citation", _require_non_empty_str(self.citation, "citation"))
|
| 504 |
+
object.__setattr__(self, "reason", _require_non_empty_str(self.reason, "reason"))
|
| 505 |
+
sections: list[str] = []
|
| 506 |
+
for item in self.affects_sections or ():
|
| 507 |
+
sections.append(normalize_section_token(item))
|
| 508 |
+
object.__setattr__(self, "affects_sections", tuple(sections))
|
| 509 |
+
if self.public_law is not None:
|
| 510 |
+
object.__setattr__(
|
| 511 |
+
self, "public_law", _require_non_empty_str(self.public_law, "public_law")
|
| 512 |
+
)
|
| 513 |
+
if self.notes is not None:
|
| 514 |
+
object.__setattr__(self, "notes", _require_non_empty_str(self.notes, "notes"))
|
| 515 |
+
if not isinstance(self.metadata, Mapping):
|
| 516 |
+
raise UscodeReleaseError("metadata must be a mapping")
|
| 517 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 518 |
+
|
| 519 |
+
def to_dict(self) -> dict[str, Any]:
|
| 520 |
+
return {
|
| 521 |
+
"affects_sections": list(self.affects_sections),
|
| 522 |
+
"citation": self.citation,
|
| 523 |
+
"kind": self.kind.value,
|
| 524 |
+
"metadata": _deep_sorted(self.metadata),
|
| 525 |
+
"notes": self.notes,
|
| 526 |
+
"public_law": self.public_law,
|
| 527 |
+
"reason": self.reason,
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
@classmethod
|
| 531 |
+
def from_dict(cls, value: JsonMapping) -> "ReleaseExclusion":
|
| 532 |
+
if not isinstance(value, Mapping):
|
| 533 |
+
raise UscodeReleaseError("exclusion must be a mapping")
|
| 534 |
+
affects = value.get("affects_sections") or ()
|
| 535 |
+
return cls(
|
| 536 |
+
kind=ExclusionKind.coerce(value.get("kind", ExclusionKind.OTHER)),
|
| 537 |
+
citation=str(value.get("citation") or value.get("public_law") or "unspecified"),
|
| 538 |
+
reason=str(value.get("reason") or "classification gap"),
|
| 539 |
+
affects_sections=tuple(affects),
|
| 540 |
+
public_law=value.get("public_law"),
|
| 541 |
+
notes=value.get("notes"),
|
| 542 |
+
metadata=value.get("metadata") or {},
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
@dataclass(frozen=True, slots=True)
|
| 547 |
+
class FormatArtifact:
|
| 548 |
+
"""One packaging format of a section or title package."""
|
| 549 |
+
|
| 550 |
+
format: SourceFormat
|
| 551 |
+
media_type: str
|
| 552 |
+
artifact_sha256: str
|
| 553 |
+
source_url: str
|
| 554 |
+
byte_size: Optional[int] = None
|
| 555 |
+
upstream_package_id: Optional[str] = None
|
| 556 |
+
role: IdentityRole = IdentityRole.OFFICIAL_ARTIFACT
|
| 557 |
+
|
| 558 |
+
def __post_init__(self) -> None:
|
| 559 |
+
object.__setattr__(self, "format", SourceFormat.coerce(self.format))
|
| 560 |
+
object.__setattr__(
|
| 561 |
+
self, "media_type", _require_non_empty_str(self.media_type, "media_type")
|
| 562 |
+
)
|
| 563 |
+
object.__setattr__(
|
| 564 |
+
self, "artifact_sha256", _require_sha256(self.artifact_sha256, "artifact_sha256")
|
| 565 |
+
)
|
| 566 |
+
object.__setattr__(
|
| 567 |
+
self, "source_url", _require_non_empty_str(self.source_url, "source_url")
|
| 568 |
+
)
|
| 569 |
+
if self.byte_size is not None and (not isinstance(self.byte_size, int) or self.byte_size < 0):
|
| 570 |
+
raise UscodeReleaseError("byte_size must be a non-negative int")
|
| 571 |
+
if self.upstream_package_id is not None:
|
| 572 |
+
pkg = _require_non_empty_str(self.upstream_package_id, "upstream_package_id")
|
| 573 |
+
reject_hard_coded_latest(pkg, field_name="upstream_package_id")
|
| 574 |
+
object.__setattr__(self, "upstream_package_id", pkg)
|
| 575 |
+
if not isinstance(self.role, IdentityRole):
|
| 576 |
+
object.__setattr__(self, "role", IdentityRole(str(self.role)))
|
| 577 |
+
|
| 578 |
+
def to_artifact_identity(self, *, provider: str, source_id: str) -> ArtifactIdentity:
|
| 579 |
+
return ArtifactIdentity(
|
| 580 |
+
provider=provider,
|
| 581 |
+
source_id=source_id,
|
| 582 |
+
artifact_sha256=self.artifact_sha256,
|
| 583 |
+
source_url=self.source_url,
|
| 584 |
+
media_type=self.media_type,
|
| 585 |
+
byte_size=self.byte_size,
|
| 586 |
+
upstream_package_id=self.upstream_package_id,
|
| 587 |
+
role=self.role,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
def to_dict(self) -> dict[str, Any]:
|
| 591 |
+
return {
|
| 592 |
+
"artifact_sha256": self.artifact_sha256,
|
| 593 |
+
"byte_size": self.byte_size,
|
| 594 |
+
"format": self.format.value,
|
| 595 |
+
"media_type": self.media_type,
|
| 596 |
+
"role": self.role.value,
|
| 597 |
+
"source_url": self.source_url,
|
| 598 |
+
"upstream_package_id": self.upstream_package_id,
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
@classmethod
|
| 602 |
+
def from_dict(cls, value: JsonMapping) -> "FormatArtifact":
|
| 603 |
+
if not isinstance(value, Mapping):
|
| 604 |
+
raise UscodeReleaseError("format artifact must be a mapping")
|
| 605 |
+
role_raw = value.get("role", IdentityRole.OFFICIAL_ARTIFACT.value)
|
| 606 |
+
role = role_raw if isinstance(role_raw, IdentityRole) else IdentityRole(str(role_raw))
|
| 607 |
+
return cls(
|
| 608 |
+
format=SourceFormat.coerce(value.get("format") or value.get("source_format")),
|
| 609 |
+
media_type=str(value.get("media_type") or "application/octet-stream"),
|
| 610 |
+
artifact_sha256=str(value.get("artifact_sha256") or value.get("sha256")),
|
| 611 |
+
source_url=str(value.get("source_url") or value.get("url")),
|
| 612 |
+
byte_size=value.get("byte_size"),
|
| 613 |
+
upstream_package_id=value.get("upstream_package_id"),
|
| 614 |
+
role=role,
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
@dataclass(frozen=True, slots=True)
|
| 619 |
+
class UscodeSectionRecord:
|
| 620 |
+
"""One Title section resolved against a concrete release point."""
|
| 621 |
+
|
| 622 |
+
title: str
|
| 623 |
+
section: str
|
| 624 |
+
stable_id: str
|
| 625 |
+
heading: Optional[str] = None
|
| 626 |
+
citation: Optional[str] = None
|
| 627 |
+
text_excerpt: Optional[str] = None
|
| 628 |
+
formats: Mapping[str, FormatArtifact] = field(default_factory=dict)
|
| 629 |
+
status: ResolutionStatus = ResolutionStatus.RESOLVED
|
| 630 |
+
release_point: Optional[str] = None
|
| 631 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 632 |
+
|
| 633 |
+
def __post_init__(self) -> None:
|
| 634 |
+
title_n = normalize_title(self.title)
|
| 635 |
+
section_n = normalize_section_token(self.section)
|
| 636 |
+
object.__setattr__(self, "title", title_n)
|
| 637 |
+
object.__setattr__(self, "section", section_n)
|
| 638 |
+
stable = self.stable_id or stable_section_identity(title=title_n, section=section_n)
|
| 639 |
+
# Guard: supplied stable_id must match format-independent identity.
|
| 640 |
+
expected = stable_section_identity(title=title_n, section=section_n)
|
| 641 |
+
if stable != expected:
|
| 642 |
+
# Re-normalize rather than fail on minor presentation differences.
|
| 643 |
+
stable = expected
|
| 644 |
+
object.__setattr__(self, "stable_id", stable)
|
| 645 |
+
if self.heading is not None:
|
| 646 |
+
object.__setattr__(self, "heading", _require_non_empty_str(self.heading, "heading"))
|
| 647 |
+
if self.citation is not None:
|
| 648 |
+
object.__setattr__(
|
| 649 |
+
self, "citation", _require_non_empty_str(self.citation, "citation")
|
| 650 |
+
)
|
| 651 |
+
else:
|
| 652 |
+
object.__setattr__(self, "citation", f"{title_n} U.S.C. § {section_n}")
|
| 653 |
+
if self.text_excerpt is not None:
|
| 654 |
+
object.__setattr__(self, "text_excerpt", str(self.text_excerpt))
|
| 655 |
+
fmt_map: dict[str, FormatArtifact] = {}
|
| 656 |
+
for key, art in (self.formats or {}).items():
|
| 657 |
+
if isinstance(art, FormatArtifact):
|
| 658 |
+
fmt_map[SourceFormat.coerce(key).value] = art
|
| 659 |
+
elif isinstance(art, Mapping):
|
| 660 |
+
payload = dict(art)
|
| 661 |
+
payload.setdefault("format", key)
|
| 662 |
+
fmt_map[SourceFormat.coerce(key).value] = FormatArtifact.from_dict(payload)
|
| 663 |
+
else:
|
| 664 |
+
raise UscodeReleaseError(f"invalid format artifact for {key!r}")
|
| 665 |
+
object.__setattr__(self, "formats", fmt_map)
|
| 666 |
+
if not isinstance(self.status, ResolutionStatus):
|
| 667 |
+
object.__setattr__(self, "status", ResolutionStatus(str(self.status)))
|
| 668 |
+
if self.release_point is not None:
|
| 669 |
+
object.__setattr__(
|
| 670 |
+
self,
|
| 671 |
+
"release_point",
|
| 672 |
+
_require_non_empty_str(self.release_point, "release_point"),
|
| 673 |
+
)
|
| 674 |
+
reject_hard_coded_latest(self.release_point, field_name="release_point")
|
| 675 |
+
if not isinstance(self.metadata, Mapping):
|
| 676 |
+
raise UscodeReleaseError("metadata must be a mapping")
|
| 677 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 678 |
+
|
| 679 |
+
def identity_for_all_formats(self) -> str:
|
| 680 |
+
"""Stable identity shared by every packaging format of this section."""
|
| 681 |
+
|
| 682 |
+
return self.stable_id
|
| 683 |
+
|
| 684 |
+
def to_dict(self) -> dict[str, Any]:
|
| 685 |
+
return {
|
| 686 |
+
"citation": self.citation,
|
| 687 |
+
"formats": {k: v.to_dict() for k, v in sorted(self.formats.items())},
|
| 688 |
+
"heading": self.heading,
|
| 689 |
+
"metadata": _deep_sorted(self.metadata),
|
| 690 |
+
"release_point": self.release_point,
|
| 691 |
+
"section": self.section,
|
| 692 |
+
"stable_id": self.stable_id,
|
| 693 |
+
"status": self.status.value,
|
| 694 |
+
"text_excerpt": self.text_excerpt,
|
| 695 |
+
"title": self.title,
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
@classmethod
|
| 699 |
+
def from_dict(cls, value: JsonMapping) -> "UscodeSectionRecord":
|
| 700 |
+
if not isinstance(value, Mapping):
|
| 701 |
+
raise UscodeReleaseError("section record must be a mapping")
|
| 702 |
+
title = value.get("title", DEFAULT_TITLE)
|
| 703 |
+
section = value.get("section")
|
| 704 |
+
if section is None:
|
| 705 |
+
raise UscodeReleaseError("section is required")
|
| 706 |
+
status_raw = value.get("status", ResolutionStatus.RESOLVED.value)
|
| 707 |
+
status = (
|
| 708 |
+
status_raw
|
| 709 |
+
if isinstance(status_raw, ResolutionStatus)
|
| 710 |
+
else ResolutionStatus(str(status_raw))
|
| 711 |
+
)
|
| 712 |
+
return cls(
|
| 713 |
+
title=str(title),
|
| 714 |
+
section=str(section),
|
| 715 |
+
stable_id=str(
|
| 716 |
+
value.get("stable_id")
|
| 717 |
+
or stable_section_identity(title=title, section=section)
|
| 718 |
+
),
|
| 719 |
+
heading=value.get("heading"),
|
| 720 |
+
citation=value.get("citation"),
|
| 721 |
+
text_excerpt=value.get("text_excerpt"),
|
| 722 |
+
formats=value.get("formats") or {},
|
| 723 |
+
status=status,
|
| 724 |
+
release_point=value.get("release_point"),
|
| 725 |
+
metadata=value.get("metadata") or {},
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
@dataclass(frozen=True, slots=True)
|
| 730 |
+
class UscodeReleaseAcquisition:
|
| 731 |
+
"""Result of acquiring one Title 35 release point and its sections."""
|
| 732 |
+
|
| 733 |
+
status: ResolutionStatus
|
| 734 |
+
release_point: Optional[ReleasePoint]
|
| 735 |
+
exclusions: tuple[ReleaseExclusion, ...]
|
| 736 |
+
sections: Mapping[str, UscodeSectionRecord]
|
| 737 |
+
authority_source: Optional[AuthoritySourceRecord] = None
|
| 738 |
+
receipt: Optional[SourceReceipt] = None
|
| 739 |
+
title: str = DEFAULT_TITLE
|
| 740 |
+
notes: Optional[str] = None
|
| 741 |
+
unknown_reason: Optional[str] = None
|
| 742 |
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
| 743 |
+
|
| 744 |
+
def __post_init__(self) -> None:
|
| 745 |
+
if not isinstance(self.status, ResolutionStatus):
|
| 746 |
+
object.__setattr__(self, "status", ResolutionStatus(str(self.status)))
|
| 747 |
+
object.__setattr__(self, "title", normalize_title(self.title))
|
| 748 |
+
object.__setattr__(self, "exclusions", tuple(self.exclusions or ()))
|
| 749 |
+
sec_map: dict[str, UscodeSectionRecord] = {}
|
| 750 |
+
for key, sec in (self.sections or {}).items():
|
| 751 |
+
if isinstance(sec, UscodeSectionRecord):
|
| 752 |
+
record = sec
|
| 753 |
+
elif isinstance(sec, Mapping):
|
| 754 |
+
record = UscodeSectionRecord.from_dict(sec)
|
| 755 |
+
else:
|
| 756 |
+
raise UscodeReleaseError("sections values must be mappings or records")
|
| 757 |
+
sec_map[record.section] = record
|
| 758 |
+
object.__setattr__(self, "sections", sec_map)
|
| 759 |
+
if not isinstance(self.metadata, Mapping):
|
| 760 |
+
raise UscodeReleaseError("metadata must be a mapping")
|
| 761 |
+
object.__setattr__(self, "metadata", dict(self.metadata))
|
| 762 |
+
|
| 763 |
+
@property
|
| 764 |
+
def is_unknown(self) -> bool:
|
| 765 |
+
return self.status is ResolutionStatus.UNKNOWN
|
| 766 |
+
|
| 767 |
+
def get_section(self, section: Any) -> UscodeSectionRecord:
|
| 768 |
+
token = normalize_section_token(section)
|
| 769 |
+
try:
|
| 770 |
+
return self.sections[token]
|
| 771 |
+
except KeyError as exc:
|
| 772 |
+
raise SectionNotFoundError(
|
| 773 |
+
f"section {token!r} not present in acquisition "
|
| 774 |
+
f"(release={None if self.release_point is None else self.release_point.release_point})"
|
| 775 |
+
) from exc
|
| 776 |
+
|
| 777 |
+
def resolve_section(self, section: Any) -> UscodeSectionRecord:
|
| 778 |
+
"""Resolve a section or return an unknown-status record when release is missing."""
|
| 779 |
+
|
| 780 |
+
if self.status is ResolutionStatus.UNKNOWN or self.release_point is None:
|
| 781 |
+
token = normalize_section_token(section)
|
| 782 |
+
return UscodeSectionRecord(
|
| 783 |
+
title=self.title,
|
| 784 |
+
section=token,
|
| 785 |
+
stable_id=stable_section_identity(title=self.title, section=token),
|
| 786 |
+
status=ResolutionStatus.UNKNOWN,
|
| 787 |
+
release_point=None,
|
| 788 |
+
metadata={"unknown_reason": self.unknown_reason or "missing release point"},
|
| 789 |
+
)
|
| 790 |
+
return self.get_section(section)
|
| 791 |
+
|
| 792 |
+
def recorded_exclusions(self) -> tuple[ReleaseExclusion, ...]:
|
| 793 |
+
return self.exclusions
|
| 794 |
+
|
| 795 |
+
def to_dict(self) -> dict[str, Any]:
|
| 796 |
+
return {
|
| 797 |
+
"authority_source": (
|
| 798 |
+
None if self.authority_source is None else self.authority_source.to_dict()
|
| 799 |
+
),
|
| 800 |
+
"exclusions": [e.to_dict() for e in self.exclusions],
|
| 801 |
+
"metadata": _deep_sorted(self.metadata),
|
| 802 |
+
"notes": self.notes,
|
| 803 |
+
"receipt": None if self.receipt is None else self.receipt.to_dict(),
|
| 804 |
+
"release_point": None if self.release_point is None else self.release_point.to_dict(),
|
| 805 |
+
"schema_version": SCHEMA_VERSION,
|
| 806 |
+
"sections": {
|
| 807 |
+
k: v.to_dict() for k, v in sorted(self.sections.items(), key=lambda kv: kv[0])
|
| 808 |
+
},
|
| 809 |
+
"status": self.status.value,
|
| 810 |
+
"title": self.title,
|
| 811 |
+
"unknown_reason": self.unknown_reason,
|
| 812 |
+
}
|
| 813 |
+
|
| 814 |
+
def to_canonical_json(self) -> str:
|
| 815 |
+
return canonical_json_dumps(self.to_dict())
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def default_fixture_dir() -> Path:
|
| 819 |
+
"""Return the repository Title 35 fixture directory when present."""
|
| 820 |
+
|
| 821 |
+
# processors/legal_scrapers/federal_scrapers/thisfile -> repo root is 5 parents up
|
| 822 |
+
here = Path(__file__).resolve()
|
| 823 |
+
candidates = [
|
| 824 |
+
here.parents[4] / "tests" / "fixtures" / "legal_data" / "patent_authorities" / "uscode",
|
| 825 |
+
Path.cwd() / "tests" / "fixtures" / "legal_data" / "patent_authorities" / "uscode",
|
| 826 |
+
]
|
| 827 |
+
for path in candidates:
|
| 828 |
+
if path.is_dir():
|
| 829 |
+
return path
|
| 830 |
+
return candidates[0]
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def load_json_fixture(path: PathLike) -> dict[str, Any]:
|
| 834 |
+
p = Path(path)
|
| 835 |
+
with p.open("r", encoding="utf-8") as handle:
|
| 836 |
+
payload = json.load(handle)
|
| 837 |
+
if not isinstance(payload, Mapping):
|
| 838 |
+
raise FixtureSchemaError(f"fixture root must be a mapping: {p}")
|
| 839 |
+
return dict(payload)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def _media_type_for_format(fmt: SourceFormat) -> str:
|
| 843 |
+
return {
|
| 844 |
+
SourceFormat.USLM: "application/uslm+xml",
|
| 845 |
+
SourceFormat.XML: "application/xml",
|
| 846 |
+
SourceFormat.HTML: "text/html",
|
| 847 |
+
SourceFormat.HTM: "text/html",
|
| 848 |
+
SourceFormat.PDF: "application/pdf",
|
| 849 |
+
SourceFormat.ZIP: "application/zip",
|
| 850 |
+
}[fmt]
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def _build_format_map(
|
| 854 |
+
raw_formats: Mapping[str, Any] | None,
|
| 855 |
+
*,
|
| 856 |
+
release: ReleasePoint,
|
| 857 |
+
section: str,
|
| 858 |
+
) -> dict[str, FormatArtifact]:
|
| 859 |
+
out: dict[str, FormatArtifact] = {}
|
| 860 |
+
if not raw_formats:
|
| 861 |
+
return out
|
| 862 |
+
for key, item in raw_formats.items():
|
| 863 |
+
fmt = SourceFormat.coerce(key)
|
| 864 |
+
if isinstance(item, FormatArtifact):
|
| 865 |
+
out[fmt.value] = item
|
| 866 |
+
continue
|
| 867 |
+
if not isinstance(item, Mapping):
|
| 868 |
+
raise FixtureSchemaError(f"formats[{key!r}] must be a mapping")
|
| 869 |
+
payload = dict(item)
|
| 870 |
+
payload.setdefault("format", fmt.value)
|
| 871 |
+
payload.setdefault("media_type", _media_type_for_format(fmt))
|
| 872 |
+
if "artifact_sha256" not in payload and "sha256" not in payload:
|
| 873 |
+
# Deterministic synthetic digest for compact recipes that omit bytes.
|
| 874 |
+
seed = f"{release.release_point}|{release.title}|{section}|{fmt.value}"
|
| 875 |
+
payload["artifact_sha256"] = content_sha256(seed)
|
| 876 |
+
if "source_url" not in payload and "url" not in payload:
|
| 877 |
+
if release.congress and release.release:
|
| 878 |
+
payload["source_url"] = ushouse_releasepoint_zip_url(
|
| 879 |
+
congress=release.congress,
|
| 880 |
+
release=release.release,
|
| 881 |
+
title=release.title,
|
| 882 |
+
format_kind=fmt,
|
| 883 |
+
)
|
| 884 |
+
elif release.source_url:
|
| 885 |
+
payload["source_url"] = release.source_url
|
| 886 |
+
else:
|
| 887 |
+
payload["source_url"] = (
|
| 888 |
+
f"{USHOUSE_DOWNLOAD_PAGE}#title-{release.title}-section-{section}-{fmt.value}"
|
| 889 |
+
)
|
| 890 |
+
if "upstream_package_id" not in payload:
|
| 891 |
+
payload["upstream_package_id"] = release.govinfo_package_id or release.release_point
|
| 892 |
+
out[fmt.value] = FormatArtifact.from_dict(payload)
|
| 893 |
+
return out
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
def _build_authority_source(
|
| 897 |
+
release: ReleasePoint,
|
| 898 |
+
*,
|
| 899 |
+
formats: Mapping[str, FormatArtifact] | None = None,
|
| 900 |
+
receipt: SourceReceipt | None = None,
|
| 901 |
+
verification_state: VerificationState = VerificationState.UNVERIFIED,
|
| 902 |
+
) -> AuthoritySourceRecord:
|
| 903 |
+
official: Optional[ArtifactIdentity] = None
|
| 904 |
+
derived: Optional[ArtifactIdentity] = None
|
| 905 |
+
fmt_map = dict(formats or {})
|
| 906 |
+
|
| 907 |
+
preferred_official = (
|
| 908 |
+
SourceFormat.USLM.value,
|
| 909 |
+
SourceFormat.XML.value,
|
| 910 |
+
SourceFormat.PDF.value,
|
| 911 |
+
SourceFormat.HTML.value,
|
| 912 |
+
SourceFormat.HTM.value,
|
| 913 |
+
SourceFormat.ZIP.value,
|
| 914 |
+
)
|
| 915 |
+
for key in preferred_official:
|
| 916 |
+
if key in fmt_map:
|
| 917 |
+
art = fmt_map[key]
|
| 918 |
+
official = art.to_artifact_identity(
|
| 919 |
+
provider=release.provider,
|
| 920 |
+
source_id=f"uscode-{release.title}:{release.release_point}:{key}",
|
| 921 |
+
)
|
| 922 |
+
break
|
| 923 |
+
|
| 924 |
+
if official is None and release.content_sha256 and release.source_url:
|
| 925 |
+
official = ArtifactIdentity(
|
| 926 |
+
provider=release.provider,
|
| 927 |
+
source_id=f"uscode-{release.title}:{release.release_point}",
|
| 928 |
+
artifact_sha256=release.content_sha256,
|
| 929 |
+
source_url=release.source_url,
|
| 930 |
+
role=IdentityRole.OFFICIAL_ARTIFACT,
|
| 931 |
+
upstream_package_id=release.govinfo_package_id or release.release_point,
|
| 932 |
+
)
|
| 933 |
+
|
| 934 |
+
# Prefer HTML as derived presentation when a richer official format exists.
|
| 935 |
+
if official is not None:
|
| 936 |
+
for key in (SourceFormat.HTML.value, SourceFormat.HTM.value):
|
| 937 |
+
if key in fmt_map and fmt_map[key].artifact_sha256 != official.artifact_sha256:
|
| 938 |
+
derived = fmt_map[key].to_artifact_identity(
|
| 939 |
+
provider=release.provider,
|
| 940 |
+
source_id=f"uscode-{release.title}:{release.release_point}:{key}:presentation",
|
| 941 |
+
)
|
| 942 |
+
derived = ArtifactIdentity(
|
| 943 |
+
provider=derived.provider,
|
| 944 |
+
source_id=derived.source_id,
|
| 945 |
+
artifact_sha256=derived.artifact_sha256,
|
| 946 |
+
source_url=derived.source_url,
|
| 947 |
+
media_type=derived.media_type,
|
| 948 |
+
byte_size=derived.byte_size,
|
| 949 |
+
upstream_package_id=derived.upstream_package_id,
|
| 950 |
+
role=IdentityRole.DERIVED_PRESENTATION,
|
| 951 |
+
)
|
| 952 |
+
break
|
| 953 |
+
|
| 954 |
+
edition = release.edition or release.release_point
|
| 955 |
+
return AuthoritySourceRecord(
|
| 956 |
+
source_key=f"uscode-{release.title}-{release.release_point.replace('/', '-')}",
|
| 957 |
+
authority_tier=AuthorityTier.OFFICIAL_BASE,
|
| 958 |
+
collection=COLLECTION_USCODE,
|
| 959 |
+
jurisdiction=DEFAULT_JURISDICTION,
|
| 960 |
+
title=release.title,
|
| 961 |
+
citation=f"{release.title} U.S.C.",
|
| 962 |
+
edition=edition,
|
| 963 |
+
version=release.release_point,
|
| 964 |
+
release_point=release.release_point,
|
| 965 |
+
official_artifact=official,
|
| 966 |
+
derived_presentation=derived,
|
| 967 |
+
receipt=receipt,
|
| 968 |
+
verification_state=verification_state,
|
| 969 |
+
notes="House OLRC / GovInfo U.S. Code release-point acquisition",
|
| 970 |
+
metadata={
|
| 971 |
+
"congress": release.congress,
|
| 972 |
+
"release": release.release,
|
| 973 |
+
"govinfo_package_id": release.govinfo_package_id,
|
| 974 |
+
"year": release.year,
|
| 975 |
+
"processor_schema": SCHEMA_VERSION,
|
| 976 |
+
"authority_schema": AUTHORITY_SCHEMA_VERSION,
|
| 977 |
+
},
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def _build_receipt(release: ReleasePoint) -> Optional[SourceReceipt]:
|
| 982 |
+
if not release.source_url and not release.content_sha256:
|
| 983 |
+
return None
|
| 984 |
+
endpoint = release.source_url or USHOUSE_DOWNLOAD_PAGE
|
| 985 |
+
retrieved = release.retrieved_at or datetime(1970, 1, 1, tzinfo=timezone.utc)
|
| 986 |
+
return SourceReceipt(
|
| 987 |
+
endpoint=endpoint,
|
| 988 |
+
retrieved_at=retrieved,
|
| 989 |
+
response_status=200,
|
| 990 |
+
sanitized_request={"method": "GET", "path": endpoint},
|
| 991 |
+
upstream_id=release.govinfo_package_id or release.release_point,
|
| 992 |
+
content_sha256=release.content_sha256,
|
| 993 |
+
retry_count=0,
|
| 994 |
+
cache_hit=False,
|
| 995 |
+
media_type="application/zip",
|
| 996 |
+
metadata={"provider": release.provider, "title": release.title},
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
class UscodeReleaseProcessor:
|
| 1001 |
+
"""Acquire Title 35 U.S. Code content at an exact release point.
|
| 1002 |
+
|
| 1003 |
+
Primary path is fixture replay (recorded OLRC/GovInfo metadata). Live
|
| 1004 |
+
network discovery is deliberately not performed by default so tests and
|
| 1005 |
+
offline operators remain deterministic.
|
| 1006 |
+
"""
|
| 1007 |
+
|
| 1008 |
+
def __init__(
|
| 1009 |
+
self,
|
| 1010 |
+
*,
|
| 1011 |
+
fixture_dir: PathLike | None = None,
|
| 1012 |
+
registry: AuthoritySourceRegistry | None = None,
|
| 1013 |
+
retry_cache_policy: RetryCachePolicy | None = None,
|
| 1014 |
+
default_title: str = DEFAULT_TITLE,
|
| 1015 |
+
) -> None:
|
| 1016 |
+
self.fixture_dir = Path(fixture_dir) if fixture_dir else default_fixture_dir()
|
| 1017 |
+
self.registry = registry if registry is not None else AuthoritySourceRegistry(
|
| 1018 |
+
default_retry_cache_policy=retry_cache_policy
|
| 1019 |
+
)
|
| 1020 |
+
self.default_title = normalize_title(default_title)
|
| 1021 |
+
self._acquisitions: dict[str, UscodeReleaseAcquisition] = {}
|
| 1022 |
+
|
| 1023 |
+
# ------------------------------------------------------------------
|
| 1024 |
+
# Identity helpers (format-independent)
|
| 1025 |
+
# ------------------------------------------------------------------
|
| 1026 |
+
|
| 1027 |
+
def stable_section_identity(self, section: Any, *, title: Any | None = None) -> str:
|
| 1028 |
+
return stable_section_identity(
|
| 1029 |
+
title=self.default_title if title is None else title,
|
| 1030 |
+
section=section,
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
def identities_equal_across_formats(
|
| 1034 |
+
self,
|
| 1035 |
+
*,
|
| 1036 |
+
title: Any,
|
| 1037 |
+
section: Any,
|
| 1038 |
+
formats: Sequence[SourceFormat | str],
|
| 1039 |
+
) -> bool:
|
| 1040 |
+
"""Return True when every *format* maps to the same stable identity."""
|
| 1041 |
+
|
| 1042 |
+
base = stable_section_identity(title=title, section=section)
|
| 1043 |
+
for _fmt in formats:
|
| 1044 |
+
# Format is intentionally ignored for identity.
|
| 1045 |
+
if stable_section_identity(title=title, section=section) != base:
|
| 1046 |
+
return False
|
| 1047 |
+
return len(list(formats)) > 0
|
| 1048 |
+
|
| 1049 |
+
# ------------------------------------------------------------------
|
| 1050 |
+
# Fixture acquisition
|
| 1051 |
+
# ------------------------------------------------------------------
|
| 1052 |
+
|
| 1053 |
+
def load_fixture_package(self, path: PathLike | None = None) -> dict[str, Any]:
|
| 1054 |
+
"""Load a compact Title 35 release fixture (recipe or full package)."""
|
| 1055 |
+
|
| 1056 |
+
target = Path(path) if path is not None else self._default_package_path()
|
| 1057 |
+
if target.is_dir():
|
| 1058 |
+
recipe = target / "title35_release_recipe.json"
|
| 1059 |
+
if recipe.is_file():
|
| 1060 |
+
target = recipe
|
| 1061 |
+
else:
|
| 1062 |
+
# Merge directory components when present.
|
| 1063 |
+
return self._load_fixture_directory(target)
|
| 1064 |
+
payload = load_json_fixture(target)
|
| 1065 |
+
schema = payload.get("schema_version")
|
| 1066 |
+
if schema and schema not in {FIXTURE_SCHEMA_VERSION, SCHEMA_VERSION}:
|
| 1067 |
+
# Accept forward-compatible minor variants that share the prefix.
|
| 1068 |
+
if not str(schema).startswith("uscode-release"):
|
| 1069 |
+
raise FixtureSchemaError(
|
| 1070 |
+
f"unsupported fixture schema_version {schema!r} in {target}"
|
| 1071 |
+
)
|
| 1072 |
+
return payload
|
| 1073 |
+
|
| 1074 |
+
def _default_package_path(self) -> Path:
|
| 1075 |
+
recipe = self.fixture_dir / "title35_release_recipe.json"
|
| 1076 |
+
if recipe.is_file():
|
| 1077 |
+
return recipe
|
| 1078 |
+
return self.fixture_dir
|
| 1079 |
+
|
| 1080 |
+
def _load_fixture_directory(self, directory: Path) -> dict[str, Any]:
|
| 1081 |
+
release_path = directory / "release_point.json"
|
| 1082 |
+
if not release_path.is_file():
|
| 1083 |
+
raise FixtureSchemaError(
|
| 1084 |
+
f"fixture directory {directory} lacks title35_release_recipe.json "
|
| 1085 |
+
"or release_point.json"
|
| 1086 |
+
)
|
| 1087 |
+
payload: dict[str, Any] = {
|
| 1088 |
+
"schema_version": FIXTURE_SCHEMA_VERSION,
|
| 1089 |
+
"release": load_json_fixture(release_path),
|
| 1090 |
+
}
|
| 1091 |
+
exclusions_path = directory / "exclusions.json"
|
| 1092 |
+
if exclusions_path.is_file():
|
| 1093 |
+
raw = load_json_fixture(exclusions_path)
|
| 1094 |
+
payload["exclusions"] = raw.get("exclusions", raw if isinstance(raw, list) else [])
|
| 1095 |
+
sections_dir = directory / "sections"
|
| 1096 |
+
sections: list[Any] = []
|
| 1097 |
+
if sections_dir.is_dir():
|
| 1098 |
+
for path in sorted(sections_dir.glob("*.json")):
|
| 1099 |
+
sections.append(load_json_fixture(path))
|
| 1100 |
+
payload["sections"] = sections
|
| 1101 |
+
return payload
|
| 1102 |
+
|
| 1103 |
+
def acquire_from_fixture(
|
| 1104 |
+
self,
|
| 1105 |
+
path: PathLike | None = None,
|
| 1106 |
+
*,
|
| 1107 |
+
register: bool = True,
|
| 1108 |
+
) -> UscodeReleaseAcquisition:
|
| 1109 |
+
"""Acquire Title 35 content from a recorded fixture package.
|
| 1110 |
+
|
| 1111 |
+
Missing release identity yields :attr:`ResolutionStatus.UNKNOWN`.
|
| 1112 |
+
"""
|
| 1113 |
+
|
| 1114 |
+
payload = self.load_fixture_package(path)
|
| 1115 |
+
return self.acquire_from_payload(payload, register=register)
|
| 1116 |
+
|
| 1117 |
+
def acquire_from_payload(
|
| 1118 |
+
self,
|
| 1119 |
+
payload: JsonMapping,
|
| 1120 |
+
*,
|
| 1121 |
+
register: bool = True,
|
| 1122 |
+
) -> UscodeReleaseAcquisition:
|
| 1123 |
+
if not isinstance(payload, Mapping):
|
| 1124 |
+
raise FixtureSchemaError("payload must be a mapping")
|
| 1125 |
+
|
| 1126 |
+
release_raw = payload.get("release") or payload.get("release_point")
|
| 1127 |
+
title = normalize_title(payload.get("title") or self.default_title)
|
| 1128 |
+
|
| 1129 |
+
# Fail-closed: missing release data → unknown.
|
| 1130 |
+
if not release_raw:
|
| 1131 |
+
return UscodeReleaseAcquisition(
|
| 1132 |
+
status=ResolutionStatus.UNKNOWN,
|
| 1133 |
+
release_point=None,
|
| 1134 |
+
exclusions=(),
|
| 1135 |
+
sections={},
|
| 1136 |
+
title=title,
|
| 1137 |
+
unknown_reason="missing release data",
|
| 1138 |
+
notes="Exact release point unavailable; section authority is unknown.",
|
| 1139 |
+
metadata={"schema_version": payload.get("schema_version")},
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
if isinstance(release_raw, str):
|
| 1143 |
+
release_raw = {"release_point": release_raw, "provider": "ushouse", "title": title}
|
| 1144 |
+
|
| 1145 |
+
if not isinstance(release_raw, Mapping):
|
| 1146 |
+
raise FixtureSchemaError("release must be a mapping or release_point string")
|
| 1147 |
+
|
| 1148 |
+
# Explicit null/empty release_point field also yields unknown.
|
| 1149 |
+
rp_token = release_raw.get("release_point")
|
| 1150 |
+
has_congress_release = (
|
| 1151 |
+
release_raw.get("congress") is not None and release_raw.get("release") is not None
|
| 1152 |
+
)
|
| 1153 |
+
has_govinfo = bool(release_raw.get("govinfo_package_id"))
|
| 1154 |
+
if rp_token in (None, "") and not has_congress_release and not has_govinfo:
|
| 1155 |
+
return UscodeReleaseAcquisition(
|
| 1156 |
+
status=ResolutionStatus.UNKNOWN,
|
| 1157 |
+
release_point=None,
|
| 1158 |
+
exclusions=tuple(
|
| 1159 |
+
ReleaseExclusion.from_dict(e)
|
| 1160 |
+
for e in (payload.get("exclusions") or [])
|
| 1161 |
+
if isinstance(e, Mapping)
|
| 1162 |
+
),
|
| 1163 |
+
sections={},
|
| 1164 |
+
title=title,
|
| 1165 |
+
unknown_reason="missing release data",
|
| 1166 |
+
notes="Release mapping present but no concrete release identity.",
|
| 1167 |
+
metadata={"schema_version": payload.get("schema_version")},
|
| 1168 |
+
)
|
| 1169 |
+
|
| 1170 |
+
try:
|
| 1171 |
+
release = ReleasePoint.from_dict({**dict(release_raw), "title": release_raw.get("title", title)})
|
| 1172 |
+
except (MissingReleasePointError, HardCodedLatestEditionError, UscodeReleaseError) as exc:
|
| 1173 |
+
return UscodeReleaseAcquisition(
|
| 1174 |
+
status=ResolutionStatus.UNKNOWN,
|
| 1175 |
+
release_point=None,
|
| 1176 |
+
exclusions=(),
|
| 1177 |
+
sections={},
|
| 1178 |
+
title=title,
|
| 1179 |
+
unknown_reason=str(exc),
|
| 1180 |
+
notes="Failed to parse release point; treating authority as unknown.",
|
| 1181 |
+
metadata={"schema_version": payload.get("schema_version"), "error": str(exc)},
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
exclusions = tuple(
|
| 1185 |
+
ReleaseExclusion.from_dict(item)
|
| 1186 |
+
for item in (payload.get("exclusions") or [])
|
| 1187 |
+
if isinstance(item, Mapping)
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
package_formats = _build_format_map(
|
| 1191 |
+
payload.get("package_formats") or release_raw.get("formats"),
|
| 1192 |
+
release=release,
|
| 1193 |
+
section="*",
|
| 1194 |
+
)
|
| 1195 |
+
|
| 1196 |
+
sections: dict[str, UscodeSectionRecord] = {}
|
| 1197 |
+
for raw_sec in payload.get("sections") or []:
|
| 1198 |
+
if not isinstance(raw_sec, Mapping):
|
| 1199 |
+
continue
|
| 1200 |
+
sec_title = normalize_title(raw_sec.get("title", release.title))
|
| 1201 |
+
sec_num = normalize_section_token(raw_sec["section"])
|
| 1202 |
+
formats = _build_format_map(
|
| 1203 |
+
raw_sec.get("formats"),
|
| 1204 |
+
release=release,
|
| 1205 |
+
section=sec_num,
|
| 1206 |
+
)
|
| 1207 |
+
record = UscodeSectionRecord(
|
| 1208 |
+
title=sec_title,
|
| 1209 |
+
section=sec_num,
|
| 1210 |
+
stable_id=stable_section_identity(title=sec_title, section=sec_num),
|
| 1211 |
+
heading=raw_sec.get("heading"),
|
| 1212 |
+
citation=raw_sec.get("citation"),
|
| 1213 |
+
text_excerpt=raw_sec.get("text_excerpt"),
|
| 1214 |
+
formats=formats,
|
| 1215 |
+
status=ResolutionStatus.RESOLVED,
|
| 1216 |
+
release_point=release.release_point,
|
| 1217 |
+
metadata=raw_sec.get("metadata") or {},
|
| 1218 |
+
)
|
| 1219 |
+
sections[record.section] = record
|
| 1220 |
+
|
| 1221 |
+
receipt = _build_receipt(release)
|
| 1222 |
+
if receipt is None and release.source_url:
|
| 1223 |
+
receipt = SourceReceipt(
|
| 1224 |
+
endpoint=release.source_url,
|
| 1225 |
+
retrieved_at=release.retrieved_at or datetime.now(timezone.utc),
|
| 1226 |
+
response_status=200,
|
| 1227 |
+
sanitized_request={"method": "GET"},
|
| 1228 |
+
upstream_id=release.release_point,
|
| 1229 |
+
content_sha256=release.content_sha256,
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
authority = _build_authority_source(
|
| 1233 |
+
release,
|
| 1234 |
+
formats=package_formats,
|
| 1235 |
+
receipt=receipt,
|
| 1236 |
+
verification_state=VerificationState.UNVERIFIED,
|
| 1237 |
+
)
|
| 1238 |
+
|
| 1239 |
+
if register:
|
| 1240 |
+
self.registry.register(authority, overwrite=True)
|
| 1241 |
+
if receipt is not None and authority.receipt is None:
|
| 1242 |
+
self.registry.attach_receipt(authority.source_key, receipt)
|
| 1243 |
+
|
| 1244 |
+
acquisition = UscodeReleaseAcquisition(
|
| 1245 |
+
status=ResolutionStatus.RESOLVED,
|
| 1246 |
+
release_point=release,
|
| 1247 |
+
exclusions=exclusions,
|
| 1248 |
+
sections=sections,
|
| 1249 |
+
authority_source=authority,
|
| 1250 |
+
receipt=receipt,
|
| 1251 |
+
title=release.title,
|
| 1252 |
+
notes=payload.get("notes"),
|
| 1253 |
+
metadata={
|
| 1254 |
+
"schema_version": payload.get("schema_version") or FIXTURE_SCHEMA_VERSION,
|
| 1255 |
+
"fixture_id": payload.get("fixture_id"),
|
| 1256 |
+
"exclusion_count": len(exclusions),
|
| 1257 |
+
"section_count": len(sections),
|
| 1258 |
+
},
|
| 1259 |
+
)
|
| 1260 |
+
self._acquisitions[release.release_point] = acquisition
|
| 1261 |
+
return acquisition
|
| 1262 |
+
|
| 1263 |
+
# ------------------------------------------------------------------
|
| 1264 |
+
# Resolution API
|
| 1265 |
+
# ------------------------------------------------------------------
|
| 1266 |
+
|
| 1267 |
+
def acquire_unknown(self, *, reason: str = "missing release data", title: Any | None = None) -> UscodeReleaseAcquisition:
|
| 1268 |
+
"""Explicit unknown acquisition when no release can be established."""
|
| 1269 |
+
|
| 1270 |
+
return UscodeReleaseAcquisition(
|
| 1271 |
+
status=ResolutionStatus.UNKNOWN,
|
| 1272 |
+
release_point=None,
|
| 1273 |
+
exclusions=(),
|
| 1274 |
+
sections={},
|
| 1275 |
+
title=self.default_title if title is None else normalize_title(title),
|
| 1276 |
+
unknown_reason=reason,
|
| 1277 |
+
notes="Exact release point unavailable; section authority is unknown.",
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
def resolve_patent_sensitive_sections(
|
| 1281 |
+
self,
|
| 1282 |
+
acquisition: UscodeReleaseAcquisition | None = None,
|
| 1283 |
+
*,
|
| 1284 |
+
path: PathLike | None = None,
|
| 1285 |
+
) -> dict[str, UscodeSectionRecord]:
|
| 1286 |
+
"""Resolve 35 USC 122 and 181–188 against a release acquisition."""
|
| 1287 |
+
|
| 1288 |
+
acq = acquisition if acquisition is not None else self.acquire_from_fixture(path)
|
| 1289 |
+
resolved: dict[str, UscodeSectionRecord] = {}
|
| 1290 |
+
for section in PATENT_SENSITIVE_SECTIONS:
|
| 1291 |
+
resolved[section] = acq.resolve_section(section)
|
| 1292 |
+
return resolved
|
| 1293 |
+
|
| 1294 |
+
def get_acquisition(self, release_point: str) -> UscodeReleaseAcquisition:
|
| 1295 |
+
key, _, _ = parse_release_point_id(release_point)
|
| 1296 |
+
try:
|
| 1297 |
+
return self._acquisitions[key]
|
| 1298 |
+
except KeyError as exc:
|
| 1299 |
+
# Also allow raw key lookup (govinfo package ids).
|
| 1300 |
+
if release_point in self._acquisitions:
|
| 1301 |
+
return self._acquisitions[release_point]
|
| 1302 |
+
raise UscodeReleaseError(f"no acquisition for release_point {release_point!r}") from exc
|
| 1303 |
+
|
| 1304 |
+
def list_exclusions(
|
| 1305 |
+
self, acquisition: UscodeReleaseAcquisition | None = None
|
| 1306 |
+
) -> tuple[ReleaseExclusion, ...]:
|
| 1307 |
+
if acquisition is None:
|
| 1308 |
+
if not self._acquisitions:
|
| 1309 |
+
return ()
|
| 1310 |
+
# Most recent insertion order is fine; values() is insertion-ordered.
|
| 1311 |
+
acquisition = next(reversed(list(self._acquisitions.values())))
|
| 1312 |
+
return acquisition.recorded_exclusions()
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
def build_title35_fixture_recipe(
|
| 1316 |
+
*,
|
| 1317 |
+
congress: int = 118,
|
| 1318 |
+
release: str = "45",
|
| 1319 |
+
fixture_id: str = "title35-uspl-118-45",
|
| 1320 |
+
) -> dict[str, Any]:
|
| 1321 |
+
"""Build a compact deterministic Title 35 fixture recipe for tests/tools.
|
| 1322 |
+
|
| 1323 |
+
Prefer this generator over bulk golden dumps that re-emit full envelopes.
|
| 1324 |
+
"""
|
| 1325 |
+
|
| 1326 |
+
canonical, congress_s, release_s = parse_release_point_id(f"{congress}/{release}")
|
| 1327 |
+
content_seed = f"ushouse|{canonical}|title-35|package"
|
| 1328 |
+
package_sha = content_sha256(content_seed)
|
| 1329 |
+
source_url = ushouse_releasepoint_zip_url(
|
| 1330 |
+
congress=congress_s, release=release_s, title="35", format_kind=SourceFormat.USLM
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
headings = {
|
| 1334 |
+
"122": "Confidential status of applications; publication of patent applications",
|
| 1335 |
+
"181": "Secrecy of certain inventions and withholding of patent",
|
| 1336 |
+
"182": "Abandonment of invention for unauthorized disclosure",
|
| 1337 |
+
"183": "Right to compensation",
|
| 1338 |
+
"184": "Filing of application in foreign country",
|
| 1339 |
+
"185": "Patent barred for filing without license",
|
| 1340 |
+
"186": "Penalty",
|
| 1341 |
+
"187": "Nonapplicability to certain persons",
|
| 1342 |
+
"188": "Rules and regulations, delegation of power",
|
| 1343 |
+
}
|
| 1344 |
+
excerpts = {
|
| 1345 |
+
"122": (
|
| 1346 |
+
"(a) Except as provided in subsection (b), applications for patents "
|
| 1347 |
+
"shall be kept in confidence by the Patent and Trademark Office..."
|
| 1348 |
+
),
|
| 1349 |
+
"181": (
|
| 1350 |
+
"Whenever publication or disclosure by the publication of an "
|
| 1351 |
+
"application or by the grant of a patent..."
|
| 1352 |
+
),
|
| 1353 |
+
}
|
| 1354 |
+
|
| 1355 |
+
sections: list[dict[str, Any]] = []
|
| 1356 |
+
for sec in PATENT_SENSITIVE_SECTIONS:
|
| 1357 |
+
formats = {}
|
| 1358 |
+
for fmt in (SourceFormat.USLM, SourceFormat.HTML, SourceFormat.PDF):
|
| 1359 |
+
seed = f"{canonical}|35|{sec}|{fmt.value}"
|
| 1360 |
+
formats[fmt.value] = {
|
| 1361 |
+
"format": fmt.value,
|
| 1362 |
+
"media_type": _media_type_for_format(fmt),
|
| 1363 |
+
"artifact_sha256": content_sha256(seed),
|
| 1364 |
+
"source_url": ushouse_releasepoint_zip_url(
|
| 1365 |
+
congress=congress_s,
|
| 1366 |
+
release=release_s,
|
| 1367 |
+
title="35",
|
| 1368 |
+
format_kind=fmt,
|
| 1369 |
+
),
|
| 1370 |
+
"byte_size": 1000 + int(sec) + (10 if fmt is SourceFormat.PDF else 0),
|
| 1371 |
+
"upstream_package_id": canonical,
|
| 1372 |
+
}
|
| 1373 |
+
sections.append(
|
| 1374 |
+
{
|
| 1375 |
+
"title": "35",
|
| 1376 |
+
"section": sec,
|
| 1377 |
+
"heading": headings.get(sec, f"35 U.S.C. § {sec}"),
|
| 1378 |
+
"citation": f"35 U.S.C. § {sec}",
|
| 1379 |
+
"text_excerpt": excerpts.get(sec, f"[excerpt 35 U.S.C. § {sec}]"),
|
| 1380 |
+
"formats": formats,
|
| 1381 |
+
}
|
| 1382 |
+
)
|
| 1383 |
+
|
| 1384 |
+
return {
|
| 1385 |
+
"schema_version": FIXTURE_SCHEMA_VERSION,
|
| 1386 |
+
"fixture_id": fixture_id,
|
| 1387 |
+
"title": "35",
|
| 1388 |
+
"notes": (
|
| 1389 |
+
"Compact Title 35 release-point recipe. Exact release point and "
|
| 1390 |
+
"uncodified/classification exclusions are recorded; sections 122 "
|
| 1391 |
+
"and 181–188 resolve with format-independent stable identities."
|
| 1392 |
+
),
|
| 1393 |
+
"release": {
|
| 1394 |
+
"provider": "ushouse",
|
| 1395 |
+
"congress": int(congress_s),
|
| 1396 |
+
"release": release_s,
|
| 1397 |
+
"release_point": canonical,
|
| 1398 |
+
"title": "35",
|
| 1399 |
+
"edition": f"olrc-{canonical.replace('/', '-')}",
|
| 1400 |
+
"source_url": source_url,
|
| 1401 |
+
"content_sha256": package_sha,
|
| 1402 |
+
"retrieved_at": "2024-09-15T14:00:00Z",
|
| 1403 |
+
"formats": {
|
| 1404 |
+
"uslm": {
|
| 1405 |
+
"format": "uslm",
|
| 1406 |
+
"media_type": "application/uslm+xml",
|
| 1407 |
+
"artifact_sha256": package_sha,
|
| 1408 |
+
"source_url": source_url,
|
| 1409 |
+
"upstream_package_id": canonical,
|
| 1410 |
+
},
|
| 1411 |
+
"html": {
|
| 1412 |
+
"format": "html",
|
| 1413 |
+
"media_type": "text/html",
|
| 1414 |
+
"artifact_sha256": content_sha256(content_seed + "|html"),
|
| 1415 |
+
"source_url": ushouse_releasepoint_zip_url(
|
| 1416 |
+
congress=congress_s,
|
| 1417 |
+
release=release_s,
|
| 1418 |
+
title="35",
|
| 1419 |
+
format_kind=SourceFormat.HTML,
|
| 1420 |
+
),
|
| 1421 |
+
"upstream_package_id": canonical,
|
| 1422 |
+
},
|
| 1423 |
+
},
|
| 1424 |
+
},
|
| 1425 |
+
"exclusions": [
|
| 1426 |
+
{
|
| 1427 |
+
"kind": "uncodified_slip_law",
|
| 1428 |
+
"citation": "Pub. L. 118-100 § 3",
|
| 1429 |
+
"public_law": "Pub. L. 118-100",
|
| 1430 |
+
"reason": (
|
| 1431 |
+
"Enacted patent-fee adjustment not yet classified into "
|
| 1432 |
+
"positive-law Title 35 at this release point."
|
| 1433 |
+
),
|
| 1434 |
+
"affects_sections": [],
|
| 1435 |
+
},
|
| 1436 |
+
{
|
| 1437 |
+
"kind": "classification_gap",
|
| 1438 |
+
"citation": "Pub. L. 117-328 div. W",
|
| 1439 |
+
"public_law": "Pub. L. 117-328",
|
| 1440 |
+
"reason": (
|
| 1441 |
+
"Classification table records a pending editorial "
|
| 1442 |
+
"reclassification affecting cross-references in Title 35."
|
| 1443 |
+
),
|
| 1444 |
+
"affects_sections": ["122"],
|
| 1445 |
+
},
|
| 1446 |
+
{
|
| 1447 |
+
"kind": "positive_law_pending",
|
| 1448 |
+
"citation": "Uncodified national-security notice schedule",
|
| 1449 |
+
"reason": (
|
| 1450 |
+
"Agency secrecy-order implementing schedule published as "
|
| 1451 |
+
"uncodified material; not part of 35 U.S.C. 181–188 text."
|
| 1452 |
+
),
|
| 1453 |
+
"affects_sections": ["181", "182", "183", "184", "185", "186", "187", "188"],
|
| 1454 |
+
},
|
| 1455 |
+
],
|
| 1456 |
+
"sections": sections,
|
| 1457 |
+
}
|
| 1458 |
+
|
| 1459 |
+
|
| 1460 |
+
def write_default_fixtures(directory: PathLike | None = None) -> Path:
|
| 1461 |
+
"""Materialize the default Title 35 fixture recipe and missing-release case."""
|
| 1462 |
+
|
| 1463 |
+
root = Path(directory) if directory is not None else default_fixture_dir()
|
| 1464 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 1465 |
+
|
| 1466 |
+
recipe = build_title35_fixture_recipe()
|
| 1467 |
+
recipe_path = root / "title35_release_recipe.json"
|
| 1468 |
+
recipe_path.write_text(
|
| 1469 |
+
json.dumps(recipe, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
| 1470 |
+
encoding="utf-8",
|
| 1471 |
+
)
|
| 1472 |
+
|
| 1473 |
+
missing = {
|
| 1474 |
+
"schema_version": FIXTURE_SCHEMA_VERSION,
|
| 1475 |
+
"fixture_id": "title35-missing-release",
|
| 1476 |
+
"title": "35",
|
| 1477 |
+
"notes": "Release identity deliberately omitted for unknown-status tests.",
|
| 1478 |
+
"release": {
|
| 1479 |
+
"provider": "ushouse",
|
| 1480 |
+
"title": "35",
|
| 1481 |
+
"release_point": None,
|
| 1482 |
+
},
|
| 1483 |
+
"exclusions": [],
|
| 1484 |
+
"sections": [],
|
| 1485 |
+
}
|
| 1486 |
+
missing_path = root / "title35_missing_release.json"
|
| 1487 |
+
missing_path.write_text(
|
| 1488 |
+
json.dumps(missing, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
| 1489 |
+
encoding="utf-8",
|
| 1490 |
+
)
|
| 1491 |
+
|
| 1492 |
+
# Lightweight README for operators (not required by admission, but helpful).
|
| 1493 |
+
readme = root / "README.md"
|
| 1494 |
+
if not readme.exists():
|
| 1495 |
+
readme.write_text(
|
| 1496 |
+
"# Title 35 U.S. Code release-point fixtures\n\n"
|
| 1497 |
+
"Compact recipes for PATLAW-013. Prefer `title35_release_recipe.json` "
|
| 1498 |
+
"over bulk golden dumps. Missing release data is modeled in "
|
| 1499 |
+
"`title35_missing_release.json` and must resolve as `unknown`.\n",
|
| 1500 |
+
encoding="utf-8",
|
| 1501 |
+
)
|
| 1502 |
+
return root
|
| 1503 |
+
|
| 1504 |
+
|
| 1505 |
+
__all__ = [
|
| 1506 |
+
"COLLECTION_USCODE",
|
| 1507 |
+
"CONFIDENTIALITY_SECTION",
|
| 1508 |
+
"DEFAULT_TITLE",
|
| 1509 |
+
"FIXTURE_SCHEMA_VERSION",
|
| 1510 |
+
"PATENT_SENSITIVE_SECTIONS",
|
| 1511 |
+
"SCHEMA_VERSION",
|
| 1512 |
+
"SECRECY_ORDER_SECTIONS",
|
| 1513 |
+
"ExclusionKind",
|
| 1514 |
+
"FixtureSchemaError",
|
| 1515 |
+
"FormatArtifact",
|
| 1516 |
+
"MissingReleasePointError",
|
| 1517 |
+
"ReleaseExclusion",
|
| 1518 |
+
"ReleasePoint",
|
| 1519 |
+
"ResolutionStatus",
|
| 1520 |
+
"SectionNotFoundError",
|
| 1521 |
+
"SourceFormat",
|
| 1522 |
+
"UscodeReleaseAcquisition",
|
| 1523 |
+
"UscodeReleaseError",
|
| 1524 |
+
"UscodeReleaseProcessor",
|
| 1525 |
+
"UscodeSectionRecord",
|
| 1526 |
+
"build_title35_fixture_recipe",
|
| 1527 |
+
"content_sha256",
|
| 1528 |
+
"default_fixture_dir",
|
| 1529 |
+
"govinfo_title_package_id",
|
| 1530 |
+
"govinfo_title_zip_url",
|
| 1531 |
+
"load_json_fixture",
|
| 1532 |
+
"normalize_section_token",
|
| 1533 |
+
"normalize_title",
|
| 1534 |
+
"parse_release_point_id",
|
| 1535 |
+
"stable_section_identity",
|
| 1536 |
+
"ushouse_releasepoint_zip_url",
|
| 1537 |
+
"ushouse_title_code",
|
| 1538 |
+
"write_default_fixtures",
|
| 1539 |
+
]
|
scrapers_and_normalizers/scripts/scrapers/legal/us_code_scraper.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compatibility shim for legacy imports.
|
| 2 |
+
|
| 3 |
+
The legal scraper implementations live under
|
| 4 |
+
`ipfs_datasets_py.legal_scrapers`.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from ipfs_datasets_py.processors.legal_scrapers.us_code_scraper import * # noqa: F401,F403
|