diff --git a/README.md b/README.md index eebfe1fa79bcd0d42fbe862d08d9fe3ac01e3646..bdaca5790b5316ed7d27f4645ce79d9789d99e89 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ tags: - not-legal-advice - hongkong pretty_name: Hong Kong laws IR (CID-keyed GraphRAG) +size_categories: +- 10K dict[str, Any]: country = get_country(source) if not country.get("indexable", True): @@ -192,7 +193,8 @@ def build_country( else None ) _log( - f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}" + f"build start {repo} -> {out} " + f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}" ) configure_hf() CACHE.mkdir(parents=True, exist_ok=True) @@ -217,7 +219,7 @@ def build_country( force=force, rebuild_stub_vectors=not skip_vectors, ) - if plan.skip_build: + if plan.skip_build and not renormalize: _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") result = { "country": country["slug"], @@ -264,12 +266,35 @@ def build_country( current_corpus=corpus, force=force, rebuild_stub_vectors=not skip_vectors, + compare_normalized=renormalize and not force, ) _log( f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " f"added={0 if plan.delta is None else plan.delta.n_added} " f"removed={0 if plan.delta is None else plan.delta.n_removed}" ) + if plan.skip_build: + _log(f"skip unchanged after normalize {country['slug']}") + result = { + "country": country["slug"], + "source": repo, + "source_revision": source_meta["source_revision"], + "out": str(out), + "target_hub_id": target_repo(country["slug"]), + "skipped": True, + "incremental": plan.to_dict(), + "normalization": { + "n_out": norm_report.get("n_out"), + "unit": norm_report.get("unit"), + "n_law_rows": norm_report.get("n_law_rows"), + "n_child_rows": norm_report.get("n_child_rows"), + }, + "vector_blocker": None, + "neighbor_via": None, + "schema_version": "country-laws-ir-graphrag/v1", + } + record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) + return result n_docs = len(corpus) spill = spill_dir_for(country["slug"], CACHE) @@ -418,6 +443,7 @@ def reindex_from_gaps( force: bool = False, all_indexable: bool = False, device: str = "cuda", + renormalize: bool = False, ) -> list[dict[str, Any]]: """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. @@ -455,6 +481,7 @@ def reindex_from_gaps( "skip_vectors": skip_vectors, "fetch_hub_prior_ir": True, "device": device, + "renormalize": renormalize, } n_workers = max(1, int(workers or 1)) _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") diff --git a/country_laws_ir/__main__.py b/country_laws_ir/__main__.py index 438bb8d0cca0f061a42ee449d414a2ff2c0383cf..1fd7d105e98beb7edb0ce98c936f834d91a01964 100644 --- a/country_laws_ir/__main__.py +++ b/country_laws_ir/__main__.py @@ -73,7 +73,9 @@ def main(argv: list[str] | None = None) -> int: p_re.add_argument("--all", action="store_true", help="Process every indexable catalog country (not only Hub gaps)") p_re.add_argument("--force", action="store_true", - help="Rebuild even when the source SHA matches (rerun normalize/verifiers)") + help="Rebuild even when the source SHA matches, and re-encode every row") + p_re.add_argument("--renormalize", action="store_true", + help="Rerun normalization, then reindex only packs whose entry rows changed") p_ver = sub.add_parser( "verify", @@ -83,6 +85,21 @@ def main(argv: list[str] | None = None) -> int: p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country") p_ver.add_argument("--limit", type=int, default=None) + p_loop = sub.add_parser( + "normalize-loop", + help="scan residuals, improve the normalizer script with llm_router, or apply that script", + ) + p_loop.add_argument("stage", choices=["scan", "improve", "apply", "run"]) + p_loop.add_argument("--cache", default=None) + p_loop.add_argument("--out", default=None) + p_loop.add_argument("--reports", default=None, help="Per-country residual JSON directory") + p_loop.add_argument("--slug", default=None, help="One country, for a subprocess") + p_loop.add_argument("--workers", type=int, default=None, help="Country processes (default: one per CPU)") + p_loop.add_argument("--limit", type=int, default=None) + p_loop.add_argument("--passes", type=int, default=40, help="Improve batches sent to llm_router") + p_loop.add_argument("--force", action="store_true", help="Redo finished countries and retry unresolved lines") + p_loop.add_argument("--progress", default=None, help="JSONL file appended as each country or improve pass finishes") + p_raw = sub.add_parser("package-raw") p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs__laws_ir") p_raw.add_argument("--instruments-dir", default=None, @@ -175,6 +192,7 @@ def main(argv: list[str] | None = None) -> int: force=args.force, all_indexable=args.all, device=args.device, + renormalize=args.renormalize, ) print(json.dumps( [ @@ -253,6 +271,125 @@ def main(argv: list[str] | None = None) -> int: ) ) return 1 if failed else 0 + if args.cmd == "normalize-loop": + from .build import CACHE, ROOT + from .normalize_loop import ( + _apply_job, + _scan_job, + append_progress, + apply_done, + cache_packs, + improve_from_reports, + load_generate_text, + run_parallel, + scan_done, + worker_count, + ) + + cache = Path(args.cache) if args.cache else CACHE + reports = Path(args.reports) if args.reports else ROOT / "reports" / "residuals" + out = Path(args.out) if args.out else ROOT / "llm-normalized" + packs = cache_packs(cache, slug=args.slug) + if args.limit: + packs = packs[: int(args.limit)] + workers = worker_count(args.workers) + progress = Path(args.progress) if args.progress else ROOT / "reports" / f"normalize_{args.stage}.jsonl" + + def _pending(stage: str) -> tuple[list[tuple[str, str, str]], list[str]]: + jobs: list[tuple[str, str, str]] = [] + skipped: list[str] = [] + for slug, path in packs: + done = scan_done(reports, slug) if stage == "scan" else apply_done(out, slug) + if done and not args.force: + skipped.append(slug) + continue + dest = reports if stage == "scan" else out + jobs.append((slug, str(path), str(dest))) + return jobs, skipped + + def _run(stage: str, worker) -> list[dict]: + jobs, skipped = _pending(stage) + total = len(jobs) + len(skipped) + done = len(skipped) + print(json.dumps({ + "event": "start", + "stage": stage, + "workers": workers, + "done": done, + "pending": len(jobs), + "total": total, + "progress": str(progress), + }), flush=True) + state = {"done": done} + + def _on_done(row: dict) -> None: + state["done"] += 1 + print(json.dumps({ + "event": stage, + "done": state["done"], + "total": total, + **row, + }), flush=True) + + return run_parallel(jobs, worker, workers, progress_path=progress, on_done=_on_done) + + if args.stage == "scan": + rows = _run("scan", _scan_job) + failed = [row for row in rows if row.get("error")] + print(json.dumps({"stage": "scan", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2)) + return 1 if failed else 0 + if args.stage == "apply": + rows = _run("apply", _apply_job) + failed = [row for row in rows if row.get("error")] + print(json.dumps({"stage": "apply", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2)) + return 1 if failed else 0 + def _on_pass(row: dict) -> None: + print(json.dumps({"event": "improve", **row}, ensure_ascii=False), flush=True) + append_progress(progress, {"event": "improve", **row}) + + def _improve(): + print(json.dumps({ + "event": "start", + "stage": "improve", + "passes": args.passes, + "reports": str(reports), + }), flush=True) + try: + generate = load_generate_text() + except Exception as exc: + print(json.dumps({"error": f"llm_router unavailable: {exc}"}), flush=True) + return None + return improve_from_reports( + reports, + generate, + max_passes=args.passes, + on_pass=_on_pass, + reset_unresolved=bool(args.force), + ) + + if args.stage == "improve": + result = _improve() + if result is None: + return 1 + print(json.dumps({"stage": "improve", **result}, indent=2, ensure_ascii=False)) + return 0 + # run scans, then improves the script. Applying the script to every + # pack is the separate ``apply`` stage. + scan_rows = _run("scan", _scan_job) + failed = [row for row in scan_rows if row.get("error")] + if failed: + print(json.dumps({"stage": "run", "n_scanned": len(scan_rows), "n_failed": len(failed)}, indent=2)) + return 1 + improved = _improve() + if improved is None: + return 1 + print(json.dumps( + {"stage": "run", "workers": workers, "improve": improved, "n_scanned": len(scan_rows)}, + indent=2, + ensure_ascii=False, + default=str, + )) + return 0 if args.cmd == "package-raw": from .build import RELEASES from .raw_package import default_instruments_dir, package_instruments diff --git a/country_laws_ir/build.py b/country_laws_ir/build.py index 768973af97da5ea96deef2b5b7bbbc06909d9ebe..8d1c8f2e144e403200add9db1514e56f2ca5e4b5 100644 --- a/country_laws_ir/build.py +++ b/country_laws_ir/build.py @@ -176,6 +176,7 @@ def build_country( force: bool = False, prior_dir: Path | None = None, fetch_hub_prior_ir: bool = True, + renormalize: bool = False, ) -> dict[str, Any]: country = get_country(source) if not country.get("indexable", True): @@ -192,7 +193,8 @@ def build_country( else None ) _log( - f"build start {repo} -> {out} (upload={upload} mode={mode} force={force}) local={local_dir}" + f"build start {repo} -> {out} " + f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}" ) configure_hf() CACHE.mkdir(parents=True, exist_ok=True) @@ -217,7 +219,7 @@ def build_country( force=force, rebuild_stub_vectors=not skip_vectors, ) - if plan.skip_build: + if plan.skip_build and not renormalize: _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") result = { "country": country["slug"], @@ -264,12 +266,35 @@ def build_country( current_corpus=corpus, force=force, rebuild_stub_vectors=not skip_vectors, + compare_normalized=renormalize and not force, ) _log( f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " f"added={0 if plan.delta is None else plan.delta.n_added} " f"removed={0 if plan.delta is None else plan.delta.n_removed}" ) + if plan.skip_build: + _log(f"skip unchanged after normalize {country['slug']}") + result = { + "country": country["slug"], + "source": repo, + "source_revision": source_meta["source_revision"], + "out": str(out), + "target_hub_id": target_repo(country["slug"]), + "skipped": True, + "incremental": plan.to_dict(), + "normalization": { + "n_out": norm_report.get("n_out"), + "unit": norm_report.get("unit"), + "n_law_rows": norm_report.get("n_law_rows"), + "n_child_rows": norm_report.get("n_child_rows"), + }, + "vector_blocker": None, + "neighbor_via": None, + "schema_version": "country-laws-ir-graphrag/v1", + } + record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) + return result n_docs = len(corpus) spill = spill_dir_for(country["slug"], CACHE) @@ -418,6 +443,7 @@ def reindex_from_gaps( force: bool = False, all_indexable: bool = False, device: str = "cuda", + renormalize: bool = False, ) -> list[dict[str, Any]]: """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country. @@ -455,6 +481,7 @@ def reindex_from_gaps( "skip_vectors": skip_vectors, "fetch_hub_prior_ir": True, "device": device, + "renormalize": renormalize, } n_workers = max(1, int(workers or 1)) _log(f"reindex parallel workers={n_workers} countries={len(slugs)} device=cuda") diff --git a/country_laws_ir/citations.py b/country_laws_ir/citations.py new file mode 100644 index 0000000000000000000000000000000000000000..4900f9f3fd1d7b8d9f2c4ba3316e947750de2783 --- /dev/null +++ b/country_laws_ir/citations.py @@ -0,0 +1,139 @@ +"""Official and Bluebook citations for country-law corpus rows. + +Bluebook T2/T10 abbreviations are used only when this table has a row. +Unknown jurisdictions get ``official_citation`` only — never a invented +Bluebook form. Query keys are normalized so ``ORS 1.010`` and +``Or. Rev. Stat. § 1.010`` can hit the same row later. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import re +import unicodedata +from typing import Any + +from pathlib import Path +import json as _json + +_TABLE_PATH = Path(__file__).resolve().parent / "data" / "bluebook_t2.json" + + +def _load_t2() -> dict[str, dict[str, Any]]: + if not _TABLE_PATH.is_file(): + return {} + payload = _json.loads(_TABLE_PATH.read_text(encoding="utf-8")) + return payload if isinstance(payload, dict) else {} + + +_BLUEBOOK_T2 = _load_t2() + + +@dataclass(frozen=True) +class Citation: + official_citation: str + bluebook_citation: str + cite_key: str + citation_status: str # bluebook | official_only | unknown + pinpoint: str + + +def normalize_cite_key(value: str) -> str: + if not value: + return "" + text = unicodedata.normalize("NFKC", value).lower() + text = text.replace("§", " s ") + text = text.replace("¶", " ") + text = re.sub(r"\bart(?:icle|\.)?\b", "art", text) + text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text) + text = re.sub(r"[^a-z0-9]+", " ", text) + return re.sub(r"\s+", " ", text).strip() + + +def _pinpoint(article_number: str, section_number: str, record_type: str) -> str: + if record_type == "section" and section_number: + return f"§ {section_number}" + if article_number: + return f"art. {article_number}" + if section_number: + return f"§ {section_number}" + return "" + + +def _t2_row(jurisdiction: str, country: str, slug: str = "") -> dict[str, Any]: + for key in (slug, country, jurisdiction): + hit = _BLUEBOOK_T2.get(str(key or "").strip().lower().replace("_", " ")) + if isinstance(hit, dict): + return hit + return {} + + +def assign_citation( + *, + eli: str = "", + official_identifier: str = "", + identifier: str = "", + instrument_title: str = "", + article_number: str = "", + section_number: str = "", + record_type: str = "law", + jurisdiction: str = "", + country: str = "", + slug: str = "", + year: str = "", +) -> Citation: + pinpoint = _pinpoint(article_number, section_number, record_type) + official = ( + (eli or "").strip() + or (official_identifier or "").strip() + or (identifier or "").strip() + or (instrument_title or "").strip() + ) + if official and pinpoint and pinpoint.lower() not in official.lower(): + official_cite = f"{official}, {pinpoint}" + else: + official_cite = official + + t2 = _t2_row(jurisdiction, country, slug) + abbrev = str(t2.get("abbrev") or "") + emit = str(t2.get("emit") or "official_only") + required = list(t2.get("required") or []) + have = { + "year": bool(year), + "section": bool(section_number or (record_type == "section" and article_number)), + "article": bool(article_number), + "title": bool(instrument_title), + } + missing = [k for k in required if not have.get(k)] + bluebook = "" + if emit == "bluebook" and abbrev and not missing: + if pinpoint: + bluebook = f"{abbrev} {pinpoint}" + (f" ({year})" if year else "") + elif have.get("section"): + bluebook = f"{abbrev} § {section_number}" + (f" ({year})" if year else "") + + if bluebook: + status = "bluebook" + elif official_cite: + status = "official_only" + else: + status = "unknown" + + key_src = bluebook or official_cite + return Citation( + official_citation=official_cite, + bluebook_citation=bluebook, + cite_key=normalize_cite_key(key_src), + citation_status=status, + pinpoint=pinpoint, + ) + + +def citation_fields(cite: Citation) -> dict[str, Any]: + return { + "official_citation": cite.official_citation, + "bluebook_citation": cite.bluebook_citation, + "cite_key": cite.cite_key, + "citation_status": cite.citation_status, + "pinpoint": cite.pinpoint, + } diff --git a/country_laws_ir/data/bluebook_t2.json b/country_laws_ir/data/bluebook_t2.json new file mode 100644 index 0000000000000000000000000000000000000000..4886b2c4633abed67efe8105a93cc369796f4559 --- /dev/null +++ b/country_laws_ir/data/bluebook_t2.json @@ -0,0 +1,27 @@ +{ + "usa": {"abbrev": "U.S.C.", "emit": "bluebook", "required": ["title", "section"]}, + "united states": {"abbrev": "U.S.C.", "emit": "bluebook", "required": ["title", "section"]}, + "uk": {"abbrev": "U.K.", "emit": "official_only", "required": []}, + "united kingdom": {"abbrev": "U.K.", "emit": "official_only", "required": []}, + "australia": {"abbrev": "Cth", "emit": "official_only", "required": ["year"]}, + "canada": {"abbrev": "S.C.", "emit": "official_only", "required": ["year"]}, + "germany": {"abbrev": "BGBl.", "emit": "official_only", "required": []}, + "france": {"abbrev": "J.O.", "emit": "official_only", "required": []}, + "malta": {"abbrev": "Laws of Malta", "emit": "official_only", "required": []}, + "ireland": {"abbrev": "Ir.", "emit": "official_only", "required": []}, + "newzealand": {"abbrev": "N.Z.", "emit": "official_only", "required": []}, + "new zealand": {"abbrev": "N.Z.", "emit": "official_only", "required": []}, + "southafrica": {"abbrev": "S. Afr.", "emit": "official_only", "required": []}, + "south africa": {"abbrev": "S. Afr.", "emit": "official_only", "required": []}, + "india": {"abbrev": "India", "emit": "official_only", "required": []}, + "japan": {"abbrev": "Japan", "emit": "official_only", "required": []}, + "china": {"abbrev": "P.R.C.", "emit": "official_only", "required": []}, + "netherlands": {"abbrev": "Stb.", "emit": "official_only", "required": []}, + "austria": {"abbrev": "BGBl.", "emit": "official_only", "required": []}, + "switzerland": {"abbrev": "AS", "emit": "official_only", "required": []}, + "sweden": {"abbrev": "SFS", "emit": "official_only", "required": []}, + "norway": {"abbrev": "Norsk Lovtidend", "emit": "official_only", "required": []}, + "denmark": {"abbrev": "Lovtidende", "emit": "official_only", "required": []}, + "finland": {"abbrev": "Finlex", "emit": "official_only", "required": []}, + "eu": {"abbrev": "O.J.", "emit": "official_only", "required": []} +} diff --git a/country_laws_ir/data/learned_line_patterns.json b/country_laws_ir/data/learned_line_patterns.json new file mode 100644 index 0000000000000000000000000000000000000000..b5b010c3654d2629ad348136c35f9179caa7ceea --- /dev/null +++ b/country_laws_ir/data/learned_line_patterns.json @@ -0,0 +1,3 @@ +{ + "patterns": [] +} diff --git a/country_laws_ir/duckdb_store.py b/country_laws_ir/duckdb_store.py index 743473eea8b69f71eb222568bcadf0549160db49..84cd52b7e05f8b35192c86ac93cf8c680a656795 100644 --- a/country_laws_ir/duckdb_store.py +++ b/country_laws_ir/duckdb_store.py @@ -151,6 +151,73 @@ def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]] con.close() +def cite_search( + root: Path, + citation: str, + *, + cite_format: str = "any", + limit: int = 25, +) -> list[dict[str, Any]]: + """Look up corpus rows by Bluebook, official cite, or normalized cite_key.""" + from .citations import normalize_cite_key + + needle = (citation or "").strip() + if not needle: + return [] + key = normalize_cite_key(needle) + con = connect_release(root) + try: + tables = { + r[0] + for r in con.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" + ).fetchall() + } + if "corpus" not in tables: + raise DuckDBStoreError("release is missing corpus parquet shards") + cols = [ + r[1] + for r in con.execute( + "SELECT table_schema, column_name FROM information_schema.columns " + "WHERE table_schema = 'main' AND table_name = 'corpus'" + ).fetchall() + ] + wanted = [ + "entry_cid", + "record_type", + "title", + "instrument_title", + "article_number", + "official_citation", + "bluebook_citation", + "cite_key", + "citation_status", + "source_url", + ] + select = ", ".join(c for c in wanted if c in cols) or "*" + clauses = [] + params: list[Any] = [] + fmt = (cite_format or "any").strip().lower() + if fmt in {"any", "bluebook"} and "bluebook_citation" in cols: + clauses.append("lower(coalesce(bluebook_citation, '')) = lower(?)") + params.append(needle) + if fmt in {"any", "official"} and "official_citation" in cols: + clauses.append("lower(coalesce(official_citation, '')) = lower(?)") + params.append(needle) + if "cite_key" in cols and key: + clauses.append("cite_key = ?") + params.append(key) + if not clauses: + return [] + sql = f"SELECT {select} FROM corpus WHERE {' OR '.join(clauses)} LIMIT ?" + params.append(int(limit)) + rows = con.execute(sql, params).fetchall() + names = [c for c in wanted if c in cols] if select != "*" else list(cols) + return [dict(zip(names, row)) for row in rows] + finally: + con.close() + + def graph_neighbors( root: Path, node_cid: str, diff --git a/country_laws_ir/graph.py b/country_laws_ir/graph.py index 194057fa551559d44027bad475ecb1b6ec48ed8f..a0e6f4590d7a7d74d9dc59a358288e2fd688528d 100644 --- a/country_laws_ir/graph.py +++ b/country_laws_ir/graph.py @@ -21,6 +21,15 @@ FACET_FIELDS = ( ) ADJ_POINTERS_PER_ROW = 4096 ADJ_POINTERS_PER_SHARD = 8192 +_LABEL_MAX = 4096 + + +def _graph_label(text: str, fallback: str) -> str: + """Node labels are capped at 4096 characters. The full value stays in properties.""" + cleaned = str(text or "").replace("\x00", "").strip() or fallback + if len(cleaned) > _LABEL_MAX: + return cleaned[: _LABEL_MAX - 3] + "..." + return cleaned def _facet_cid(kind: str, value: str) -> str: @@ -68,7 +77,7 @@ def build_graph( "node_cid": law_cid, "node_type": "law", "entry_cid": "", - "label": getattr(rec, "instrument_title", None) or instrument_id, + "label": _graph_label(getattr(rec, "instrument_title", None) or instrument_id, instrument_id), "properties_json": _json( { "instrument_id": instrument_id, @@ -85,14 +94,19 @@ def build_graph( nodes.append(law_node) for rec in corpus.itertuples(index=False): - node_type = "law_entry" if rec.record_type == "law" else "article" + if rec.record_type == "law": + node_type = "law_entry" + elif rec.record_type == "notice": + node_type = "notice" + else: + node_type = "article" title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id nodes.append( { "node_cid": rec.entry_cid, "node_type": node_type, "entry_cid": rec.entry_cid, - "label": title, + "label": _graph_label(title or rec.source_id, str(rec.source_id)), "properties_json": _props_tuple(rec), "schema_version": SCHEMA_VERSION, } @@ -112,7 +126,7 @@ def build_graph( "node_cid": fc, "node_type": f"facet_{kind}", "entry_cid": "", - "label": f"{kind}:{value}", + "label": _graph_label(f"{kind}:{value}", kind), "properties_json": _json({"kind": kind, "value": value}), "schema_version": SCHEMA_VERSION, } @@ -130,7 +144,7 @@ def build_graph( "node_cid": fc, "node_type": "facet_eli", "entry_cid": "", - "label": f"eli:{eli}", + "label": _graph_label(f"eli:{eli}", "eli"), "properties_json": _json({"kind": "eli", "value": eli}), "schema_version": SCHEMA_VERSION, } @@ -146,7 +160,7 @@ def build_graph( "node_cid": fc, "node_type": "facet_identifier", "entry_cid": "", - "label": f"identifier:{ident}", + "label": _graph_label(f"identifier:{ident}", "identifier"), "properties_json": _json({"kind": "identifier", "value": ident}), "schema_version": SCHEMA_VERSION, } @@ -157,7 +171,7 @@ def build_graph( law_cid = str(row_map.get("law_cid") or "") instrument_id = str(row_map.get("instrument_id") or "") - if rec.record_type == "article": + if rec.record_type in {"article", "section"}: parent = entry_by_instrument.get(instrument_id) or law_cid if parent and parent != rec.entry_cid: edges.append( diff --git a/country_laws_ir/incremental.py b/country_laws_ir/incremental.py index 870039d76530cefabb9284ebd6322289345b1c06..d6d1337a7273f307726a193131e877d9ef6ee750 100644 --- a/country_laws_ir/incremental.py +++ b/country_laws_ir/incremental.py @@ -235,6 +235,7 @@ def plan_rebuild( current_corpus: pd.DataFrame | None = None, force: bool = False, rebuild_stub_vectors: bool = True, + compare_normalized: bool = False, ) -> RebuildPlan: """Decide skip / delta / full from source fingerprints and CID overlap.""" mode = BuildMode.coerce(mode) @@ -288,7 +289,8 @@ def plan_rebuild( "partial", } - if prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors: + fingerprint_match = bool(prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors) + if fingerprint_match and not (compare_normalized and current_corpus is not None): return RebuildPlan( kind=RebuildKind.UNCHANGED, mode=mode, @@ -312,6 +314,20 @@ def plan_rebuild( delta = None if current_corpus is not None: delta = diff_corpus(prior.corpus, current_corpus) + if delta.n_added == 0 and delta.n_removed == 0 and not stub_vectors: + return RebuildPlan( + kind=RebuildKind.UNCHANGED, + mode=mode, + reason="normalized entry_cids match the prior release", + source_revision=revision, + prior_revision=prior_revision, + source_fingerprint=fingerprint, + prior_fingerprint=prior_fp, + delta=delta, + reuse_embeddings=True, + skip_build=True, + equivalent_to_full=False, + ) if delta.equivalent_to_full: return RebuildPlan( kind=RebuildKind.FULL_REBUILD, diff --git a/country_laws_ir/normalize.py b/country_laws_ir/normalize.py index b3c348f675dd13ca6f9184c6ffffce5cdfead2d8..1d77e3281ac66ffa99064e6afbcc5f1917da8a98 100644 --- a/country_laws_ir/normalize.py +++ b/country_laws_ir/normalize.py @@ -12,6 +12,7 @@ from __future__ import annotations import json import os +import re from collections import Counter from pathlib import Path from typing import Any @@ -24,7 +25,13 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws -from .structure import normalize_legal_text, split_structured_units +from .reconstruct import ( + article_sort_key, + parent_needs_reconstruct, + reconstruct_on, + reconstruct_parent, +) +from .structure import StructureUnit, normalize_legal_text, split_structured_units COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" EMPTY_ARTICLE_COLUMNS = ( @@ -311,6 +318,249 @@ def _hierarchy_fields( } +def _compact_line(text: str) -> str: + return re.sub(r"\s+", " ", text or "").strip().casefold() + + +def _is_title_shell(body: str, title: str) -> bool: + """True when the article row is only its heading, repeated once.""" + folded_body = _compact_line(body) + folded_title = _compact_line(title) + if len(folded_title) < 24 or not folded_body: + return False + return folded_body == folded_title or folded_body == f"{folded_title} {folded_title}" + + +_NOTICE_RE = re.compile( + r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|" + r"\bnews item\b|\bnotice board\b)" +) + + +def _instrument_record_type(metadata: dict[str, Any], title: str) -> str: + """A normative instrument is a law, even when its title says Article. + + Newsletters, blogs, and press notices are not laws. A provision inside a + law stays an article; this label is only for the instrument itself. + """ + meta = metadata or {} + document_type = str(meta.get("document_type") or "").strip().casefold() + meta_type = str(meta.get("record_type") or "").strip().casefold() + if _NOTICE_RE.search(title or "") or document_type in { + "newsletter", + "blog", + "press", + "press_release", + "notice", + }: + return "notice" + if document_type in {"gazette", "gazette_pdf"} and meta_type not in { + "law", + "statute", + "constitution", + }: + return "notice" + return "law" + + +def _unit_record_type(unit: Any, instrument_type: str, *, n_units: int, parent_body: str) -> str: + """One unit that is the whole instrument keeps the instrument label.""" + if instrument_type == "notice": + return "notice" + if ( + n_units == 1 + and parent_body + and len(getattr(unit, "body", "") or "") >= int(0.8 * len(parent_body)) + ): + return "law" + kind = getattr(unit, "kind", "") or "" + if kind in {"article", "section"}: + return kind + return "article" + + +def _children_are_rich(kids: list[dict[str, Any]], parent_body: str) -> bool: + """True when the article rows already carry the statute, not just headings.""" + if not kids: + return False + total = sum(len((kid.get("body") or "").strip()) for kid in kids) + if total >= max(int(len(parent_body) * 0.5), 200): + return True + return any( + len((kid.get("body") or "").strip()) >= 80 + and not _is_title_shell(kid.get("body") or "", kid.get("title") or "") + for kid in kids + ) + + +def _article_copies_parent( + kid: dict[str, Any], parent_body: str, parent_title: str +) -> bool: + """True when this row is the statute, not a provision inside it. + + Collectors sometimes store the whole law again in the article table, with + the law's own title and no article number. A numbered provision whose body + is shorter than the statute stays a provision. + """ + body = (kid.get("body") or "").strip() + parent = (parent_body or "").strip() + if not body or not parent: + return False + if _compact_line(body) == _compact_line(parent): + return True + same_title = _compact_line(kid.get("title") or "") == _compact_line(parent_title) + no_number = not str(kid.get("article_number") or "").strip() + if not same_title or not no_number or len(parent) < 200: + return False + if len(body) < int(0.85 * len(parent)): + return False + return body[:200] in parent or parent[:200] in body + + +def _needs_parent_split( + kids: list[dict[str, Any]], parent_body: str, parent_title: str = "" +) -> bool: + """Split the parent when it holds the text and the article rows do not.""" + if len(parent_body) < 250 or len(parent_body) > 1_200_000: + return False + provisions = [ + kid + for kid in kids + if not _article_copies_parent(kid, parent_body, parent_title) + ] + return not _children_are_rich(provisions, parent_body) + + +_REAL_HEADING_RE = re.compile( + r"(?i)^(?:article|art\.?|artikel|articulo|artículo|section|sec\.?|§|" + r"مادة|المادة|clause|regulation|rule|schedule)\b" +) + + +def _is_provision_heading(unit: StructureUnit) -> bool: + """A numbered article or section stays its own row even when the text is short.""" + head = (unit.heading or unit.body or "").strip() + return _REAL_HEADING_RE.match(head) is not None + + +def _merge_units(parts: list[StructureUnit]) -> StructureUnit: + first = parts[0] + body = "\n\n".join(part.body.strip() for part in parts if part.body and part.body.strip()) + return StructureUnit( + kind=first.kind, + number=first.number, + heading=first.heading, + body=body, + title_number=first.title_number, + chapter_number=first.chapter_number, + part_number=first.part_number, + article_number=first.article_number, + section_number=first.section_number, + subsections=first.subsections, + hierarchy_path=first.hierarchy_path, + char_start=first.char_start, + char_end=parts[-1].char_end, + ) + + +def _thicken_units(units: list[StructureUnit]) -> list[StructureUnit]: + """Join one-line splits onto the previous provision. + + A provision of at least 80 characters stays its own row. Shorter pieces, + such as a lettered clause or a heading with no sentence, stay in the + previous provision. When every piece is that short, they are grouped into + passages of at least 240 characters. Fewer than two passages means the + statute stays a single law row. + """ + if len(units) < 2: + return [] + kept: list[StructureUnit] = [] + pending: list[StructureUnit] = [] + for unit in units: + if len((unit.body or "").strip()) >= 80 or _is_provision_heading(unit): + if pending: + kept.append(_merge_units([*pending, unit])) + pending = [] + else: + kept.append(unit) + elif kept: + kept[-1] = _merge_units([kept[-1], unit]) + else: + pending.append(unit) + if pending and kept: + kept[-1] = _merge_units([kept[-1], *pending]) + elif pending: + buf: list[StructureUnit] = [] + size = 0 + for unit in pending: + buf.append(unit) + size += len((unit.body or "").strip()) + if size >= 240: + kept.append(_merge_units(buf)) + buf = [] + size = 0 + if buf and kept: + kept[-1] = _merge_units([kept[-1], *buf]) + elif buf and size >= 240: + kept.append(_merge_units(buf)) + if len(kept) < 2: + return [] + return kept + + +def _copy_is_notice(kid: dict[str, Any]) -> bool: + meta = dict(kid.get("metadata") or {}) + if kid.get("record_type") and "record_type" not in meta: + meta["record_type"] = kid["record_type"] + return _instrument_record_type(meta, kid.get("title") or "") == "notice" + + +def _prefer_notice_from_copies(parent: dict[str, Any], kids: list[dict[str, Any]]) -> None: + """A statute row that is only a newsletter stays a notice.""" + doc = str((parent.get("metadata") or {}).get("document_type") or "").casefold() + if doc in {"law", "statute", "constitution"}: + return + for kid in kids: + if _article_copies_parent( + kid, parent.get("body") or "", parent.get("instrument_title") or "" + ) and _copy_is_notice(kid): + parent["metadata"] = { + **(parent.get("metadata") or {}), + "document_type": "newsletter", + } + return + + +def _expand_title_shell(parent: str, title: str, sibling_titles: set[str]) -> str | None: + """Copy the parent span from this heading to the next sibling heading. + + The span is taken only from lines already in the parent. A short heading + such as "Article 1" is left alone, because it matches too many lines. + """ + key = _compact_line(title) + peers = {item for item in sibling_titles if item and item != key and len(item) >= 24} + if len(key) < 24 or not peers or not parent: + return None + lines = [ln.strip() for ln in parent.splitlines() if ln.strip()] + compact = [_compact_line(ln) for ln in lines] + best = "" + for index, folded in enumerate(compact): + if folded != key: + continue + chunk = [lines[index]] + for later, later_folded in zip(lines[index + 1 :], compact[index + 1 :]): + if later_folded in peers: + break + chunk.append(later) + text = "\n".join(chunk).strip() + if len(text) > len(best): + best = text + # The heading alone is not enough. Require a following sentence from the parent. + if len(best) < len(key) + 40: + return None + return best + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -399,6 +649,34 @@ def _base_record( } if extra: rec.update(extra) + from .citations import assign_citation, citation_fields + + slug = "" + if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): + slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws") + year = "" + if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit(): + year = snapshot_date[:4] + extra = extra or {} + rec.update( + citation_fields( + assign_citation( + eli=str(rec.get("eli") or extra.get("eli") or ""), + official_identifier=str( + rec.get("official_identifier") or extra.get("official_identifier") or "" + ), + identifier=str(rec.get("identifier") or extra.get("identifier") or ""), + instrument_title=instrument_title, + article_number=article_number, + section_number=str(extra.get("section_number") or ""), + record_type=record_type, + jurisdiction=jurisdiction, + country=str(extra.get("country") or ""), + slug=slug, + year=year, + ) + ) + ) rec["entry_cid"] = _entry_cid(rec) rec["title_length"] = len(title_for_bm25) rec["body_length"] = len(body) @@ -455,16 +733,163 @@ def build_corpus( "schema_surprises": list(source_meta.get("schema_surprises") or []), "n_out": 0, "never_invented_legal_text": True, + "n_reconstructed_parents": 0, + "n_reconstructed_truncated": 0, + "n_reconstructed_stubs": 0, + "n_empty_parents_with_articles_not_reconstructed": 0, + "n_thin_instruments_replaced": 0, + "n_statute_rows_kept_as_law": 0, } entries: list[dict[str, Any]] = [] + slug = "" + if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): + slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws") + + children_by_law: dict[str, list[dict[str, Any]]] = {} + if not articles_empty: + for _, row in articles.iterrows(): + lid = _row_get(row, "law_id") + if not lid: + continue + children_by_law.setdefault(lid, []).append( + { + "id": _row_get(row, "id"), + "title": _row_get(row, "title"), + "article_number": _row_get(row, "article_number"), + "body": _row_get(row, "text"), + "record_type": _row_get(row, "record_type"), + "metadata": _parse_meta(_row_get(row, "metadata_json")), + "row": row, + } + ) + + reconstructed_ids: set[str] = set() + running_extra_bytes = 0 + + def _append_law_row( + instrument_id: str, + parent: dict[str, Any], + recon=None, + ) -> None: + body = parent["body"] + recon_extra: dict[str, Any] = {} + coverage = _coverage_from( + parent["row"], + parent["metadata"], + articles_empty=articles_empty, + sparse_fallback=sparse_fallback, + ) + if recon is not None and recon.reconstructed_from_articles: + body = recon.body + recon_extra = recon.extra_fields() + coverage = f"{coverage}; reconstructed_from_articles" + if not body: + kids = children_by_law.get(instrument_id) or [] + if kids: + report["n_empty_parents_with_articles_not_reconstructed"] += 1 + report["drops"]["empty_body"] += 1 + if len(report["drop_samples"]["empty_body"]) < 20: + report["drop_samples"]["empty_body"].append(instrument_id) + return + meta = parent["metadata"] + entries.append( + _base_record( + record_type=_instrument_record_type(meta, parent["instrument_title"]), + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number="", + article_title="", + body=body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage=coverage, + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=instrument_id, + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": "", + "article_id": "", + "reconstructed_from_articles": False, + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), + **recon_extra, + }, + ) + ) if sparse_fallback: report["schema_surprises"].append( f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units" ) - if use_articles: + for instrument_id, parent in law_map.items(): + kids = children_by_law.get(instrument_id) or [] + recon = None + if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)): + recon = reconstruct_parent( + slug=slug, + parent_body=parent["body"], + parent_title=parent["instrument_title"], + children=[ + { + "id": k["id"], + "title": k["title"], + "article_number": k["article_number"], + "body": k["body"], + } + for k in kids + ], + running_extra_bytes=running_extra_bytes, + sha256_hex=sha256_hex, + ) + running_extra_bytes += recon.extra_bytes + reconstructed_ids.add(instrument_id) + report["n_reconstructed_parents"] += 1 + if recon.reconstruction_truncated: + report["n_reconstructed_truncated"] += 1 + if recon.is_stub: + report["n_reconstructed_stubs"] += 1 + _prefer_notice_from_copies(parent, kids) + _append_law_row(instrument_id, parent, recon) + + emit_articles = use_articles or bool(reconstructed_ids) + skip_body_split = emit_articles + sibling_titles = { + instrument_id: {_compact_line(kid["title"]) for kid in kids} + for instrument_id, kids in children_by_law.items() + } + promoted: dict[str, list[Any]] = {} + if emit_articles: + for instrument_id, parent in law_map.items(): + kids = children_by_law.get(instrument_id) or [] + if not _needs_parent_split(kids, parent["body"], parent["instrument_title"]): + continue + units = split_structured_units(parent["body"], language=parent["language"]) + covered = sum(len(unit.body) for unit in units) + thick = _thicken_units(units) + if len(thick) >= 2 and covered >= int(0.35 * len(parent["body"])): + promoted[instrument_id] = thick + if promoted: + report["n_thin_instruments_replaced"] = len(promoted) + report["schema_surprises"].append( + "parent headings used for " + f"{len(promoted)} instruments whose article rows were missing or thin" + ) + + if emit_articles: for _, row in articles.iterrows(): source_id = _row_get(row, "id") instrument_id = _row_get(row, "law_id") @@ -477,6 +902,27 @@ def build_corpus( report["drop_samples"]["empty_body"].append(source_id) continue parent = law_map.get(instrument_id) + if parent and _article_copies_parent( + { + "body": body, + "title": article_title, + "article_number": article_number, + }, + parent["body"], + parent["instrument_title"], + ): + report["n_statute_rows_kept_as_law"] += 1 + continue + if instrument_id in promoted: + continue + if parent and _is_title_shell(body, article_title): + expanded = _expand_title_shell( + parent["body"], + article_title, + sibling_titles.get(instrument_id) or set(), + ) + if expanded: + body = expanded if not parent: report["drops"]["missing_instrument"] += 1 if len(report["drop_samples"]["missing_instrument"]) < 20: @@ -487,9 +933,10 @@ def build_corpus( meta = parent["metadata"] art_meta = _parse_meta(_row_get(row, "metadata_json")) merged_meta = {**meta, **art_meta} + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) entries.append( _base_record( - record_type="article", + record_type="notice" if instrument_type == "notice" else "article", source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, @@ -521,22 +968,76 @@ def build_corpus( }, ) ) - else: + for instrument_id, units in promoted.items(): + parent = law_map[instrument_id] + meta = parent["metadata"] + report["unit"] = "structured" + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) + for unit in units: + entries.append( + _base_record( + record_type=_unit_record_type( + unit, + instrument_type, + n_units=len(units), + parent_body=parent["body"], + ), + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (thin article rows replaced from the parent law)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + elif not skip_body_split: for instrument_id, parent in law_map.items(): body = parent["body"] if not body: - report["drops"]["empty_body"] += 1 - if len(report["drop_samples"]["empty_body"]) < 20: - report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] - units = split_structured_units(body, language=parent["language"]) + units = _thicken_units( + split_structured_units(body, language=parent["language"]) + ) if units: report["unit"] = "structured" + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) for unit in units: entries.append( _base_record( - record_type=unit.kind if unit.kind in {"article", "section"} else "article", + record_type=_unit_record_type( + unit, + instrument_type, + n_units=len(units), + parent_body=body, + ), source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, @@ -572,49 +1073,11 @@ def build_corpus( }, ) ) - continue - entries.append( - _base_record( - record_type="law", - source_dataset=source_dataset, - source_revision=source_revision, - instrument_id=instrument_id, - instrument_title=parent["instrument_title"], - law_cid=parent["law_cid"], - article_number="", - article_title="", - body=body, - jurisdiction=parent["jurisdiction"], - language=parent["language"], - source_url=parent["source_url"], - snapshot_date=_snapshot_date(parent["row"], meta, source_meta), - coverage=_coverage_from( - parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback - ), - license_expr=parent["license"], - collector=_collector(meta, source_dataset), - source_id=instrument_id, - extra={ - "eli": parent["eli"], - "identifier": parent["identifier"], - "official_identifier": parent["official_identifier"], - "source_type": parent["source_type"], - "country": parent["country"], - "law_status": parent["law_status"], - "parent_law_id": "", - "article_id": "", - **_hierarchy_fields( - parent["instrument_title"], body, "", language=parent["language"] - ), - }, - ) - ) entries.sort( key=lambda r: ( r["instrument_id"], - r.get("article_number") or "", - r["source_id"], + article_sort_key(r.get("article_number") or "", r["source_id"]), ) ) n_before = len(entries) @@ -639,6 +1102,20 @@ def build_corpus( raise SchemaError("Duplicate entry_cid remained after dedupe") report["n_before_dedupe"] = n_before report["n_out"] = int(len(df)) + if not df.empty and "record_type" in df.columns: + n_law_rows = int((df["record_type"] == "law").sum()) + n_child_rows = int(df["record_type"].isin(["article", "section"]).sum()) + report["n_law_rows"] = n_law_rows + report["n_child_rows"] = n_child_rows + report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows + if n_law_rows and n_child_rows: + report["unit"] = ( + "law+structured" if report.get("unit") == "structured" else "law+article" + ) + elif n_law_rows: + report["unit"] = "law" + elif n_child_rows: + report["unit"] = "article" report["n_dropped_total"] = ( report["drops"]["empty_body"] + report["drops"]["missing_instrument"] diff --git a/country_laws_ir/normalize_loop.py b/country_laws_ir/normalize_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e66ce5a879e8c2303e75a867e60281cde48d7e --- /dev/null +++ b/country_laws_ir/normalize_loop.py @@ -0,0 +1,621 @@ +"""Improve the row normalizer, then let that script normalize every row. + +``scan`` and ``apply`` only call ``normalize_legal_text``. They do not import +the LLM router, so one subprocess per country does not boot a model. + +``improve`` imports ``llm_router`` once. Each pass sends a short batch of +lines the current script still leaves in place. The model proposes whole-line +patterns. A pattern is stored only when it matches one of those lines, misses +every held-out legal sentence, and the script then actually drops the line. +Accepted patterns live in ``data/learned_line_patterns.json`` and are applied +by the same script that normalizes the rows. The model never rewrites a row. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +from collections import Counter +from concurrent.futures import ProcessPoolExecutor, as_completed +from pathlib import Path +from typing import Any, Callable, Sequence + +from .catalog import EXCLUDED_SLUGS +from .structure import learned_patterns_path, normalize_legal_text + +GenerateText = Callable[[str], str] + +# Sentences the learned rules must not delete. Whole-line patterns that +# full-match any of these are discarded. +KEEP_LINES = ( + "Article 1 The present Act applies throughout the territory and binds every person.", + "The court in Malawi shall apply the Public Roads Act throughout the territory.", + "2. Amendment of section 5 of Cap. 122A", + "publié au Journal Officiel et entre en vigueur sur tout le territoire.", + "10 dicembre 1948", + "Quarta-Feira de Cinzas continua a ser feriado nacional.", + "Phone: +1 202 555 0100 is the number appointed under this section.", + "Troubleshoot faulty system.", + "100 GENERAL PROVISIONS", + "applicable rule applies throughout the territory.", + "The register is published at www.example.com for public inspection under this Act.", + "بسم الله الرحمن الرحيم", + "Done at Brussels, 25 June 1999.", + "2", + "10", + "published in the Gazette.", + "Gazetted 1 October 2009", + "Lycée : séries ES, L et S", + "au Journal Officiel", + "Subs. ibid., for “local official Gazette”.", + "(a) books (excluding printed music and periodicals) ;", + "Act 19 Copyright and Neighbouring Rights Act 2006", +) + +# One local-model window is 1024 tokens. Keep the prompt well under that. +PROMPT_CHAR_BUDGET = 1600 +_PROMPT_PREFIX = ( + "These lines survived legal-text normalization. " + 'Propose JSON only: {"line_patterns": ["^...$"]}. ' + "Each pattern must match one whole chrome line (page header, site footer, " + "printer stamp) and must not match a legal sentence. Do not write legal text. " + 'If none are safe, return {"line_patterns": []}.\n' +) + + +def cache_packs(cache_dir: Path, slug: str | None = None) -> list[tuple[str, Path]]: + packs: list[tuple[str, Path]] = [] + for path in sorted(cache_dir.glob("*_corpus.parquet")): + name = path.name[: -len("_corpus.parquet")] + if name in EXCLUDED_SLUGS or not name: + continue + if slug is not None and name != slug: + continue + packs.append((name, path)) + return packs + + +_HEADING_LINE = re.compile( + r"(?i)^(article|art\.|section|chapter|part|subtopic|§)\b" +) +_CHROME_HINT = re.compile( + r"(?i)(translated|serial number|copyright|gazette|https?://|www\.|" + r"\bpage\b|printed|journal officiel|série|series\b)" +) +# Repeated lines that are still the law, not a banner. The router must not see them. +_PROVISION_LINE = re.compile( + r"(?i)(publi[eé]|lycée|lycee|newspaper|days after|série cei|série en |" + r"\bshall\b|\bmust\b|inserted sig|the gazette\.$|in the gazette\.$|" + r"\bgazetted\b|\bau journal officiel\b|subs\.\s*ibid|" + r"excluding printed|whether or not printed|neighbouring rights|" + r"série de classe|note de bas de page|communaut[eé]s europ)" +) + + +def scan_pack(path: Path, *, sample_lines: int = 40) -> dict[str, Any]: + """Count rows and keep the repeated short lines the script did not remove.""" + import pyarrow.parquet as pq + + pf = pq.ParquetFile(path) + if "body" not in set(pf.schema_arrow.names): + raise ValueError(f"{path.name} has no body column") + short: Counter[str] = Counter() + n = 0 + n_changed = 0 + n_unstable = 0 + for batch in pf.iter_batches(batch_size=512, columns=["body"]): + for body in batch.column("body").to_pylist(): + if body is None: + continue + original = body if isinstance(body, str) else str(body) + n += 1 + normalized = normalize_legal_text(original) + if normalized != original: + n_changed += 1 + if normalize_legal_text(normalized) != normalized: + n_unstable += 1 + for line in normalized.splitlines(): + stripped = line.strip() + if not stripped or len(stripped) > 60 or _HEADING_LINE.match(stripped): + continue + if not _CHROME_HINT.search(stripped): + continue + if stripped in short or len(short) < 20000: + short[stripped] += 1 + leftovers = [ + {"line": line, "count": count} + for line, count in short.most_common(sample_lines) + if count >= 3 + ] + return { + "n": n, + "n_changed": n_changed, + "n_unstable": n_unstable, + "leftovers": leftovers, + } + + +def apply_pack(path: Path, out_path: Path) -> dict[str, Any]: + """Rewrite every body with the current script. No model is loaded.""" + import pyarrow as pa + import pyarrow.parquet as pq + + pf = pq.ParquetFile(path) + if "body" not in set(pf.schema_arrow.names): + raise ValueError(f"{path.name} has no body column") + out_path.parent.mkdir(parents=True, exist_ok=True) + tmp = out_path.with_suffix(out_path.suffix + ".partial") + writer = pq.ParquetWriter(tmp, pf.schema_arrow) + n = 0 + n_changed = 0 + try: + for batch in pf.iter_batches(batch_size=256): + bodies = batch.column("body").to_pylist() + rewritten: list[Any] = [] + for body in bodies: + if body is None: + rewritten.append(None) + continue + original = body if isinstance(body, str) else str(body) + n += 1 + normalized = normalize_legal_text(original) + if normalized != original: + n_changed += 1 + rewritten.append(normalized) + index = batch.schema.get_field_index("body") + arrays = [batch.column(i) for i in range(batch.num_columns)] + arrays[index] = pa.array(rewritten, type=batch.schema.field("body").type) + writer.write_batch(pa.record_batch(arrays, schema=batch.schema)) + except Exception: + writer.close() + tmp.unlink(missing_ok=True) + raise + writer.close() + tmp.replace(out_path) + return {"n": n, "n_changed": n_changed} + + +def _safe_pattern(pattern: str) -> bool: + if not isinstance(pattern, str) or not pattern.startswith("^") or not pattern.endswith("$"): + return False + if not 4 <= len(pattern) <= 180: + return False + if len(re.findall(r"\.\*|\.\+", pattern)) > 2: + return False + if re.search(r"\([^)]*[+*][^)]*\)[+*{]", pattern): + return False + try: + re.compile(pattern, re.IGNORECASE) + except re.error: + return False + return True + + +def _blocked_candidate(line: str) -> bool: + """Publication sentences, headings, and mid-sentence fragments stay in the row.""" + if _PROVISION_LINE.search(line) or _HEADING_LINE.match(line): + return True + if len(line) <= 3: + return True + return line.endswith((",", ";", " or", " and")) + + +def accept_line_patterns( + proposals: Sequence[str], + leftovers: Sequence[str], + existing: Sequence[str] = (), + *, + must_hit: Sequence[str] | None = None, +) -> list[str]: + """Keep a proposal only when it hits a leftover and misses every held-out sentence.""" + accepted: list[str] = [] + seen = set(existing) + pool = [line.strip() for line in leftovers if line and str(line).strip()] + required = pool if must_hit is None else [line.strip() for line in must_hit if line and str(line).strip()] + for pattern in proposals: + if pattern in seen or not _safe_pattern(pattern): + continue + compiled = re.compile(pattern, re.IGNORECASE) + if any(compiled.fullmatch(line.strip()) for line in KEEP_LINES): + continue + if compiled.fullmatch("2") or compiled.fullmatch("10"): + continue + hits = [line for line in pool if compiled.fullmatch(line)] + if not hits: + continue + if required and not any(compiled.fullmatch(line) for line in required): + continue + if any(_blocked_candidate(line) for line in hits): + continue + accepted.append(pattern) + seen.add(pattern) + return accepted + + +def line_still_present(line: str) -> bool: + """True when the current script still leaves this exact line in place.""" + probe = ( + line + + "\nArticle 1 The present Act applies throughout the territory and binds every person." + ) + normalized = normalize_legal_text(probe) + return line in normalized.splitlines() + + +def router_candidates( + leftovers: Sequence[dict[str, Any]], + limit: int = 40, + *, + skip: set[str] | None = None, + presence: dict[str, bool] | None = None, +) -> list[dict[str, Any]]: + """Banners the script still keeps, in leftover order, excluding provision lines.""" + chosen: list[dict[str, Any]] = [] + seen: set[str] = set() + held = skip or set() + known = presence if presence is not None else {} + for item in leftovers: + line = str(item.get("line") or "").strip() + if not line or line in seen or line in held: + continue + if line not in known: + known[line] = line_still_present(line) + if not known[line] or _blocked_candidate(line): + continue + seen.add(line) + chosen.append({"line": line, "count": int(item.get("count") or 0)}) + if len(chosen) >= limit: + break + return chosen + + +def _cluster_key(line: str) -> str: + shape = re.sub(r"\d+", "0", line.casefold()) + shape = re.sub(r"[^\w\s]+", " ", shape, flags=re.UNICODE) + shape = re.sub(r"\s+", " ", shape).strip() + return " ".join(shape.split()[:4]) + + +def largest_cluster(candidates: Sequence[dict[str, Any]], limit: int) -> list[dict[str, Any]]: + """The repeated family with the highest total count, capped to one prompt.""" + groups: dict[str, list[dict[str, Any]]] = {} + for item in candidates: + groups.setdefault(_cluster_key(str(item["line"])), []).append(item) + best = max(groups.values(), key=lambda group: sum(int(item["count"]) for item in group)) + best.sort(key=lambda item: int(item["count"]), reverse=True) + return best[:limit] + + +_BARE_PATTERN = re.compile(r"\^[^\n]{1,180}\$") + + +def _patterns_from_model_text(raw: str) -> list[str]: + """Read whole-line patterns from JSON, or from a model that skipped the JSON.""" + start, end = raw.find("{"), raw.rfind("}") + if start >= 0 and end > start: + try: + payload = json.loads(raw[start : end + 1]) + except json.JSONDecodeError: + payload = None + found = payload.get("line_patterns") if isinstance(payload, dict) else None + if isinstance(found, list): + return [item for item in found if isinstance(item, str)] + seen: set[str] = set() + bare: list[str] = [] + for item in _BARE_PATTERN.findall(raw): + if item not in seen and item != "^...$": + seen.add(item) + bare.append(item) + return bare + + +def propose_line_patterns( + leftovers: Sequence[dict[str, Any]], + generate_text: GenerateText, + *, + char_budget: int = PROMPT_CHAR_BUDGET, +) -> list[str]: + """One router call. The model proposes whole-line patterns, not statute text.""" + if not leftovers: + return [] + body: list[str] = [] + used = len(_PROMPT_PREFIX) + for item in leftovers: + row = f"- {item['count']}× {item['line']}\n" + if used + len(row) > char_budget: + break + body.append(row) + used += len(row) + if not body: + room = max(0, char_budget - len(_PROMPT_PREFIX) - 16) + snippet = str(leftovers[0]["line"])[:room] + body.append(f"- {leftovers[0]['count']}× {snippet}\n") + raw = str(generate_text(_PROMPT_PREFIX + "".join(body))) + return _patterns_from_model_text(raw) + + +def load_learned_patterns() -> list[str]: + path = learned_patterns_path() + if not path.is_file(): + return [] + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return [] + return [item for item in payload.get("patterns") or [] if isinstance(item, str)] + + +def save_learned_patterns(patterns: Sequence[str]) -> None: + path = learned_patterns_path() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps({"patterns": list(patterns)}, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + # The structure cache keys on mtime; the write updates it. + + +def unresolved_path(report_dir: Path) -> Path: + return report_dir / "_unresolved.json" + + +def load_unresolved(report_dir: Path) -> set[str]: + path = unresolved_path(report_dir) + if not path.is_file(): + return set() + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return set() + return {item.strip() for item in payload.get("lines") or [] if isinstance(item, str) and item.strip()} + + +def save_unresolved(report_dir: Path, lines: set[str]) -> None: + path = unresolved_path(report_dir) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps({"lines": sorted(lines)}, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + + +def collect_leftovers(report_dir: Path) -> list[dict[str, Any]]: + """Merge per-country residual lines. Counts for the same line are summed.""" + counts: Counter[str] = Counter() + if not report_dir.is_dir(): + return [] + for path in sorted(report_dir.glob("*.json")): + if path.name.startswith("_"): + continue + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + for item in payload.get("leftovers") or []: + if isinstance(item, dict) and isinstance(item.get("line"), str): + line = item["line"].strip() + if line: + counts[line] += int(item.get("count") or 0) + return [{"line": line, "count": count} for line, count in counts.most_common()] + + +def improve_from_reports( + report_dir: Path, + generate_text: GenerateText, + *, + max_passes: int = 40, + batch_size: int = 12, + char_budget: int = PROMPT_CHAR_BUDGET, + on_pass: Callable[[dict[str, Any]], None] | None = None, + reset_unresolved: bool = False, +) -> dict[str, Any]: + """Ask the router, one short batch at a time, for rules the script can apply. + + A batch is one repeated family. Patterns that do not remove a line, or that + also match a publication sentence, are not stored. Families the model cannot + safely pattern are remembered so the next batch is a different family. + """ + merged = collect_leftovers(report_dir) + pool_lines = [str(item["line"]) for item in merged] + presence: dict[str, bool] = {} + skip = set() if reset_unresolved else load_unresolved(report_dir) + existing = load_learned_patterns() + accepted_all: list[str] = [] + removed_lines: list[str] = [] + proposed = 0 + passes = 0 + + def _emit(row: dict[str, Any]) -> None: + if on_pass is not None: + on_pass(row) + + for pass_no in range(1, max(1, max_passes) + 1): + pending = router_candidates(merged, limit=100_000, skip=skip, presence=presence) + if not pending: + break + batch = largest_cluster(pending, batch_size) + cluster = _cluster_key(str(batch[0]["line"])) + _emit({ + "event": "prompt", + "pass": pass_no, + "cluster": cluster, + "batch_id": hashlib.sha256(cluster.encode("utf-8")).hexdigest()[:8], + "candidates": len(batch), + "lines": [str(item["line"]) for item in batch], + }) + try: + proposals = propose_line_patterns(batch, generate_text, char_budget=char_budget) + except Exception as exc: + passes += 1 + _emit({"event": "pass", "pass": pass_no, "cluster": cluster, "error": str(exc)}) + break + proposed += len(proposals) + accepted = accept_line_patterns(proposals, pool_lines, existing, must_hit=[str(item["line"]) for item in batch]) + before = list(existing) + kept: list[str] = [] + removed_now: list[str] = [] + if accepted: + save_learned_patterns([*before, *accepted]) + for pattern in accepted: + compiled = re.compile(pattern, re.IGNORECASE) + hits = [line for line in pool_lines if compiled.fullmatch(line)] + dropped = [line for line in hits if not line_still_present(line)] + if not dropped: + continue + kept.append(pattern) + removed_now.extend(dropped) + if kept != accepted: + save_learned_patterns([*before, *kept]) + if not kept: + skip.update(str(item["line"]) for item in batch) + else: + for line in removed_now: + presence[line] = False + skip.discard(line) + if line not in removed_lines: + removed_lines.append(line) + existing = [*before, *kept] + accepted_all.extend(kept) + passes += 1 + _emit({ + "event": "pass", + "pass": pass_no, + "cluster": cluster, + "proposed": len(proposals), + "accepted": kept, + "removed": len(removed_now), + }) + + save_unresolved(report_dir, skip) + withheld = 0 + for item in merged: + line = str(item["line"]) + if line not in presence: + presence[line] = line_still_present(line) + if presence[line] and _blocked_candidate(line): + withheld += 1 + remaining = router_candidates(merged, limit=100_000, skip=skip, presence=presence) + return { + "proposed": proposed, + "accepted": accepted_all, + "leftover_lines": len(merged), + "removed": len(removed_lines), + "removed_lines": removed_lines[:40], + "unresolved": len(skip), + "withheld": withheld, + "remaining": len(remaining), + "passes": passes, + } + + +def worker_count(requested: int | None) -> int: + if requested is not None: + return max(1, int(requested)) + return max(1, os.cpu_count() or 1) + + +def _scan_job(job: tuple[str, str, str]) -> dict[str, Any]: + slug, path, report_dir = job + stats = scan_pack(Path(path)) + write_scan(Path(report_dir), slug, stats) + return {"slug": slug, "n": stats["n"], "n_changed": stats["n_changed"], "n_unstable": stats["n_unstable"], "leftovers": len(stats["leftovers"])} + + +def _apply_job(job: tuple[str, str, str]) -> dict[str, Any]: + slug, path, out_dir = job + out_path = Path(out_dir) / Path(path).name + stats = apply_pack(Path(path), out_path) + return {"slug": slug, "out": str(out_path), **stats} + + +def run_parallel( + jobs: Sequence[tuple[str, str, str]], + worker, + workers: int | None, + *, + progress_path: Path | None = None, + on_done: Callable[[dict[str, Any]], None] | None = None, +) -> list[dict[str, Any]]: + """One process per batch of countries. Each country writes its own file. + + Progress is recorded in the parent as each country finishes, so a later + run can skip those slugs. + """ + count = worker_count(workers) + + def _finish(row: dict[str, Any]) -> dict[str, Any]: + if progress_path is not None: + append_progress(progress_path, row) + if on_done is not None: + on_done(row) + return row + + if count == 1 or len(jobs) <= 1: + return [_finish(worker(job)) for job in jobs] + rows: list[dict[str, Any]] = [] + with ProcessPoolExecutor(max_workers=min(count, len(jobs))) as pool: + futures = {pool.submit(worker, job): job[0] for job in jobs} + for future in as_completed(futures): + slug = futures[future] + try: + row = future.result() + except Exception as exc: + row = {"slug": slug, "error": str(exc)} + rows.append(_finish(row)) + rows.sort(key=lambda row: str(row.get("slug") or "")) + return rows + + +def write_scan(report_dir: Path, slug: str, stats: dict[str, Any]) -> Path: + report_dir.mkdir(parents=True, exist_ok=True) + path = report_dir / f"{slug}.json" + tmp = path.with_suffix(".json.tmp") + tmp.write_text(json.dumps({"slug": slug, **stats}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + tmp.replace(path) + return path + + +def scan_done(report_dir: Path, slug: str) -> bool: + path = report_dir / f"{slug}.json" + if not path.is_file(): + return False + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + return isinstance(payload.get("n"), int) + + +def apply_done(out_dir: Path, slug: str) -> bool: + path = out_dir / f"{slug}_corpus.parquet" + if not path.is_file() or path.stat().st_size < 12: + return False + with path.open("rb") as handle: + if handle.read(4) != b"PAR1": + return False + handle.seek(-4, 2) + return handle.read(4) == b"PAR1" + + +def append_progress(path: Path, row: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + handle.flush() + + +def load_generate_text() -> GenerateText: + """Import the router once per process. Scan and apply never call this.""" + from ipfs_datasets_py.llm_router import generate_text + + return generate_text + + +def default_paths(root: Path) -> dict[str, Path]: + return { + "cache": root / "cache", + "reports": root / "reports" / "residuals", + "out": root / "llm-normalized", + } diff --git a/country_laws_ir/package.py b/country_laws_ir/package.py index 05c6be4495ff4b698be8ac375e66f934a3b779b0..affc176233dc4ec89a00a986556d2f837d4579e8 100644 --- a/country_laws_ir/package.py +++ b/country_laws_ir/package.py @@ -253,7 +253,9 @@ def package_release( return file_descriptor(path, f"indexes/{name}") hub_id = target_repo(country["slug"]) - edge_types = graph["stats"].get("edge_types") or [ + bm25_stats = bm25.get("stats") if isinstance(bm25.get("stats"), dict) else {} + graph_stats = graph.get("stats") if isinstance(graph.get("stats"), dict) else {} + edge_types = graph_stats.get("edge_types") or [ "HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", @@ -270,10 +272,20 @@ def package_release( "dataset_revision": source_meta["source_revision"], "country": country, "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.", - "bm25": {k: bm25["stats"][k] for k in ( - "k1", "b", "title_weight", "body_weight", "average_document_length", - "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard", - )}, + "bm25": { + k: bm25_stats.get(k) + for k in ( + "k1", + "b", + "title_weight", + "body_weight", + "average_document_length", + "tokenizer", + "max_query_terms", + "posting_rows_per_record", + "terms_per_shard", + ) + }, "counts": counts, "parquet": { "compression": "zstd", @@ -361,7 +373,17 @@ def package_release( if extra_manifest: manifest.update(extra_manifest) (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - _write_readme(out, country, source_meta, counts, bm25["stats"], graph["stats"], vectors["stats"], hub_id) + _write_readme( + out, + country, + source_meta, + counts, + bm25_stats, + graph_stats, + vectors.get("stats") if isinstance(vectors.get("stats"), dict) else {}, + hub_id, + normalization_report=normalization_report, + ) _write_gitattributes(out) _write_dataset_configs(out) return manifest @@ -395,6 +417,55 @@ def _write_gitattributes(out: Path) -> None: ) +def _size_category(n: int) -> str: + if n < 1000: + return "n<1K" + if n < 10_000: + return "1K10M" + + +def _card_languages(normalization_report: dict[str, Any] | None) -> list[str]: + if not normalization_report: + return [] + seen: list[str] = [] + majority = str(normalization_report.get("document_language_majority") or "").strip() + breakdown = normalization_report.get("language_breakdown") or {} + ordered = [] + if majority: + ordered.append(majority) + ordered.extend( + sorted( + (str(k) for k in breakdown if k), + key=lambda k: -int(breakdown.get(k) or 0), + ) + ) + for raw in ordered: + lang = str(raw).strip().lower().replace("_", "-").split("-")[0] + if lang and lang not in seen and lang not in {"und", "none", "null"}: + seen.append(lang) + if len(seen) >= 8: + break + return seen + + +def _adj_glob(out: Path, direction: str) -> str: + aliases = { + "out": ("out", "outgoing"), + "in": ("in", "incoming"), + } + for name in aliases.get(direction, (direction,)): + if (out / "data" / "graph" / "adjacency" / name).is_dir(): + return f"data/graph/adjacency/{name}/*.parquet" + return f"data/graph/adjacency/{direction}/*.parquet" + + def _write_readme( out: Path, country: dict[str, Any], @@ -404,67 +475,49 @@ def _write_readme( graph_stats: dict[str, Any], vector_stats: dict[str, Any], hub_id: str, + normalization_report: dict[str, Any] | None = None, ) -> None: slug = country["slug"] - name = country["name"] - src = source_meta["source_dataset"] - rev = source_meta["source_revision"] - vec_status = vector_stats.get("status", "embedded") + name = country.get("name") or slug + src = source_meta.get("source_dataset") or "" + rev = source_meta.get("source_revision") or "" + vec_status = (vector_stats or {}).get("status", "embedded") + n_docs = int((counts or {}).get("corpus_rows") or 0) + languages = _card_languages(normalization_report) + import yaml + + card = { + "license": "other", + "task_categories": ["text-retrieval"], + "tags": [ + "legal", + "law", + "graphrag", + "bm25", + "research", + "not-legal-advice", + str(slug), + ], + "pretty_name": f"{name} laws IR (CID-keyed GraphRAG)", + "size_categories": [_size_category(n_docs)], + "configs": [ + {"config_name": "corpus", "data_files": [{"split": "train", "path": "data/corpus/*.parquet"}]}, + {"config_name": "bm25_documents", "data_files": [{"split": "train", "path": "data/bm25/documents/*.parquet"}]}, + {"config_name": "bm25_postings", "data_files": [{"split": "train", "path": "data/bm25/postings/*.parquet"}]}, + {"config_name": "bm25_keyword_index", "data_files": [{"split": "train", "path": "indexes/bm25_keyword_shards.parquet"}]}, + {"config_name": "vectors", "data_files": [{"split": "train", "path": "data/vectors/*.parquet"}]}, + {"config_name": "vector_meta_index", "data_files": [{"split": "train", "path": "indexes/vector_chunks.parquet"}]}, + {"config_name": "graph_nodes", "data_files": [{"split": "train", "path": "data/graph/nodes/*.parquet"}]}, + {"config_name": "graph_edges", "data_files": [{"split": "train", "path": "data/graph/edges/*.parquet"}]}, + {"config_name": "graph_outgoing_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "out")}]}, + {"config_name": "graph_incoming_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "in")}]}, + ], + } + if languages: + card["language"] = languages + front = yaml.safe_dump(card, sort_keys=False, allow_unicode=True) text = f"""--- -license: other -task_categories: -- text-retrieval -tags: -- legal -- law -- graphrag -- bm25 -- research -- not-legal-advice -- {slug} -pretty_name: {name} laws IR (CID-keyed GraphRAG) -configs: -- config_name: corpus - data_files: - - split: train - path: data/corpus/*.parquet -- config_name: bm25_documents - data_files: - - split: train - path: data/bm25/documents/*.parquet -- config_name: bm25_postings - data_files: - - split: train - path: data/bm25/postings/*.parquet -- config_name: bm25_keyword_index - data_files: - - split: train - path: indexes/bm25_keyword_shards.parquet -- config_name: vectors - data_files: - - split: train - path: data/vectors/*.parquet -- config_name: vector_meta_index - data_files: - - split: train - path: indexes/vector_chunks.parquet -- config_name: graph_nodes - data_files: - - split: train - path: data/graph/nodes/*.parquet -- config_name: graph_edges - data_files: - - split: train - path: data/graph/edges/*.parquet -- config_name: graph_outgoing_adjacency - data_files: - - split: train - path: data/graph/adjacency/outgoing/*.parquet -- config_name: graph_incoming_adjacency - data_files: - - split: train - path: data/graph/adjacency/incoming/*.parquet ---- +{front}--- # {name} legislation IR (CID-keyed sparse GraphRAG) @@ -484,14 +537,14 @@ Target Hub id (packaging metadata only): `{hub_id}`. | Field | Value | | --- | --- | -| Laws (corpus units) | {counts['n_laws']} | -| Articles (corpus units) | {counts['n_articles']} | -| Canonical docs | {counts['corpus_rows']} | -| BM25 terms | {counts['bm25_terms']} | -| BM25 postings | {counts['bm25_postings']} | -| Graph nodes | {counts['graph_nodes']} | -| Graph edges | {counts['graph_edges']} | -| Vectors | {counts['vector_rows']} × {vector_stats['dimension']}-d `{vector_stats['model_name']}` ({vec_status}) | +| Laws (corpus units) | {(counts or {}).get('n_laws', 0)} | +| Articles (corpus units) | {(counts or {}).get('n_articles', 0)} | +| Canonical docs | {(counts or {}).get('corpus_rows', 0)} | +| BM25 terms | {(counts or {}).get('bm25_terms', 0)} | +| BM25 postings | {(counts or {}).get('bm25_postings', 0)} | +| Graph nodes | {(counts or {}).get('graph_nodes', 0)} | +| Graph edges | {(counts or {}).get('graph_edges', 0)} | +| Vectors | {(counts or {}).get('vector_rows', 0)} × {(vector_stats or {}).get('dimension', 384)}-d `{(vector_stats or {}).get('model_name', 'thenlper/gte-small')}` ({vec_status}) | ## Canonical fields @@ -825,7 +878,7 @@ def package_release_sequential( "dataset_revision": source_meta["source_revision"], "country": country, "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.", - "bm25": {k: bm25_stats[k] for k in ( + "bm25": {k: (bm25_stats or {}).get(k) for k in ( "k1", "b", "title_weight", "body_weight", "average_document_length", "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard", ) if k in bm25_stats}, @@ -900,7 +953,17 @@ def package_release_sequential( (out / "manifest.json").write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) - _write_readme(out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id) + _write_readme( + out, + country, + source_meta, + counts, + bm25_stats, + gstats, + vstats, + hub_id, + normalization_report=normalization_report, + ) _write_gitattributes(out) _write_dataset_configs(out) checkpoint("package_seq_done") diff --git a/country_laws_ir/profiles.py b/country_laws_ir/profiles.py index 44c3d6a91b3c1bf18ede24a585e0409d7ca37518..d9066fbfad1ba3e487d3a99ef15a8e3a0ff258e2 100644 --- a/country_laws_ir/profiles.py +++ b/country_laws_ir/profiles.py @@ -27,13 +27,23 @@ _add("en", "title", "title") _add("en", "chapter", "chapter") _add("en", "part", "part") _add("en", "article", "article") -_add("en", "section", "section", "sec.") +_add("en", "section", "section", "sec.", "rule", "regulation", "schedule", "annex", "appendix") +_add("fr", "section", "annexe") +_add("es", "section", "anexo") +_add("de", "section", "anlage") +_add("nl", "section", "bijlage") +_add("it", "section", "allegato") +_add("pl", "section", "załącznik") +_add("sv", "section", "bilaga") +_add("fi", "section", "liite") +_add("cs", "section", "příloha") +_add("pt", "section", "anexo") _add("fr", "title", "titre") _add("fr", "chapter", "chapitre") _add("fr", "part", "partie") _add("fr", "article", "article") -_add("fr", "section", "section") +_add("fr", "section", "section", "paragraphe") _add("de", "title", "titel") _add("de", "chapter", "kapitel") @@ -52,6 +62,7 @@ _add("es", "chapter", "capítulo", "capitulo") _add("es", "part", "parte") _add("es", "article", "artículo", "articulo") _add("es", "section", "sección", "seccion") +_add("es", "article", "disposición", "disposicion") _add("pt", "title", "título", "titulo") _add("pt", "chapter", "capítulo", "capitulo") @@ -66,26 +77,222 @@ _add("it", "article", "articolo") _add("it", "section", "sezione") _add("el", "article", "άρθρο", "αρθρο") -_add("hu", "article", "szakasz") +_add("el", "chapter", "κεφάλαιο") +_add("hu", "article", "szakasz", "cikk") _add("cs", "article", "článek") +_add("cs", "chapter", "kapitola") +_add("cs", "section", "odstavec", "odst.") _add("sk", "article", "článok") -_add("sl", "article", "član") +_add("sl", "article", "člen") _add("nb", "article", "artikkel") -_add("sv", "article", "artikel") +_add("sv", "article", "paragraf") +_add("fi", "article", "pykälä") +_add("fi", "chapter", "luku") +_add("is", "article", "grein") +_add("lv", "article", "pants") +_add("lv", "chapter", "nodaļa") +_add("et", "article", "paragrahv") +_add("et", "chapter", "peatükk") _add("pl", "article", "artykuł", "artykul") _add("ro", "article", "articolul", "articol") -_add("zh", "article", "条") -_add("ar", "article", "مادة", "المادة") +_add("mt", "article", "artikolu") +_add("zh", "article", "条", "條") +_add("ar", "article", "مادة", "المادة", "الماده", "املادة", "املاده") +_add("ar", "chapter", "الباب") +_add("ar", "part", "الكتاب") +_add("ar", "section", "الفصل", "ملحق", "الفرع") +_add("fa", "article", "ماده") +_add("fa", "section", "تبصره", "بند") _add("ja", "article", "条") +_add("ko", "article", "조") +_add("he", "article", "סעיף") +_add("he", "chapter", "פרק") +_add("he", "part", "חלק") +_add("he", "section", "סימן", "תוספת", "תקנה") +_add("th", "article", "มาตรา") +_add("th", "chapter", "หมวด") +_add("th", "section", "ข้อ", "วรรค") +_add("hi", "article", "धारा") +_add("bn", "article", "ধারা") +_add("ru", "article", "статья") +_add("ru", "chapter", "глава") +_add("ru", "title", "раздел") +_add("uk", "article", "стаття") +_add("bg", "article", "член", "чл") +_add("mk", "article", "член") +_add("sr", "article", "члан") +_add("hr", "article", "članak") +_add("hr", "chapter", "poglavlje") +_add("bs", "article", "članak") +_add("sq", "article", "neni") +_add("tr", "article", "madde") +_add("az", "article", "maddə") +_add("uz", "article", "модда") +_add("mn", "article", "зүйл") +_add("lo", "article", "ມາດຕາ") +_add("id", "article", "pasal") +_add("id", "chapter", "bab") +_add("ms", "article", "seksyen") +_add("ms", "part", "bahagian") +_add("lt", "article", "straipsnis") +_add("ta", "article", "பிரிவு") +_add("el", "part", "μέρος") +_add("el", "section", "παράγραφος") +_add("uk", "title", "розділ") +_add("zh", "chapter", "章") +_add("ja", "chapter", "章") +_add("ko", "chapter", "장") +_add("vi", "article", "điều") +_add("vi", "chapter", "chương") +_add("ka", "article", "მუხლი") +_add("hy", "article", "հոդված") +_add("am", "article", "አንቀጽ") +_add("km", "article", "មាត្រា") +_add("my", "article", "ပုဒ်မ") +_add("ne", "article", "दफा") +_add("si", "article", "වගන්තිය") +_add("kk", "article", "бап") +_add("uz", "article", "modda") +_add("be", "article", "артыкул") +_add("ky", "article", "берене") +_add("ur", "article", "دفعہ") +_add("so", "article", "qodob", "qodobka") +_add("ga", "article", "airteagal") +_add("cy", "article", "erthygl") +_add("fil", "article", "artikulo") +_add("fil", "section", "seksyon") +_add("fil", "chapter", "kabanata") +_add("id", "part", "bagian") +_add("vi", "part", "mục") +_add("sw", "part", "sehemu") +_add("ht", "article", "atik") +_add("eu", "article", "artikulua") +_add("da", "section", "stk") +_add("nb", "section", "ledd") +_add("de", "section", "absatz") +_add("es", "section", "apartado") +_add("it", "section", "comma") +_add("tr", "section", "fıkra") +_add("hr", "section", "stavak") +_add("bg", "section", "ал") +_add("te", "article", "ప్రకరణము", "ప్రకరణ") +_add("kn", "article", "ಪ್ರಕರಣ") +_add("gu", "article", "કલમ") +_add("pa", "article", "ਧਾਰਾ") +_add("ml", "article", "വകുപ്പ്") +_add("th", "title", "ลักษณะ") +_add("zh", "part", "编") +_add("ja", "part", "編") +_add("ko", "part", "편") +_add("tg", "article", "модда") +_add("sw", "article", "kifungu") +_add("ca", "article", "article") +_add("ca", "chapter", "capítol", "capitol") +_add("ca", "title", "títol", "titol") +_add("ca", "section", "secció", "seccio") +_add("pl", "chapter", "rozdział") +_add("pl", "title", "dział") +_add("ro", "chapter", "capitolul") +_add("ro", "title", "titlul") +_add("it", "chapter", "capo") +_add("cs", "chapter", "hlava") +_add("sk", "chapter", "hlava") +_add("es", "part", "libro") +_add("sv", "chapter", "kap") +_add("km", "chapter", "ជំពូក") +_add("lo", "part", "ພາກ") +_add("my", "chapter", "အခန်း") +_add("ka", "chapter", "თავი") +_add("hy", "chapter", "գլուխ") +_add("am", "chapter", "ምዕራፍ") +_add("sq", "chapter", "kreu") +_add("hu", "chapter", "fejezet") +_add("tr", "chapter", "bölüm") +_add("az", "chapter", "fəsil") +_add("lt", "chapter", "skyrius") +_add("is", "chapter", "kafli") +_add("ga", "chapter", "caibidil") +_add("cy", "chapter", "pennod") +_add("mt", "chapter", "kapitolu") +_add("ht", "chapter", "chapit") +_add("sw", "chapter", "sura") +_add("nb", "chapter", "kapittel") +_add("ha", "chapter", "sashe") +_add("mg", "chapter", "andiany") +_add("mi", "part", "wāhanga", "wahanga") +_add("sm", "part", "vaega") +_add("to", "article", "kupu") +_add("fj", "chapter", "wase") +_add("tpi", "part", "hap") +_add("fo", "chapter", "kapittul") +_add("bi", "article", "atikol") +_add("rw", "article", "ingingo") +_add("zu", "chapter", "isigaba") +_add("xh", "chapter", "icandelo") +_add("st", "part", "karolo") +_add("tn", "chapter", "kgaolo") +_add("sn", "part", "chikamu") +_add("ny", "article", "ndime") +_add("ku", "part", "beş") +_add("ky", "chapter", "бөлүм") +_add("tg", "chapter", "боби") +_add("yo", "article", "abala") +_add("yo", "chapter", "ori") +_add("ig", "article", "nkeji") +_add("lg", "part", "ekitundu") +_add("om", "chapter", "kutaa") +_add("ln", "part", "eténi", "eteni") +_add("ti", "article", "ዓንቀጽ") +_add("bm", "article", "sariya") +_add("wo", "article", "tere") +_add("ak", "article", "ahyɛde", "ahyede") +_add("ee", "part", "akpa") +_add("ff", "part", "faanda") +_add("br", "article", "pennad") +_add("kri", "section", "sekshon") +_add("bo", "article", "དོན་ཚན") +_add("ug", "article", "ماددا") +_add("kw", "article", "erthygel") +_add("tw", "article", "hyɛdeɛ", "hyedee") +_add("tet", "article", "artigu") +_add("haw", "article", "paukū", "pauku") +_add("ty", "article", "irava") +_add("ch", "part", "påtte", "patte") +_add("es", "section", "numeral") +_add("it", "section", "capoverso") +_add("de", "section", "nummer") +_add("so", "part", "qaybta") +_add("vi", "part", "phần") +_add("sk", "chapter", "oddiel") +_add("el", "title", "τίτλος") +_add("bg", "title", "дял") +_add("uz", "chapter", "bob") +_add("kk", "chapter", "тарау") +_add("hi", "chapter", "अध्याय") +_add("bn", "chapter", "অধ্যায়") +_add("ur", "chapter", "باب") +_add("fa", "chapter", "فصل") +_add("ne", "chapter", "परिच्छेद") +_add("zh", "section", "节") +_add("ja", "section", "節") +_add("ko", "section", "절") +_add("th", "section", "ตอน") +_add("sr", "part", "одељак") +_add("be", "title", "раздзел") # Shared abbreviation; language left unknown. -_add("und", "article", "art.") +_add("und", "article", "art.", "član") _add("und", "section", "§") # Scripts we do not Latin-split: -NO_LATIN_SPLIT_LANGS = frozenset({"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am"}) +NO_LATIN_SPLIT_LANGS = frozenset( + { + "ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", + "am", "ru", "uk", "be", "ka", "hy", "km", "lo", "my", "si", + } +) -_TOKEN_RE = re.compile(r"[^\W\d_]{2,}|art\.|sec\.|§", re.UNICODE) +_TOKEN_RE = re.compile(r"[^\W\d_]+|art\.|sec\.|чл\.|§", re.UNICODE) def classify_heading_token(token: str) -> list[tuple[str, str]]: diff --git a/country_laws_ir/query.py b/country_laws_ir/query.py index 9cd3a1da6f2ac29b2287609ec1bc797fd55c4774..d1f4db567a8944a31bc19a28c6fb6b78aed632f8 100644 --- a/country_laws_ir/query.py +++ b/country_laws_ir/query.py @@ -158,6 +158,11 @@ class Release: hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"])) return hits[:limit] + def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]: + from .duckdb_store import cite_search + + return cite_search(self.root, citation, cite_format=cite_format, limit=limit) + def _print(rows: list[dict]) -> None: print(json.dumps(rows, indent=2, ensure_ascii=False)) @@ -189,6 +194,16 @@ def main(argv: list[str] | None = None) -> int: ) p_n.add_argument("--limit", type=int, default=25) + p_cite = sub.add_parser("cite") + p_cite.add_argument("citation") + p_cite.add_argument( + "--format", + dest="cite_format", + default="any", + choices=["any", "bluebook", "official"], + ) + p_cite.add_argument("--limit", type=int, default=25) + args = ap.parse_args(argv) rel = Release(Path(args.local_dir)) if args.cmd == "bm25": @@ -197,6 +212,8 @@ def main(argv: list[str] | None = None) -> int: _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device)) elif args.cmd == "graph" and args.graph_cmd == "neighbors": _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit)) + elif args.cmd == "cite": + _print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit)) return 0 diff --git a/country_laws_ir/reconstruct.py b/country_laws_ir/reconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..eb125e048ca3ec9c61621d72ad4a17b072a17636 --- /dev/null +++ b/country_laws_ir/reconstruct.py @@ -0,0 +1,229 @@ +"""Reconstruct empty parent law bodies from article children. + +Never invents legal text. Glue uses the same normalized strings as child +corpus fields. Eligible empty parents always get a law row (full glue, +streamed prefix, or title/number stub) — they are not dropped. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import os +import re +import unicodedata +from typing import Any, Iterable + +from .structure import normalize_legal_text + +RECONSTRUCT_MAX_PARENT_CHARS = 2_000_000 +RECONSTRUCT_STUB_MAX_CHARS = 8_192 +RECONSTRUCT_PROCESS_BUDGET_BYTES = 512 * 1024 * 1024 +RSS_ABORT_SKIP_FULL_CONCAT = frozenset({"france", "eu", "denmark"}) +PARENT_TRUNCATED_MAX_CHARS = 40 + +_DIGIT_FOLD = str.maketrans( + { + "٠": "0", + "١": "1", + "٢": "2", + "٣": "3", + "٤": "4", + "٥": "5", + "٦": "6", + "٧": "7", + "٨": "8", + "٩": "9", + "۰": "0", + "۱": "1", + "۲": "2", + "۳": "3", + "۴": "4", + "۵": "5", + "۶": "6", + "۷": "7", + "۸": "8", + "۹": "9", + "〇": "0", + "零": "0", + } +) +_NUM_RUN = re.compile(r"\d+|\D+") + + +def fold_digits(value: str) -> str: + return unicodedata.normalize("NFKC", value or "").translate(_DIGIT_FOLD) + + +def article_sort_key(article_number: str, source_id: str) -> tuple: + folded = fold_digits(article_number or "") + nums: list[int] = [] + rest: list[str] = [] + for run in _NUM_RUN.findall(folded) if folded else []: + if run.isdigit(): + nums.append(int(run)) + else: + rest.append(run) + if not folded: + return (0, (), "", source_id or "") + if nums: + return (1, tuple(nums), "".join(rest), source_id or "") + return (2, (), folded, source_id or "") + + +def glue_piece(title: str, article_number: str, body: str) -> str: + """One child's contribution to a reconstructed parent (normalized strings).""" + title = title or "" + article_number = article_number or "" + body = body or "" + chunk = title if title else article_number + if chunk and not body.lstrip().startswith(chunk): + return f"{chunk}\n{body}" if body else chunk + return body + + +def glue_parent(pieces: Iterable[str]) -> str: + return "\n\n".join(p for p in pieces if p) + + +@dataclass +class ReconstructResult: + body: str + reconstructed_from_articles: bool + reconstruction_truncated: bool + reconstruction_gap_note: str + reconstruction_article_count: int + reconstruction_article_ids: list[str] = field(default_factory=list) + reconstruction_article_sha256: list[str] = field(default_factory=list) + extra_bytes: int = 0 + is_stub: bool = False + + def extra_fields(self) -> dict[str, Any]: + return { + "reconstructed_from_articles": self.reconstructed_from_articles, + "reconstruction_truncated": self.reconstruction_truncated, + "reconstruction_gap_note": self.reconstruction_gap_note, + "reconstruction_article_count": self.reconstruction_article_count, + "reconstruction_article_ids": list(self.reconstruction_article_ids), + "reconstruction_article_sha256": list(self.reconstruction_article_sha256), + } + + +def parent_needs_reconstruct(parent_body: str, n_articles: int) -> bool: + if n_articles < 1: + return False + body = parent_body or "" + return (not body) or len(body) < PARENT_TRUNCATED_MAX_CHARS + + +def reconstruct_on() -> bool: + return os.environ.get("COUNTRY_LAWS_RECONSTRUCT", "1").strip() not in {"0", "false", "off"} + + +def force_full_concat() -> bool: + return os.environ.get("COUNTRY_LAWS_RECONSTRUCT_FULL", "").strip() in {"1", "true", "on"} + + +def process_budget_bytes() -> int: + raw = os.environ.get("RECONSTRUCT_PROCESS_BUDGET_BYTES") + if raw and raw.isdigit(): + return int(raw) + return RECONSTRUCT_PROCESS_BUDGET_BYTES + + +def reconstruct_parent( + *, + slug: str, + parent_body: str, + parent_title: str, + children: list[dict[str, str]], + running_extra_bytes: int, + sha256_hex, +) -> ReconstructResult: + """Apply the five-way outcome table. ``children`` already normalized.""" + ordered = sorted( + children, + key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""), + ) + ids = [c.get("id") or "" for c in ordered] + shas = [sha256_hex((c.get("body") or "").encode("utf-8")) for c in ordered] + n = len(ordered) + if n < 1 or not parent_needs_reconstruct(parent_body, n): + return ReconstructResult( + body=parent_body, + reconstructed_from_articles=False, + reconstruction_truncated=False, + reconstruction_gap_note="", + reconstruction_article_count=0, + ) + + stub_note = "" + if slug in RSS_ABORT_SKIP_FULL_CONCAT and not force_full_concat(): + stub_note = "rss_abort_slug" + elif running_extra_bytes >= process_budget_bytes(): + stub_note = "reconstruct_budget" + + if stub_note: + parts: list[str] = [] + if parent_title: + parts.append(parent_title) + for child in ordered: + label = child.get("title") or child.get("article_number") or "" + if label: + parts.append(label) + stub = "\n".join(parts)[:RECONSTRUCT_STUB_MAX_CHARS] + return ReconstructResult( + body=stub, + reconstructed_from_articles=True, + reconstruction_truncated=False, + reconstruction_gap_note=stub_note, + reconstruction_article_count=n, + reconstruction_article_ids=ids, + reconstruction_article_sha256=shas, + extra_bytes=0, + is_stub=True, + ) + + acc: list[str] = [] + size = 0 + truncated = False + for child in ordered: + piece = glue_piece( + child.get("title") or "", + child.get("article_number") or "", + child.get("body") or "", + ) + if not piece: + continue + extra = (2 if acc else 0) + len(piece) + if size + extra > RECONSTRUCT_MAX_PARENT_CHARS: + room = RECONSTRUCT_MAX_PARENT_CHARS - size - (2 if acc else 0) + if room > 0: + acc.append(piece[:room]) + size = RECONSTRUCT_MAX_PARENT_CHARS + truncated = True + break + acc.append(piece) + size += extra + body = glue_parent(acc) + return ReconstructResult( + body=body, + reconstructed_from_articles=True, + reconstruction_truncated=truncated, + reconstruction_gap_note="", + reconstruction_article_count=n, + reconstruction_article_ids=ids, + reconstruction_article_sha256=shas, + extra_bytes=len(body.encode("utf-8")), + is_stub=False, + ) + + +def expected_glue_from_children(children: list[dict[str, str]]) -> str: + ordered = sorted( + children, + key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""), + ) + return glue_parent( + glue_piece(c.get("title") or "", c.get("article_number") or "", c.get("body") or "") + for c in ordered + ) diff --git a/country_laws_ir/sparse.py b/country_laws_ir/sparse.py index 5ed793543ef74b1c48e313ee29cada56fd2aface..bf5f8693efdbac078aa51fbb57ba5b9510d7b71d 100644 --- a/country_laws_ir/sparse.py +++ b/country_laws_ir/sparse.py @@ -31,26 +31,33 @@ def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]: """ from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text - _MAX_TITLE = 8_192 + _MAX_TITLE = 4_096 _MAX_BODY = 200_000 + _CTRL = dict.fromkeys(range(32)) rows: list[dict[str, Any]] = [] for rec in corpus.itertuples(index=False): - title = str(getattr(rec, "title", "") or "").replace("\x00", "").strip() - body = str(getattr(rec, "body", "") or "").replace("\x00", "").strip() + cid = str(getattr(rec, "entry_cid", "") or "") + record_type = str(getattr(rec, "record_type", "") or "law") + title = str(getattr(rec, "title", "") or "").replace("\x00", "") + body = str(getattr(rec, "body", "") or "").replace("\x00", "") + title = title.translate(_CTRL).strip() + body = body.strip() if len(title) > _MAX_TITLE: title = title[:_MAX_TITLE].rstrip() if len(body) > _MAX_BODY: body = body[:_MAX_BODY].rstrip() + if not title: + title = f"{record_type} {cid}"[:_MAX_TITLE].strip() if not title and not body: continue if not tokenize_bm25_text(title) and not tokenize_bm25_text(body): continue rows.append( { - "entry_cid": str(rec.entry_cid), + "entry_cid": cid, "title": title, "body": body, - "record_type": str(getattr(rec, "record_type", "") or "law"), + "record_type": record_type, "document_index": int(rec.document_index), } ) diff --git a/country_laws_ir/structure.py b/country_laws_ir/structure.py index 468ecfdfff4eb76dc26a92c33c0e0e82d12c3712..8e75a1f0d697a2f93abcb7ebd62d961a24100ef4 100644 --- a/country_laws_ir/structure.py +++ b/country_laws_ir/structure.py @@ -20,6 +20,9 @@ from __future__ import annotations from dataclasses import dataclass, field from html.parser import HTMLParser import html as html_lib +import json +import os +from pathlib import Path import re import unicodedata from typing import Any @@ -27,24 +30,186 @@ from typing import Any _WS_RE = re.compile(r"\s+", re.UNICODE) _HAS_TAG_RE = re.compile(r"]*>") -# Line-anchored headings. Numbers may be arabic, roman, or dotted (1.2). +# 1:1 map so match offsets stay aligned with the stored body. re.I does not +# treat É as E; gazettes use Décision, Ordonnance, Điều, Člen, etc. +_LATIN_FOLD = str.maketrans({ + **dict.fromkeys("áàâäãåăąāấầẩẫậắằẳẵặảạ", "a"), + **dict.fromkeys("ÁÀÂÄÃÅĂĄĀẢẠ", "A"), + **dict.fromkeys("éèêëěęēếềểễệẻẹə", "e"), + **dict.fromkeys("ÉÈÊËĚĘĒẺẸƏ", "E"), + **dict.fromkeys("íìîïĩįīıịỉ", "i"), + **dict.fromkeys("ÍÌÎÏĨĮĪİỈỊ", "I"), + **dict.fromkeys("óòôöõőøōốồổỗộớờởỡợỏọ", "o"), + **dict.fromkeys("ÓÒÔÖÕŐØŌỎỌ", "O"), + **dict.fromkeys("úùûüűũūůứừửữựủụ", "u"), + **dict.fromkeys("ÚÙÛÜŰŨŪŮỦỤ", "U"), + **dict.fromkeys("ýÿỳỹỷỵ", "y"), + **dict.fromkeys("ÝŸỶỴ", "Y"), + **dict.fromkeys("çćčĉċ", "c"), + **dict.fromkeys("ÇĆČĈĊ", "C"), + **dict.fromkeys("ďđ", "d"), + **dict.fromkeys("ĎĐ", "D"), + **dict.fromkeys("ğĝģġ", "g"), + **dict.fromkeys("ĞĜĢĠ", "G"), + **dict.fromkeys("ñńņň", "n"), + **dict.fromkeys("ÑŃŅŇ", "N"), + **dict.fromkeys("ŕŗř", "r"), + **dict.fromkeys("ŔŖŘ", "R"), + **dict.fromkeys("śŝşšș", "s"), + **dict.fromkeys("ŚŜŞŠȘ", "S"), + **dict.fromkeys("ţťț", "t"), + **dict.fromkeys("ŢŤȚ", "T"), + **dict.fromkeys("źżž", "z"), + **dict.fromkeys("ŹŻŽ", "Z"), + **dict.fromkeys("ĺļľł", "l"), + **dict.fromkeys("ĹĻĽŁ", "L"), + "æ": "a", "Æ": "A", "œ": "o", "Œ": "O", "ß": "s", + "ɛ": "e", "Ɛ": "E", "ɔ": "o", "Ɔ": "O", "ŋ": "n", "Ŋ": "N", + **dict.fromkeys("ơớờởỡợ", "o"), + **dict.fromkeys("ƠỚỜỞỠỢ", "O"), + **dict.fromkeys("ưứừửữự", "u"), + **dict.fromkeys("ƯỨỪỬỮỰ", "U"), + **dict(zip("άέήίόύώϊϋΐΰ", "αεηιουωιυιυ")), + **dict(zip("ΆΈΉΊΌΎΏ", "ΑΕΗΙΟΥΩ")), + "ς": "σ", + "ё": "е", "Ё": "Е", "ї": "и", "Ї": "И", "є": "е", "Є": "Е", "ґ": "г", "Ґ": "Г", +}) + + +def _latin_fold(text: str) -> str: + return text.translate(_LATIN_FOLD) + +# Headings at line start *or* after . ; : so compacted "Art. 1. … Art. 2." still splits. +# Separator allows "Art. 1", "Art.1", "Član 12.", "ARTICULO 10.-", "Madde 1 –", +# "Article (1)", French "Art. L. 111-1", Roman "ARTICLE I". +_HEADING_NUM = ( + r"(?:[0-9٠-٩۰-۹]+(?:er|ère|bis|ter|quater|o)?" + r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])" + r"|premier(?:e)?|première|primero|primeira" + r"|unique|unico|unica|único|única)" +) +_ARTICLE_N = ( + r"(?:" + r"(?:[LRD]\.?\s*)?" + r"(?:" + r"[0-9٠-٩۰-۹]+(?:\.[0-9]+)?" + r"(?:er|ère|bis|ter|quater|aad|[A-Za-z]|o)?" + r"(?:/[0-9A-Za-z]+)?" + r"(?:\s+(?:bis|ter|quater))?" + r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])" + r"|[Α-Ω]{1,6}(?![Α-Ωα-ω])" + r")" + r"(?:[-–](?:[0-9]+|aad|bis|ter|quater|[A-Za-z](?![A-Za-z])))?" + r"(?:\([0-9A-Za-z]+\))?" + r"|premier(?:e)?" + r"|première" + r"|unique|unico|unica|único|única" + r"|primero|primera|primeiro|primeira" + r"|primo(?![A-Za-z])|secondo(?![A-Za-z])|terzo(?![A-Za-z])|quarto(?![A-Za-z])|quinto(?![A-Za-z])|prima(?![A-Za-z])" + r"|eerste|första|første" + r"|annexe" + r"|primera|segunda|tercera|cuarta|quinta" + r"|sexta|séptima|octava|novena|décima" + r")" +) +_HEADING_START = r"(?:^|(?<=[.;:])|(?<=\d[ \t]))[ \t\[\(\u00ab\u00bb\"“”‘’«»‹›\u2039\u203a]*" _HEADING_RE = re.compile( - r"(?im)^[ \t]*(?:" - r"(?PTITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|T[IÍ]TUL)\s+" - r"(?P<title_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" - r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|CAP\.)\s+" - r"(?P<chapter_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" - r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL)\s+" - r"(?P<part_n>[0-9IVXLCDM]+[A-Za-z0-9.\-]*)" - r"|(?P<article>ART(?:ICLE|IKEL|ÍCULO|IGO|ICOLO|IKKEL)?\.?|ART\." - r"|ČLÁNEK|ČLÁNOK|ČLAN|SZAKASZ|ΆΡΘΡΟ|ΑΡΘΡΟ)\s+" - r"(?P<article_n>[0-9IVXLCDMΑ-Ω]+[A-Za-zΑ-Ωa-z0-9.\-]*)" - r"|(?P<section>SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|SEC\.)\s+" - r"(?P<section_n>[0-9A-Za-z.\-]+)" - r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9A-Za-z.\-]+)" + _latin_fold( + r"(?im)" + _HEADING_START + r"(?:" + r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|TITLUL|T[IÍ]TUL|LUKU|PEAT[UÜ]KK|" + r"РАЗДЕЛ|РОЗДІЛ|DZIA[ŁL]|ΤΙΤΛΟΣ|ДЯЛ)\s+" + r"(?P<title_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" + r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|" + r"ROZDZIA[ŁL]|CAPITOLUL|NODA[ĻL]A|GLAVA|ГЛАВА|POGLAVLJE|KAPITOLA|" + r"ΚΕΦΑΛΑΙ[ΟO]|CH[UƯ][OƠ]NG|BAB|KABANATA|CAPO|HLAVA|KREU|FEJEZET|" + r"B[ÖO]L[ÜU]M|FESIL|CAIBIDIL|PENNOD|KAPITOLU|CHAPIT|ODDIEL|" + r"SURA(?:\s+YA)?|KAPITTEL|KAPITTUL|ANDIANY|SASHE(?:\s+NA)?|WASE|" + r"ISIGABA|ICANDELO|KGAOLO|BOBI|KUTAA|ORI|CAP\.)\s+" + r"(?P<chapter_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" + r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL|LIVRE|BOOK|BUCH|TOMO|KNIHA|" + r"KODEKS|CODE|ZAKONIK|BAHAGIAN|BAGIAN|SEHEMU|MỤC|MUC|LIBRO|PH[AẦ]N|" + r"QAYBTA|WAHANGA|VAEGA|HAP|KAROLO|CHIKAMU|BES|EKITUNDU|ETENI|" + r"AKPA|FAANDA|PATTE|ΜΕΡΟΣ)\s+" + r"(?P<part_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" + r"|(?P<article>(?:l['’])?(?:(?:EK|GEÇICI|GECICI|GEÇİCİ)\s+)?" + r"(?:ART(?:ICLE|IKEL|ÍCULO|ICULO|IGO|ICOLO|IKKEL|YKU[ŁL]|ICOLUL|ICOL|IKOLU|IKULA)?\.?" + r"|ART\.|NENI|PASAL|MADDE|MADDƏ|ĐIỀU|ĐIÊU|DIEU|CLANAK|ČLANAK|ČLÁNEK|ČLÁNOK|ČLEN|ČLAN|CLAN" + r"|ЧЛАНАК|ЧЛАН|ЧЛЕН|ЧЛ\.|СТАТЬЯ|СТАТТЯ|SZAKASZ|CIKK|ΆΡΘΡΟ|ΑΡΘΡΟ" + r"|PYKÄLÄ|GREIN|PANTS|SEKSYEN|CIKK|KIFUNGU|MODDA|ATIK|KUPU|ATIKOL|" + r"INGINGO(?:\s+YA)?|NDIME|ABALA|NKEJI|SARIYA|TERE|AHYEDE|PENNAD|ERTHYGEL|HYEDEE|" + r"ARTIGU|PAUKU|IRAVA" + r"|მუხლი|ՀՈԴՎԱԾ|Հոդված))(?![A-Za-z])" + r"(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*" + r"(?P<article_n>" + _ARTICLE_N + r")\)?" + r"|(?P<section>SUB(?:-)?SECTION|SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|PARAGRAHV|PARAGRAPHE|PARAGRAAF|PARAGRAPH|" + r"RECITAL|CONSIDERANDO|" + r"ALIN[EÉ]A|ALINEATUL|INCISO|P[AÁ]RRAFO|PUNKT(?![A-Za-z])|SATZ(?![A-Za-z])|LID|" + r"ΠΑΡΑΓΡΑΦΟΣ|ABSATZ|APARTADO|COMMA(?![A-Za-z])|FIKRA|STAVAK|STK\.?|АЛ\.|SEKSHON|" + r"NUMERAL|CAPOVERSO|NUMMER|" + r"AYAT|KHOẢN|KHOAN|" + r"RULE(?![A-Za-z])|REGULATION(?![A-Za-z])|SCHEDULE(?![A-Za-z])|FORM(?![A-Za-z])|" + r"ORDINANCE|ORDONNANCE|ORDONAN[TŢȚ][AĂÁ]?|ORDIN(?![A-Za-z])|BY-?LAW|DIRECTIVE(?![A-Za-z])|" + r"D[EÉ]CISION(?![A-Za-z])|DECISION(?![A-Za-z])|DECIZIE|" + r"BESLUIT(?![A-Za-z])|REGELING(?![A-Za-z])|BESCHIKKING(?![A-Za-z])|" + r"ODLUKA|PRAVILNIK|HOT[ĂA]R[ÂAÎI]RE|" + r"RESOLUCI[OÓ]N(?![A-Za-z])|RESOLU[CÇ][AÃ]O(?![A-Za-z])|PORTARIA(?![A-Za-z])|ACUERDO(?![A-Za-z])|" + r"MEDIDA\s+PROVIS[OÓ]RIA|" + r"PROCLAMATION(?![A-Za-z])|PROKLAMATION|CIRCULAR(?![A-Za-z])|INSTRUCTION(?![A-Za-z])|" + r"GUIDELINE(?![A-Za-z])|MEMORANDUM(?![A-Za-z])|" + r"AVISO(?![A-Za-z])|AVIS(?![A-Za-z])|BEKANNTMACHUNG|MEDDELANDE|" + r"NORMA(?![A-Za-z])|" + r"PRESIDENTIAL\s+DECREE|DECRETO-LEI|DECRETO(?![A-Za-z])|DECREE(?![A-Za-z])|" + r"D[EÉ]CRET-LOI|D[EÉ]CRET(?![A-Za-z])|ARR[EÊ]T[EÉ]|" + r"DELIBERA[CÇ][AÃ]O|D[EÉ]LIB[EÉ]RATION|COMUNICADO|" + r"R[EÈ]GLEMENT(?![A-Za-z])|CIRCULAIRE(?![A-Za-z])|VERORDNUNG(?![A-Za-z])|ERLASS(?![A-Za-z])|" + r"PUNTO(?![A-Za-z])|SUB(?:-)?PARAGRAPH|" + r"ANNEX(?:E)?(?![A-Za-z])|ANEXO|ANLAGE|BIJLAGE|APPENDIX|ALLEGATO|" + r"ZA[ŁL][AĄ]CZNIK|BILAGA|LIITE|P[ŘR][IÍ]LOHA|" + r"UST\.|ODST\.|ODS\.|BEK\.|" + r"SEC(?:\.|(?=\s+[0-9])))(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?[.\s:]*\(?\s*" + r"(?P<section_n>(?:[0-9][0-9A-Za-z.\-]*(?:\([0-9A-Za-z]+\))?|" + r"(?-i:[IVXLCDM]{1,8})(?![A-Za-z])|[A-Za-z](?![A-Za-z])))\)?" + r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9]+(?:[A-Za-z](?![A-Za-z]))?(?:\s+[A-Za-z](?![A-Za-z]))?(?:\s*\([0-9A-Za-z]+\))?)" + r"|(?P<section_pre_n>[0-9]+(?:\s*[a-z])?)\s*\.?\s*(?P<section_pre>§)" + r"|(?P<grein_n>[0-9]+[a-z]?)\s*\.\s*(?P<grein>gr|pants)\.?" + r"|(?P<straipsnis_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<straipsnis>straipsnis)" + r"|(?P<artikulua_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<artikulua>artikulua)" + r"|(?P<ledd_n>[0-9]+)\s*[.]?\s*(?P<ledd>ledd)" + r"|(?P<kap_n>[0-9]+)\s*(?P<kap>kap)\.?" + r"|(?P<luku_n>[0-9]+)\s*(?P<luku>luku)" + r"|(?P<fejezet_n>[IVXLCDM0-9]+)\s*\.\s*(?P<fejezet>fejezet)" + r"|(?P<peatukk_n>[0-9]+)\s*[.]?\s*(?P<peatukk>peat[uü]kk)" + r"|(?P<skyrius_n>[IVXLCDM0-9]+)\s*(?P<skyrius>skyrius)" + r"|(?P<nodala_n>[IVXLCDM0-9]+)\s*(?P<nodala>noda[ļl]a)" + r"|(?P<kafli_n>[IVXLCDM0-9]+)\s*[.]?\s*(?P<kafli>kafli)" + r"|(?P<bob_n>[0-9]+)\s*-\s*(?P<bob>bob)" + r"|(?P<tarau_n>[0-9]+)\s*-\s*(?P<tarau>тарау)" + r"|(?P<bolum_n>[0-9]+)\s*-\s*(?P<bolum>бөлүм)" + r"|(?P<modda_n>[0-9]+)\s*-\s*(?P<modda>модда|modda)" + r"|(?P<mn_n>[0-9]+)\s*(?P<mn>(?:дүгээр|дугаар)\s*зүйл)" + r"|(?P<kk_n>[0-9]+)\s*-?\s*(?P<kk>бап)" + r"|(?P<mom_n>[0-9]+)\s*(?P<mom>momentti)" + r"|(?P<order>(?:EXECUTIVE\s+)?ORDER)\s+(?P<order_n>[0-9]+)" + r"|(?P<kidogo>KIFUNGU\s+KIDOG[OU])\s*\(?\s*(?P<kidogo_n>[0-9]+)" + r"|(?P<disp>DISPOSICI[OÓ]N)(?:\s+(?:adicional(?:es)?|transitoria(?:s)?|derogatoria(?:s)?|final(?:es)?))?\s+" + r"(?P<disp_n>" + _ARTICLE_N + r")" + r"|(?P<esresol>primero|segundo|tercero|cuarto|quinto|sexto|septimo|octavo|noveno|decimo|" + r"erstens|zweitens|drittens|viertens|funftens|" + r"premierement|deuxiemement|troisiemement|quatriemement|cinquiemement)\s*:" r")" - r"(?P<rest>[^\n]{0,200})?" + ) +) +# Commonwealth "1. Short title" — used only when keyword headings are scarce. +_CW_NUM_RE = re.compile( + r"(?m)^[ \t]*(?P<cw_n>[0-9]+[A-Za-z]?)\.?\s+(?:\([0-9A-Za-z]+\)\s+)?(?=[A-Z][a-z]+)" +) +_MONTH_START_RE = re.compile( + r"(?i)^(january|february|march|april|may|june|july|august|september|october|november|december|" + r"janvier|f[eé]vrier|marzo|abril|enero|junio|julio)\b" ) +_CW_NUM_LANGS = frozenset({"", "en", "hi", "bn", "ne", "ur", "ms", "fil", "sw", "si"}) +_LEXICON_HEADING_RE: re.Pattern[str] | None = None +_LEXICON_KIND: dict[str, str] = {} _SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)") @@ -60,15 +225,733 @@ _KIND_RANK = { MIN_SPLIT_HEADINGS = 2 MIN_UNIT_CHARS = 40 +# Markers on the *stored* body (no rewritten newline copy). _ZH_ART_RE = re.compile( - r"(?:(?<=\n)|^)[  ]*" - r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)" + r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:之[一二三四五六七八九十百0-9]+)?" +) +_AR_ORD = ( + r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*والعشرون|" + r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*عشرة|" + r"العشرون|" + r"الأولى|الأولي|األولى|الاولى|الثانية|الثالثة|الرابعة|الخامسة|" + r"السادسة|السابعة|الثامنة|التاسعة|العاشرة" +) +_AR_ORD_M = ( + r"الأول|الاول|الثاني|الثالث|الرابع|الخامس|" + r"السادس|السابع|الثامن|التاسع|العاشر" ) _AR_ART_RE = re.compile( - r"(?:(?<=\n)|^)[ \t]*(المادة|مادة)\s*([0-9٠-٩]+)" + r"\(?(?:الماد[ةه]|املاد[ةه]|مادة)\s*[-–]?\s*[()]*\s*(?:[0-9٠-٩۰-۹]+|" + _AR_ORD + r")" + r"(?:\s*[-–])?(?:\s*[()]*)?(?:\s*مكرر(?:اً|ا)?)?" +) +_CITE_TAIL_RE = re.compile( + _latin_fold( + r"(?i)\s+(?:" + r"of\s+(?:this\s+|the\s+)?(?:act|law|agreement|code|constitution|article|section|" + r"principal\s+act|ordinance|regulation|decree|chapter|part|title|ruling|order)" + r"|thereof\b" + r"|hereof\b" + r"|hereunder\b" + r"|de\s+la\s+(?:loi|ley|presente|présente)" + r"|du\s+(?:code|présent|present)" + r"|des\s+gesetzes" + r"|van\s+(?:deze\s+)?(?:wet|artikel)" + r"|i\s+lov\b" + r"|cua\s+luat(?:\s+nay)?" + r")\b" + ) +) +_NUMERO_FOLD_RE = re.compile( + r"(?i)(?:№|n\.\s*o\b|n\.?[°º]|nÂ[oº°]|\bno\.?\s+(?=\d))\.?\s*" +) +_CJK_RANGE_RE = re.compile( + r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條]\s*(?:至|到|から)\s*" + r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:まで)?" +) +_FA_ORD = ( + r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم|" + r"اولی?|نخست|دوم|سوم|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم" +) +_FA_ART_RE = re.compile(r"(?:ماده|مادة)\s*(?:[0-9۰-۹]+|" + _FA_ORD + r")") +_DA_ART_RE = re.compile(r"(?:Artikel|§)\s*[0-9]+", re.IGNORECASE) +_CHROME_LINE_RE = re.compile( + r"(?i)^(?:" + r"početna stranica\b.*|" + r"upute za korištenje\b.*|" + r"elektronička pošta\b.*|" + r"vsebina uradnega lista\b.*|" + r"the incident id is\b.*|" + r"ωράριο λειτουργίας\b.*|" + r"τηλέφωνο επικοινωνίας\b.*|" + r"skip to (?:main )?content\b.*|" + r"javascript is (?:required|disabled)\b.*|" + r"privacy policy\s*$|" + r"traduction française pour information\s*$|" + r"pdf\s*$|" + r"https?://\S+\s*$|" + r"légimonaco\b.*|" + r"statutory instruments\s*$|" + r"official gazette\s*$|" + r"government gazette\s*$|" + r"(?:the )?london gazette\s*$|" + r"journal officiel(?: de la république(?: [^\n]{0,40})?)?\.?\s*$|" + r"bulletin officiel\s*$|" + r"gazette du canada\s*$|" + r"(?:the )?[\w .'-]{0,50}gazette\s*$|" + r"الوقائع المصرية\s*$|" + r"الوقائع العراقية\b.*|" + r"العدد\s*$|" + r"العدد\s+\S.{0,80}الوقائع\b.*|" + r".*شعبة الجريدة الرسمية\s*$|" + r"(?:the )?(?:republic of sudan gazette|gazette published by authority|official gazette of the republic of sudan)\b.*|" + r"الصفحة(?:\s*[0-9٠-٩]+)?\s*$|" + r"(?:الجريدة|اجلريدة|جريدة)(?:\s+الر\s*سمية)?(?:\s+العدد(?:\s*\(\s*\)?\s*[0-9٠-٩]+)?)?\s*$|" + r"république du s[ée]n[ée]gal\s*$|" + r"jamhuuriyadda\b.*|" + r"warta kerajaan\s*$|" + r"lembaran negara\s*$|" + r"berita negara\s*$|" + r"công báo\s*$|" + r"la gaceta\s*$|" + r"no\.?\s*\d+\s+government gazette\b.*|" + r"supplement to (?:the |official ).{0,60}gazette\b.*|" + r"[a-z0-9 ,.'()-]*supplement to official gazette[a-z0-9 ,.'()-]*$|" + r"printed by\b.*|" + r"https?://\S+(?:\s+\d+(?:\.\d+)*)?\s*$|" + r"©+\s*.*congress\b.*|" + r"(?:s|sm)\s+congress\b.*|" + r"palikir,\s*pohnpei\b.*|" + r"www\.\S+(?:\s+\d+)?\s*$|" + r"at\s+www\.\S+\s*$|" + r".*research bulletin.*|" + r"acts supplement\s*$|" + r"supplement\s+(?:nr\.\s*|no\.?\s*)\d+(?:\s+\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\.?)?\s*$|" + r"no\.\s+of\s+\d{4}\.?\s*$|" + r"act no\.\s+of\s+\d{4}\.?\s*$|" + r"bill for the\s*$|" + r"(?:the )?republic of [a-z]+(?:\s+[a-z]+)?\s*$|" + r"federal republic of [a-z]+(?:\s+[a-z]+)?\s*$|" + r"democratic people's republic of korea\s*$|" + r".{0,10}republic of palau\s*$|" + r"saint vincent and the grenadines\s*$|" + r"\[?\s*član\s+\.\.\.\s*\]?\s*$|" + r".*аудиони тинглаш.*|" + r"reprint\s*$|" + r"reprint authorised by\b.*|" + r"parliament building\s*$|" + r"oau drive, tower hill\s*$|" + r"office of the clerk of parliament\s*$|" + r"(?:(?:first|second|third|fourth|fifth)\s+parliament(?:\s+of\s+the\s+(?:first|second|third|fourth|fifth)\s+republic)?\s*){1,2}$|" + r"(?:(?:first|second|third|fourth|fifth)\s+meeting of parliament\s*){1,2}$|" + r"تفاصيل\s+(?:النظام|اللائحة)\s*$|" + r"مجموعة الأنظمة السعودية\s*$|" + r"المجلد\s+\S+\s*$|" + r"أنظمة\s+\S.{0,60}$|" + r"(?:first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\s+folder\s*$|" + r"this law includes:\s*$|" + r"-\s*اختر\s*-\s*$|" + r"تاريخ الإصدار\s*$|" + r"تاريخ النشر\s*$|" + r"الحالة\s*$|" + r"ساري\s*$|" + r"العربية\s*$|" + r"الإسم\s*$|" + r"البريد الإلكتروني\s*$|" + r"رقم الجوال\s*$|" + r"نوع البلاغ\s*$|" + r"\d{4}/\d{2}/\d{2}\s+ه\s+الموافق\s*:?\s*\d{2}/\d{2}/\d{4}\s+م\s*$|" + r"\d{3,4}\s+ه\s*$|" + r"خطأ لغوي\s*$|" + r"خطأ في مادة\s*$|" + r"يتضمن (?:النظام|التنظيم) ما يلي\s*:?\s*$|" + r"عدد مرات التصفح\s*\d*\s*$|" + r"نبذة عن النظام\s*$|" + r"اسم النظام/اللائحة\b.*|" + r"تاريخ (?:إصدار|نشر) النظام/اللائحة\s*$|" + r"حالة النظام/اللائحة\b.*|" + r"أدوات إصدار النظام\s*$|" + r"نص النظام\s*$|" + r"مادة معدلة\s*$|" + r"مادة ملغية\s*$|" + r"اصل الوثيقة\s*$|" + r"طباعة\s*$|" + r"إبلاغ\s*$|" + r"الإصدارات\s*$|" + r"اللغات\s*$|" + r"الإنجليزية\s*\(English\)\s*$|" + r"(?:\d{4}\s+)?revised edition(?:\s+as at\b.*|\s+page\s+\d+)?\s*$|" + r"page\s+\d+\s+\d{4}\s+revised edition\s*$|" + r"\[note: this version\b.*|" + r"\[this is the version of this document\b.*|" + r"el peruano\s*$|" + r"(?:act\s+\d+\s+of\s+\d{4}\s+)?page\s*\d+(?:\s+(?:of\s+\d+|act\s+\d+\s+of\s+\d{4}|[a-z]))?\s*$|" + r"[a-z]\s+page\s*\d+\s*$|" + r"(?:section\s+)?pages?\s*$|" + r"seite\s+\d+(?:\s+(?:von|of|bis)\s+\d+)?\s*$|" + r"bundesrecht konsolidiert\b.*|" + r".*ris\.bka\.gv\.at.*$|" + r"\{\\rtf\d+\b.*|" + r"p[aá]gina\s+\d+\s*$|" + r"pagina\s+\d+\s*$|" + r"strona\s+\d+\s*$|" + r"p\.\s*\d+(?:\s+(?:of|di|von|sur|de)\s+\d+)?\s*$|" + r"pag\.\s*\d+(?:\s+(?:di|of|de)\s+\d+)?\s*$|" + r"blz\.\s*\d+\s*$|" + r"folio\s+\d+\s*$|" + r"foglio\s+\d+\s*$|" + r"лист\s+\d+\s*$|" + r"стр\.\s*\d+\s*$|" + r"ص\s*\.?\s*\d+\s*$|" + r"עמוד\s+\d+\s*$|" + r"trang\s+\d+\s*$|" + r"halaman\s+\d+\s*$|" + r"sayfa\s+\d+\s*$|" + r"oldal\s+\d+\s*$|" + r"stran(?:ica)?\s+\d+\s*$|" + r"www\.\S+\s*$|" + r"downloaded from\b.*|" + r"printed on\s+\d.*|" + r"generated by\b.*|" + r"e-?mail:\s*\S+@\S+\s*$|" + r"tel(?:ephone)?:\s*[+\d].*$|" + r"for more information visit\b.*|" + r"[-–—]\s*\d{1,4}\s*[-–—]\s*$|" + r"table of contents\s*$|" + r"table des mati[eè]res\s*$|" + r"inhaltsverzeichnis\s*$|" + r"(?:índice|indice)\s*$|" + r"sommaire\s*$|" + r".*\barrangement of (?:sections|provisions|regulations|rules)\.?(?:\s+cap\.\s*[\d.]+.*)?\s*$|" + r"contents\s*$|" + r"section\s*$|" + r"[\s.\-;,*/_×|+~•·{}()\\=»«®∞]+$|" + r"(?=.*[+|])[+\-|]{3,}\s*$|" + r"\[original service \d{4}\].*|" + r"statute law of the [a-z ]+$|" + r"[A-Z][A-Z .'\-]{0,40}\[ch\.\s*\d+.*|" + r"التاريخ:\s*$|" + r"republic of the marshall islands\s*$|" + r"jepilpilin ke ejukaan\s*$|" + r"zastupni[cč]ki dom hrvatskoga sabora\s*$|" + r"dr[zž]avni zavod za normizaciju i mjeriteljstvo\s*$|" + r"олдинги таҳрирга қаранг\.?\s*$|" + r"explanatory note\s*$|" + r"\.\s*\(\s*\d+\s*\)\s*$|" + r"(?:يناير|فبراير|مارس|أبريل|ابريل|مايو|يونيو|يوليو|أغسطس|اغسطس|سبتمبر|أكتوبر|اكتوبر|نوفمبر|ديسمبر)\s+\d{4}\s*$|" + r"laws of (?:the )?[a-z]+(?:\s+(?:&|[a-z]+)){0,4}\s*$|" + r"(?-i:LAWS OF (?:THE )?[A-Z]+(?:\s+[A-Z]+){0,6}\s+s\s*\d+\s*$)|" + r"(?:í|i)ndice legislativo\s*$|" + r"قائمة (?:المحتويات|احملتويات)\s*$|" + r"spis tre[sś]ci\s*$|" + r"содержание\s*$|" + r"πίνακας περιεχομένων\s*$|" + r"목차\s*$|" + r"目次\s*$|" + r"สารบัญ\s*$|" + r"[aα]ριθμός\s+\d+[^\n]{0,24}\s*$|" + r"[aα]ρ\.\s*\d+(?:/\d+)?[^\n]{0,12}\s*$|" + r"številka\s+\d+[^\n]{0,24}\s*$|" + r"(?:nr|no|n[uú]m(?:ero|éro|ber)?|broj|č[ií]slo|szám|sayı|номер)\.?\s*\d{2,}(?:/\d+)?[.\s]*$|" + r"№\s*\d+\s*$|" + r"copyright\s*©?\s*\d{4}.*$|" + r"©\s*\d{4}.*$|" + r"\d{1,2}[./-]\d{1,2}[./-]\d{2,4}\s*$|" + r"\d{4}-\d{2}-\d{2}\s*$|" + r"\d{1,2}\s+(?:january|february|march|april|may|june|july|august|september|october|november|december|" + r"janvier|f[eé]vrier|mars|avril|mai|juin|juillet|ao[uû]t|septembre|octobre|novembre|d[eé]cembre|" + r"enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\s*$|" + r"end of (?:the )?document\s*$|" + r"fin du document\s*$|" + r"ende des dokuments?\s*$|" + r"fin del documento\s*$|" + r"fim do documento\s*$|" + r"[-*=._]{3,}\s*$|" + r"published\s*$|" + r"publi[eé]\s*$|" + r"publicado\s*$|" + r"veröffentlicht\s*$|" + r"\[?seal\]?\s*$|" + r"\(seal\)\s*$|" + r"l\.s\.?\s*$|" + r"god save the (?:king|queen)\s*$|" + r"vive la r[eé]publique\s*$|" + r"by (?:order|command)\s*$|" + r"signed\s*$|" + r"diario oficial(?: de la federación)?\s*$|" + r"gazzetta ufficiale(?: della repubblica(?: italiana)?)?\s*$|" + r"boletín oficial(?: del estado)?\s*$|" + r"diário da república\s*$|" + r"bundesgesetzblatt\s*$|" + r"moniteur belge\s*$|" + r"belgisch staatsblad\s*$|" + r"staatsblad\s*$|" + r"lovtidende\s*$|" + r"svensk författningssamling\s*$|" + r"uradni list\s*$|" + r"dziennik ustaw\s*$|" + r"monitorul oficial\s*$|" + r"εφημερίδα της κυβερνήσεως\s*$|" + r"resmi gazete\s*$|" + r"iris oifigiúil\s*$|" + r"latvijas vēstnesis\s*$|" + r"valstybės žinios\s*$|" + r"官報\s*$|" + r"国务院公报\s*$|" + r"관보\s*$|" + r"ราชกิจจานุเบกษา\s*$|" + r"(?:เล่ม|เลม)\s*[๐-๙0-9].*ราชกิจจานุเบกษา.*|" + r"اطلاق نسخة جديدة من الميزان\s*$|" + r"\[\d+/\d{4}(?:\s+wef\s+[\d/]+)?\]\s*$|" + r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+\s+\d{4}\]\s+.+\s+\d{1,4}\s*$|" + r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\]\s*$|" + r"(?:18|19|20)\d{2}\s*$|" + r"gazette\.?\s*$|" + r"cap\.\s*\d+(?:\.\d+)*\s*$|" + r".+\scap\.?\s*[\d.]+\s+section\s+\d+\s*$|" + r"diario oficial\s*$|" + r"diário oficial(?: da união)?\s*$|" + r"gaceta oficial(?: de la república)?\s*$|" + r"registro oficial\s*$|" + r"sbírka zákonů\s*$|" + r"zbierka z[^\n]{0,40}\s*$|" + r"magyar közlöny\s*$|" + r"narodne novine\s*$|" + r"službeni glasnik\s*$|" + r"службени гласник\s*$|" + r"държавен вестник\s*$|" + r"monitorul oficial(?: al româniei)?\s*$|" + r"norsk lovtidend\s*$|" + r"suomen säädöskokoelma\s*$|" + r"finlands författningssamling\s*$|" + r"riigi teataja\s*$|" + r"российская газета\s*$|" + r"(?:the )?kenya gazette\s*$|" + r"federal negar[ie]t gazett?e\s*$|" + r"gazette officielle\s*$|" + r"amtsblatt(?: der europäischen union)?\s*$|" + r"official journal of the european union\s*$|" + r"journal officiel de l'union européenne\s*$|" + r"gazzetta ufficiale dell'unione europea\s*$|" + r"الجريدة الرسمية\b.*|" + r"ваш броузер застарів\b.*|" + r"your browser is (?:out of date|outdated|obsolete)\b.*|" + r"all rights reserved\b.*|" + r"subscribe to\s+(?:our\s+)?(?:newsletter|mailing(?:\s+list)?|updates|feed)\b.*|" + r"(?:we use|this (?:site|website) uses)\s+cookies\b.*|" + r".{0,80}використовуємо cookies\b.*|" + r".{0,80}використання cookies\b.*|" + r"продовжуючи відвідування сайту\b.*|" + r"al meezan\b.*|" + r"الميزان\b.*|" + r".{0,40}وزارة العدل(?: و الشؤون القانونية)?\s*$|" + r"التشريعات\b.*|" + r"page not found\b.*|" + r"(?:error\s+)?404(?:\s+not found)?\b.*|" + r"access denied\s*$|" + r"forbidden\s*$|" + r"public notification\s*$|" + r"[^\n]{0,40}@mjla\b.*|" + r".{0,40}gaceta oficial(?: digital)?\b.*|" + r"paragraph\s*$|" + r"[^\n]{0,60}slov-lex\s*$|" + r"(?:crown\s+)?copyright\s*(?:©\s*)?\d{4}\.?\s*$|" + r"copying\s*/\s*unauthori[sz]ed distribution strictly prohibited\.?\s*$|" + r"(?:revision|consolidation) date\s*:.*|" + r"showing the law as at\s+\d.*|" + r"this is a revised edition of the law\b.*|" + r"printed under authority by\s*$|" + r"(?:the )?regional law revision centre\b.*|" + r"continued on next page\b.*|" + r"back to (?:page one|the top|top)\s*$|" + r"page\s*:\s*\d+\s+date\s*:.*|" + r"bwpageid\s*::.*|" + r"bwservice\s*::.*|" + r".*ron_book\b.*|" + r"\d+\s+service\s+\d+\s*$|" + r"(?:pdf|word|audio)\s+download\s*$|" + r"login with (?:facebook|google|apple|twitter|email)\b.*|" + r"(?:view|print|e-?mail)\s*$|" + r"last updated(?:\s+on)?\s+\d.*|" + r"speakers office\s*$|" + r"fsm congress\s*$|" + r".*almeezan\b.*|" + r"add new section\s*$|" + r"section name\s*$|" + r".*hijripage\b.*|" + r"search in articles\s*$|" + r"privacy statement\s*$|" + r"terms of use\s*$|" + r"rate this website\s*$|" + r"feedback via reach\s*$|" + r"singapore statutes online\b.*|" + r".*reprint is authorised by\b.*|" + r"công báo\s*/\s*số\b.*|" + r"thời gian ký\s*:.*|" + r"lex\.?uz\b.*|" + r"\[?(?:окоз|тсз|спит)\s*:.*|" + r"\d+(?:\.\d{2}){3,}.*[\u0400-\u04FF].*|" + r"issue\s*:\s*\d+\s*,\s*amendment\s*:\s*\d+\b.*|" + r"presidential comm\.?\s*no\b.*|" + r"(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}(?:\s+[a-z])?\s*$|" + r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\.\d+\b(?!.*\b(?!etc\b)[a-z]{3,}\b).*$)|" + r"(?-i:(?!.*\b(?!etc\b)[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\.\d+(?:\.\d+)*\s+\d{1,4}\s*$)|" + r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\s+(?!.*\b[a-z]{3,}\b).+$)|" + r"(?-i:(?!.*\b[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\s+\d{1,4}\s*$)|" + r"(?-i:\d{1,4}\s+[Cc]hap\.\s*\d+(?::\d+)?\b(?!.*\b[a-z]{3,}\b).*$)|" + r"(?-i:\d{1,4}\s+(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s*$)|" + r"(?-i:(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s+\d{1,4}\s*$)|" + r"constituci[oó]n pol[ií]tica del per[uú]\s+\d+\s*$|" + r"\d{1,4}\s+edici[oó]n del congreso\b.*|" + r"nr\.\s*\d+\s*\].*\[.*|" + r"st\.?\s*christopher and nevis\s*$|" + r"official gazette\s+nr\.\s*\d[\d\s/.-]*(?:\s+of\s+[\d/.-]+)?\s*$|" + r"www\.\S+(?:\s+(?!(?:for|under|and|the|is|of)\b)[A-Za-z][\w.-]{1,24}){1,2}\s*$|" + r".*laws\.africa\b.*|" + r".*share widely and freely.*|" + r".*no copyright on the legislative content.*|" + r"(?-i:^(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s+.{0,80}\(Chapter\s+\d+\)\s*$)|" + r"(?-i:^Act\s+\d+\s+(?:[A-Z][a-z]+\s+){1,6}(?:19|20)\d{2}\s*$)|" + r"issue\s*:?\s*\d+(?:\.\d+)?\s+page\s+\d+\s+of\s+\d+\b.*|" + r"issue\s*:\s*\d+(?:\.\d+)?\s+\d+\s+\d{1,2}\s+[a-z]+\s+\d{4}\s*$|" + r".*edition officielle mise [aà] jour.*|" + r"code general des impots\s+\d{4}\s*$|" + r"\d{1,2}\.\d{1,2}\.\d{4}\s*-\s*\d{1,2}\.\d{1,2}\.\d{4}\s*$|" + r"(?!.*δημοσιευ)(?!.*\bστην\b)(?=.*εφημερ.{0,12}κυβερν)(?=.*(?:τευξ|τεύχ|\(\s*τευ)).{0,140}$|" + r"(?:\d{1,4}\s+)?επ[ιί]σημη\s+εφημερ[ιί]δ[αά]\b.*|" + r"sistema integrado de gest[aã]o de finan[cç]as p[uú]blicas\s*\(sigfip\)\s*\d+\s*/\s*\d+\s*$|" + r"editado por\s*:.*\beditado em\s*:.*|" + r"issue\s+\d{1,4}\s*$|" + r"\d{1,4}\s*\|\s*page\s*$|" + r"page\s*\|\s*\d{1,4}\s*$|" + r"\{\{[^}\n]*\}\}\s*$|" + r"lap tetej[eé]re\s*$|" + r"megnyitottak\s*$|" + r"jogszab[aá]lykeres[oő]\s*$|" + r".*slu[zž]beni glasnik\b.{0,50}stranica\s+\d+\s*$|" + r".*\(unknown\)/ron\b.*|" + r"\[the next page is\s+[\d,]+\s*\]\s*$|" + r"service\s+\d+\s+[\d,]+\s*$|" + r"\[act\s+\d+\s+of\s+\d{4}\s+wef\s+[\d/]+\]\s*$|" + r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s+s[eé]rie\s*-\s*n[uú]mero\s+\d+(?:\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s*\d{1,2}\s+de\s*[a-zç]+\s+de\s+\d{4})?\s*$|" + r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s*-?\s*s[eé]rie\b.*\d.*|" + r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})s[eé]rie\b.*\d.*|" + r"\d+\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}(?:\s+p[aá]gina\s+\d+)?\s*$|" + r"s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\b.{0,80}p[aá]gina\s+\d+\s*$|" + r"(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}\s+s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\s*$|" + r"\d+\s*[\(\)]+\s*مذكرة تفسيرية\b.*|" + r"-\s*\d+\s*-\s*\).*$|" + r".*constituteproject\.org.*|" + r"pdf generated\s*:.*|" + r"[a-z][a-z]+(?:\s+[a-z][a-z]+){0,3}\s+(?:19|20)\d{2}\s+page\s+\d+\s*$|" + r"الصفحة\s*\.?\s*[0-9٠-٩]+\s*$|" + r"\[state/territory\]\s*$|" + r"direction g[eé]n[eé]rale adjointe des imp[oô]ts\s*$|" + r"et des domaines\s*$|" + r"rio:\s*\d+\s*$|" + r"#+\s*journal officiel\b.*|" + r"journal officiel\s*-\s*banque des?\s*donn[eé]es juridiques\b.*|" + r"(?!.*\b(?:publie|publi[eé]|shall|entre)\b)journal officiel (?:de la r[eé]publique|du faso)\b.{0,50}$|" + r"\[(?:\.{3}|…)\]\s*$|" + r"bsd:\s*\d+\s*$|" + r"\d{1,2}\.?\s+(?:gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre)\s*$|" + r"(?-i:(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}(?:\s+(?:19|20)\d{2})?\s+nr\.\s*\d+\s+[A-Z]\s+\d+\s*$)|" + r"(?-i:^[A-Z]\s+\d{1,4}\s+(?:19|20)\d{2}\s+nr\.\s*\d+\s+(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}\s*$)|" + r"printed on the orders? of government\s*\.?\s*$|" + r".*(?<![A-Za-z])(?:printed|thinted)\b.{0,80}government printing\b.*|" + r"to be purchased at the govt\.?\s*publications bureau\b.*|" + r"b\.?\s*l\.?\s*r\.?\s*o\.?\s*\d+\s*/\s*\d{4}\s*$|" + r"pages authorised\s*$|" + r"(?:current\s+)?authorised pages\s*$|" + r"\(inclusive\)\s*by\s+lro\.?\s*$|" + r"(?-i:(?:[A-Z][a-z]+(?:\s+|$)){1,8}(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s*$)|" + r"code\s+\S+(?:\s+\S+){0,6}\s+\d{1,3}/\d{2,3}\s*$|" + r"index\s*$|" + r"ministry/program(?:me)?/sub(?:head|program(?:me)?)\s+page\s*$|" + r"page\s+\d{1,3}\s*/\s*\d{1,3}\s*$|" + r"\[?\s*printed by authority of the\s*$|" + r"printed in [a-z][a-z .'-]{0,40}by the government printer\s*$|" + r"[\w.+-]+@[\w.-]+\.[a-z]{2,}\s+www\.\S+\s*$|" + r"secr[eé]tariat g[eé]n[eé]ral du gouvernement\s+www\.\S+\s*$|" + r"site:\s*(?:https?://|www\.)\S+\s*$|" + r"justice sector support program\s*\(jssp\).*|" + r"serial number:\s*\d+\b.*|" + r"copyright government of [a-z]+(?:\s+[a-z]+){0,3}\s*$|" + r"this page was intentionally left blank\.?\s*$|" + r"this is page \d+ of \d+\s+pages? of the above table\.?\s*$|" + r"new provisions(?: in the schedule)? are printed in italics\.?\s*$|" + r"go to top page(?: next chapter)?\s*$|" + r"(?:\d{4}\s+)?parliamentary series\s+(?:nr\.|no\.?)\s*\d+\s*$|" + r"try reloading the page or downloading the pdf\.?\s*$|" + r"reload page\s*$|" + r"uploaded by:\s*https?://\S+\s*$|" + r"t[eé]l[eé]charg[eé] sur www\.\S+\s*$|" + r"ibirimo/summary/sommaire\b.*|" + r"website:\s*(?:https?://|www\.)\S+\s*$|" + r"www\.\S+\s+[\w.+-]+@[\w.-]+\s*$|" + r"gazette order page\.?\s*$|" + r"(?:lexis finder|esilec profesional)\s*-\s*www\.\S+\s*$|" + r"official gazette\s+(?:nr\.|no\.?)\s*(?:special(?:\s+bis)?|\d+\s*bis)\s+of\b.*|" + r"s[eé]rie\s+[ivxlcdm]+\s*,\s*nr\.\s*\S+(?:\s+[A-Za-z0-9]+)?\s*$|" + r"unofficial translat(?:ed|ion)\b.*|" + r"\(?\d[\d\s().-]{6,}\)?\s*\|\s*(?:https?://|www\.)\S+\s*$|" + r"volume:\s*\d+\s+issue no:\s*\d+\s+government gazette\s*$|" + r"tonga government gazette supplement\s*$|" + r"ministry of legal affairs\s+www\.\S+\s*$|" + r"\d+\s+www\.\S+\s*$|" + r"www\.\S+\s+\d+\s*/\s*\d+\s*$|" + r"www\.\S+\s+(?:(?!for\b|is\b|shall\b|the\b)[a-z][a-z .'-]{0,50})$|" + r".*/type/page>{2,}.*|" + r"subject\.\s*reference\.\s*page\.?\s*$|" + r"name reference page no\.?\s*$|" + r"sl\s*#\s*law\s*#\s*legislation commencement gazette\s*$|" + r"gn\s*=\s*gazette notice\b.*|" + r"de blank page\b.*|" + r"printed and published by the ministry of justice\b.*|" + r"rarotonga,\s*cook islands:\s*printed under the authority\b.*|" + r"e-?mail\s*:\s*\S+@\S+.*(?:site web|www\.)\S+.*|" + r"διεύθυνση στο διαδίκτυο\s*\(url\)\s*:\s*https?://\S+.*|" + r"spletna stran:\s*www\.\S+\s*$|" + r"copyright\s*$|" + r"copyright and designs act\s+\d{4}\s*$|" + r"copyright act\s+\d{4}\s*$|" + r"powered by tcpdf\b.*|" + r"pour l'acquisition de votre abonnement\b.*|" + r"a\s*bonnement au journal officiel\b.*|" + r"[eé]dit[eé] par la direction de l'[eé]dition du journal officiel\b.*|" + r"\[the inclusion of this page is authori[sz]ed by\b.*|" + r"ins\s*=\s*inserted\b.*|" + r"[a-z]{2,8}\s*=\s*gazette\b.*|" + r"site web\s*:\s*www\.\S+\s*$|" + r"web\s*sites?\s*:?\s*-?\s*www\.\S+\s*$|" + r".*www\.documents\.gov\.lk\s*$|" + r"τηλ\.?:?\s*[\d\s,]+φαξ:?\s*[\d\s]+\s*-\s*www\.\S+\s*$|" + r"das dokument ist einsehbar unter:\s*www\.\S+\s*$|" + r"sujet articles page\s*$|" + r"language is printed on uneven numbered pages\.?\s*$|" + r".*www\.nbs\.sk\.?\s*$|" + r"\d{2}-\d{4,6}\s+\d{1,3}/\d{1,3}\s*$|" + r"\d{1,3}/\d{1,3}\s+\d{2}-\d{4,6}\s*$|" + r"[as]/(?:res|prst)/\d+\s*\(\d{4}\)\s*$|" + r"ab\s+\d{4},\s*nr\.\s*\d+\s*$|" + r"grondslag\s*:\s*[.\-–\s]*$|" + r"رقم الهاتف\s*:.*|" + r"\+[\u0600-\u06FF]{1,2}\s*$|" + r"(?-i:(?!.*\b(?:est|sont|doit|shall)\b)(?!.*\b[a-z]{4,}\b).*\bImprimerie\s+[A-Z].*$)|" + r"(?-i:(?!.*\b(?:shall|is|are|means|under|must)\b).{8,120}\(Chapter\s+\d+(?::\d+)?\)\s+[A-Z][a-z]+\s*$)|" + r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)(?:[A-ZÁÉÍÓÚÜÑ]{2,}(?:\s+|$)){4,10}\d{1,3}\s*$)|" + r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)\d{3,4}\s+(?:[A-ZÁÉÍÓÚÜÑ]{3,}(?:\s+|$)){1,3}\s*$)|" + r"\[\d{1,4}\]?\s*$|" + r"หน.?า\s+[0-9๐-๙]+\s*$|" + r"(?:home|blog|contact us|cookie|accueil|startseite|" + r"página inicial|página principal|επικοινωνία|αρχική)\s*$" + r")" +) +_CHROME_INLINE_RE = re.compile( + r"(?i)skip to (?:main )?content|all rights reserved|click here|" + r"légimonaco" +) +_JA_ART_RE = re.compile(r"第\s*[0-9一二三四五六七八九十百]+\s*[条條]") +_CIRCLED_ART_RE = re.compile(r"[①-⑳⑴-⒇❶-❿⓫-⓴]") +_CJK_ENUM_RE = re.compile(r"(?m)^[ \t]*[一二三四五六七八九十百]+、") +_CJK_PAREN_RE = re.compile(r"(?m)^[ \t]*[((][一二三四五六七八九十百]+[))]") +_CJK_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[0-90-9]+、") +_KO_GA_RE = re.compile(r"(?m)^[ \t]*[가나다라마바사아자차카타파하]\.") +_JA_KATA_ENUM_RE = re.compile(r"(?m)^[ \t]*[アイウエオカキクケコ]、") +_HANGUL_GA = "가나다라마바사아자차카타파하" +_KATA_ENUM = "アイウエオカキクケコ" +_AR_ABJAD_INDEX = { + "أ": "1", "ا": "1", "ب": "2", "ج": "3", "د": "4", "ه": "5", + "و": "6", "ز": "7", "ح": "8", "ط": "9", "ي": "10", +} +_HE_ALEF = "אבגדהוזחטי" +_TH_KO = "กขคงจฉชซฌญ" +_AR_ABJAD_RE = re.compile(r"(?m)^[ \t]*[(\[]?[أابجدهوزحطي][)\]]?\s*[-.)]") +_HE_ALEF_RE = re.compile(r"(?m)^[ \t]*[אבגדהוזחטי]\.") +_HE_PEREK_RE = re.compile(r"(?m)^[ \t]*פרק\s+[א-ת]{1,3}['׳]?") +_HE_SIMAN_RE = re.compile(r"(?m)^[ \t]*סימן\s+[א-ת]{1,3}['׳]?") +_HE_HELEK_RE = re.compile(r"(?m)^[ \t]*חלק\s+[א-ת]{1,3}['׳]?") +_HE_TOS_RE = re.compile( + r"(?m)^[ \t]*תוספת\s+(?:ראשונה|שנייה|שניה|שלישית|רביעית|חמישית|שישית|[א-ת]['׳]?|[0-9]+)" +) +_HE_TAKANA_RE = re.compile(r"(?m)^[ \t]*תקנה\s+[0-9]+") +_AR_ANNEX_RE = re.compile(r"(?m)^[ \t]*ملحق(?:\s*رقم)?\s*[0-9٠-٩()]+") +_AR_BAB_RE = re.compile( + r"(?m)^[ \t]*الباب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")" +) +_AR_FASL_RE = re.compile( + r"(?m)^[ \t]*الفصل\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")" +) +_AR_KITAB_RE = re.compile( + r"(?m)^[ \t]*الكتاب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")" +) +_AR_FARA_RE = re.compile( + r"(?m)^[ \t]*الفرع\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")" ) -_JA_ART_RE = re.compile( - r"(?:(?<=\n)|^)[  ]*(第[0-9一二三四五六七八九十百]+条)" +_FA_BAND_RE = re.compile(r"بند\s*[0-9۰-۹]+") +_CJK_ZHANG_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*章") +_KO_JANG_RE = re.compile(r"제\s*[0-9]+\s*장") +_TA_ART_RE = re.compile(r"பிரிவு\s*[0-9௦-௯]+") +_TE_ART_RE = re.compile(r"ప్రకరణ(?:ము)?\s*[0-9౦-౯]+") +_KN_ART_RE = re.compile(r"ಪ್ರಕರಣ\s*[0-9೦-೯]+") +_GU_ART_RE = re.compile(r"કલમ\s*[0-9૦-૯]+") +_PA_ART_RE = re.compile(r"ਧਾਰਾ\s*[0-9੦-੯]+") +_ML_ART_RE = re.compile(r"വകുപ്പ്\s*[0-9൦-൯]+") +_CJK_BIAN_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[编編]") +_KO_PYEON_RE = re.compile(r"제\s*[0-9]+\s*편") +_TH_LAK_RE = re.compile(r"(?m)^[ \t]*ลักษณะ\s*[0-9๐-๙]+") +_KM_CHAP_RE = re.compile(r"ជំពូក\s*[0-9០-៩]+") +_LO_PART_RE = re.compile(r"ພາກ\s*[0-9໐-໙]+") +_MY_CHAP_RE = re.compile(r"အခန်း\s*[0-9၀-၉]+") +_KA_CHAP_RE = re.compile(r"თავი\s+[IVXLCDM0-9]+") +_HY_CHAP_RE = re.compile(r"Գլուխ\s+[IVXLCDM0-9]+", re.IGNORECASE) +_AM_CHAP_RE = re.compile(r"ምዕራፍ\s*[0-9፩-፻]+") +_HI_CHAP_RE = re.compile(r"अध्याय\s*[0-9०-९]+") +_BN_CHAP_RE = re.compile(r"অধ্যায়\s*[0-9০-৯]+") +_UR_CHAP_RE = re.compile(r"باب\s*[0-9۰-۹]+") +_FA_FASL_RE = re.compile(r"فصل\s*[0-9۰-۹]+") +_NE_CHAP_RE = re.compile(r"परिच्छेद\s*[0-9०-९]+") +_CJK_JIE_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[节節]") +_KO_JEOL_RE = re.compile(r"제\s*[0-9]+\s*절") +_TH_TON_RE = re.compile(r"(?m)^[ \t]*ตอน\s*[0-9๐-๙]+") +_SR_PART_RE = re.compile(r"(?:Одељак|ОДЕЉАК)\s+[IVXLCDM0-9]+", re.IGNORECASE) +_RU_TITLE_RE = re.compile( + r"(?:Раздел|РАЗДЕЛ|Розділ|РОЗДІЛ|Раздзел|РАЗДЗЕЛ)\s+[IVXLCDM0-9]+", + re.IGNORECASE, +) +_RU_CHAP_RE = re.compile(r"(?:Глава|ГЛАВА)\s+[IVXLCDM0-9]+", re.IGNORECASE) +_TH_KO_RE = re.compile(r"(?m)^[ \t]*[กขคงจฉชซฌญ]\.") +_HI_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[०-९]+\s*[.।]") +_BN_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[০-৯]+\s*[.।]") +_CYR_AB = "абвгдежзийк" +_EL_AB = "αβγδεζηθικ" +_KA_AB = "აბგდევზთიკლ" +_HY_AB = "աբգդեզէըթժ" +_CYR_AB_RE = re.compile(r"(?im)^[ \t]*[абвгдежзийк]\s*[).]") +_EL_AB_RE = re.compile(r"(?im)^[ \t]*[αβγδεζηθικ]\s*[).]") +_KA_AB_RE = re.compile(r"(?m)^[ \t]*[აბგდევზთიკლ]\s*[).]") +_HY_AB_RE = re.compile(r"(?m)^[ \t]*[աբգդեզէըթժ]\s*[).]") +_MARK_AFTER = r"(?:\s+|(?=[^\x00-\x7f]))" +_LATIN_LETTER_RE = re.compile( + r"(?m)^[ \t]*(?:\(\s*(?P<paren>[a-z])\s*\)|(?P<bare>[a-z])\)|" + r"(?P<roman>viii|iii|vii|ii|iv|ix|vi|i|v|x)\.)" + + _MARK_AFTER +) +_BULLET_RE = re.compile(r"(?m)^[ \t]*[•·●‣⁃*#]\s+") +_DASH_NUM_RE = re.compile(r"(?m)^[ \t]*-\s*(?P<bn>[0-9]{1,3})\s+(?=[^\W\d_])") +_LATIN_NUM_LIST_RE = re.compile( + r"(?m)^[ \t]*(?:" + r"\(\s*(?P<nparen>[0-9]{1,3})\s*\)|" + r"(?P<nclose>[0-9]{1,3})\)|" + r"(?P<nord>[0-9]{1,3})[º°o]|" + r"(?P<ndot>[0-9]{1,3})\.-|" + r"(?P<ncolon>[0-9]{1,3}):|" + r"(?P<ndash>[0-9]{1,3})-|" + r"(?P<dbl>([a-z])\2)\)" + r")" + + _MARK_AFTER +) +_ROMAN_LOWER = { + "i": "1", "ii": "2", "iii": "3", "iv": "4", "x": "10", + "v": "5", "vi": "6", "vii": "7", "viii": "8", "ix": "9", +} +_JA_KOU_RE = re.compile(r"第[0-9一二三四五六七八九十百]+項") +_ZH_KUAN_RE = re.compile(r"第[一二三四五六七八九十百千万零〇两0-9]+款") +_KO_ART_RE = re.compile(r"제\s*[0-9]+\s*조") +_KO_HANG_RE = re.compile(r"제\s*[0-9]+\s*항") +_KO_HO_RE = re.compile(r"제\s*[0-9]+\s*호") +_TH_PARA_RE = re.compile(r"วรรค\s*[0-9๐-๙]+") +_TH_KHO_RE = re.compile(r"(?m)^[ \t]*ข้อ\s*[0-9๐-๙]+") +_TH_HUAT_RE = re.compile(r"(?m)^[ \t]*หมวด\s*[0-9๐-๙]+") +_FA_TAB_RE = re.compile(r"تبصره\s*[0-9۰-۹]+") +_HE_PARA_RE = re.compile(r"פסקה\s*[0-9]+") +_AR_PARA_RE = re.compile(r"الفقرة\s*[0-9٠-٩]+") +_AR_QARAR_RE = re.compile(r"قرار(?:\s*رقم)?\s*[0-9٠-٩]+") +_AR_DECREE_RE = re.compile(r"(?:مرسوم|أمر)(?:\s*رقم)?\s*[0-9٠-٩]+") +_RU_INST_RE = re.compile(r"(?:Указ|Постановление|Приказ)\s+[0-9]+", re.IGNORECASE) +_KO_RANGE_RE = re.compile( + r"제\s*[0-9]+\s*조\s*부터\s*제\s*[0-9]+\s*조(?:까지)?" +) +_HE_ART_RE = re.compile( + r"(?:סעיף\s*(?:[0-9]+|(?!קטן)[א-ת]{1,3}['׳]?)|\.\s*[0-9]+(?=[\u0590-\u05FF]))" +) +_HE_KATAN_RE = re.compile(r"סעיף\s+קטן\s*\(?\s*[א-ת]'?\)?") +_TH_ART_RE = re.compile(r"มาตรา\s*[0-9๐-๙]+") +_HI_ART_RE = re.compile(r"(?:धारा|ধারা)\s*[0-9০-৯]+") +_RU_ART_RE = re.compile(r"(?:Статья|СТАТЬЯ|Стаття|СТАТТЯ)\s+[0-9]+(?:-[0-9]+)?", re.IGNORECASE) +_KA_ART_RE = re.compile(r"მუხლი\s*[0-9]+") +_HY_ART_RE = re.compile(r"Հոդված\s*[0-9]+", re.IGNORECASE) +_AM_ART_RE = re.compile(r"አንቀጽ\s*[0-9፩-፻]+") +_BN_ART_RE = re.compile(r"ধারা\s*[0-9০-৯]+") +_LO_ART_RE = re.compile(r"ມາດຕາ\s*[0-9໐-໙]+") +_KM_ART_RE = re.compile(r"មាត្រា\s*[0-9០-៩]+") +_MY_ART_RE = re.compile(r"ပုဒ်မ\s*[0-9၀-၉]+") +_UZ_ART_RE = re.compile(r"[0-9]+\s*-\s*(?:модда|modda)", re.IGNORECASE) +_MN_ART_RE = re.compile(r"[0-9]+\s*(?:дүгээр|дугаар)\s*зүйл", re.IGNORECASE) +_KK_ART_RE = re.compile(r"[0-9]+\s*-?\s*бап", re.IGNORECASE) +_NE_ART_RE = re.compile(r"दफा\s*[0-9०-९]+") +_TI_ART_RE = re.compile(r"ዓንቀጽ\s*[0-9፩-፻]+") +_BO_ART_RE = re.compile(r"དོན་ཚན་\s*[0-9༠-༩]+") +_UG_ART_RE = re.compile(r"ماددا\s*[0-9۰-۹]+") +_AR_POINT_RE = re.compile(r"(?m)^[ \t]*(?:أولا|ثانيا|ثالثا|رابعا|خامسا)\s*[:/]") +_AR_POINT_NUM = (("أولا", "1"), ("ثانيا", "2"), ("ثالثا", "3"), ("رابعا", "4"), ("خامسا", "5")) +_SI_ART_RE = re.compile(r"වගන්තිය\s*[0-9෦-෯]+") +_UR_ART_RE = re.compile(r"دفعہ\s*[0-9۰-۹]+") +_KY_ART_RE = re.compile(r"[0-9]+\s*-?\s*берене", re.IGNORECASE) +_BE_ART_RE = re.compile(r"Артыкул\s*[0-9]+", re.IGNORECASE) + +# "A R T Í C U L O 86" / "C A P I T U L O I" → ARTÍCULO 86 / CAPITULO I +_SPACED_KEYWORD_RE = re.compile( + r"(?iu)\b((?:[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ]\s+){3,}" + r"[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ])\b" + r"(?=\s*[.:\-–—]?\s*[0-9IVXLCDM])" +) + + +def _squeeze_spaced_keyword(match: re.Match[str]) -> str: + return re.sub(r"\s+", "", match.group(1)) + + +_ZW_RE = re.compile( + r"[\ufeff\u200b\u200c\u200d\u00ad\u2060\u200e\u200f\u202a-\u202e\u2066-\u2069]" +) +# Tashkeel, niqqud, Latin combining. Keep Thai/Lao/Khmer/Myanmar/Indic Mn. +_STRIP_MARKS_RE = re.compile( + "[" + "\u0300-\u036f" + "\u0483-\u0489" + "\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7" + "\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed" + "\u08d3-\u08e1\u08e3-\u08ff" + "]" +) +_SCRIPT_CITE_TAIL_RE = re.compile( + r"(?i)^\s*(?:" + r"من\s*(?:الدستور|القانون|الأمر|المرسوم|القرار)|" + r"của\s+luật|" + r"של\s+(?:חוק|פקודה)" + r")" +) + +# UTF-8 read as Latin-1: § (U+00C2 U+00A7) is §, é is é. Âmbito stays. +_LATIN1_UTF8_RE = re.compile(r"[\u00c2\u00c3][\u0080-\u00bf]") + + +def _repair_latin1_utf8(text: str) -> str: + if "\u00c2" not in text and "\u00c3" not in text: + return text + + def repl(match: re.Match[str]) -> str: + try: + return match.group(0).encode("latin-1").decode("utf-8") + except UnicodeDecodeError: + return match.group(0) + + return _LATIN1_UTF8_RE.sub(repl, text) + + +# Script-tagged gazettes that still publish English Article/Section translations. +_LATIN_FALLBACK_LANGS = frozenset( + {"ka", "km", "hy", "am", "lo", "my", "si", "th", "he", "ne", "fa"} ) @@ -121,15 +1004,185 @@ def strip_html(raw: str) -> str: return text.strip() +_ROMAN_PAGE_RE = re.compile( + r"(?i)(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3}|xiv|xv)$" +) + + +def _is_roman_page_line(line: str, nxt: str) -> bool: + """A lone i/ii/iii between blocks is a page stamp, not a list item.""" + if _ROMAN_PAGE_RE.fullmatch(line.strip()) is None: + return False + nxt = nxt.strip() + if not nxt: + return True + return not (nxt[:1].islower() or nxt.startswith("(")) + + +def _is_page_num_line(line: str) -> bool: + token = line.strip() + if 1 <= len(token) <= 4 and all(unicodedata.category(ch) == "Nd" for ch in token): + return True + # "1/3" between paragraphs is page 1 of 3, not a section. + parts = token.split("/") + if len(parts) == 2 and all(part.isascii() and part.isdigit() for part in parts): + left, right = int(parts[0]), int(parts[1]) + return 1 <= left <= right <= 30 + return False + + +def _is_facing_page_line(line: str) -> bool: + """'736 737' between blocks is a two-page spread, not a citation.""" + parts = line.split() + if len(parts) != 2 or not all(part.isascii() and part.isdigit() for part in parts): + return False + left, right = int(parts[0]), int(parts[1]) + return 100 <= left and right == left + 1 and right <= 9999 + + +_PAGE_OF_RE = re.compile(r"(?i)(\d{1,2})\s+of\s+(\d{1,2})") + + +def _is_page_of_line(line: str) -> bool: + """'3 of 5' between blocks is a page count, not a citation.""" + match = _PAGE_OF_RE.fullmatch(line.strip()) + if match is None: + return False + left, right = int(match.group(1)), int(match.group(2)) + return 1 <= left <= right <= 30 + + +def learned_patterns_path() -> Path: + override = os.environ.get("COUNTRY_LAWS_LEARNED_PATTERNS") + if override: + return Path(override) + return Path(__file__).resolve().parent / "data" / "learned_line_patterns.json" + + +_LEARNED: tuple[float, re.Pattern[str] | None] | None = None + + +def learned_line_pattern() -> re.Pattern[str] | None: + """Whole-line rules added by the normalize loop. Compiled once per file change.""" + global _LEARNED + path = learned_patterns_path() + if not path.is_file(): + return None + mtime = path.stat().st_mtime + if _LEARNED is not None and _LEARNED[0] == mtime: + return _LEARNED[1] + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + _LEARNED = (mtime, None) + return None + parts: list[str] = [] + for item in payload.get("patterns") or []: + if not isinstance(item, str): + continue + try: + re.compile(item, re.IGNORECASE) + except re.error: + continue + parts.append(item) + compiled = re.compile("|".join(f"(?:{part})" for part in parts), re.IGNORECASE) if parts else None + _LEARNED = (mtime, compiled) + return compiled + + +def strip_chrome_lines(text: str) -> str: + """Drop gazette-site chrome lines. Never invents replacement legal text.""" + if not text: + return "" + raw_lines = text.splitlines() + multi = sum(1 for ln in raw_lines if ln.strip()) > 1 + learned = learned_line_pattern() + kept = [] + for idx, ln in enumerate(raw_lines): + stripped = ln.strip() + if not stripped: + continue + if _CHROME_LINE_RE.match(stripped) or _CHROME_INLINE_RE.search(ln): + continue + if learned is not None and learned.match(stripped): + continue + # A lone "2" or "10" is an article number. The same token inside a + # longer page is a page stamp. + if multi and ( + _is_page_num_line(stripped) + or _is_facing_page_line(stripped) + or _is_page_of_line(stripped) + ): + continue + nxt = "" + for later in raw_lines[idx + 1 :]: + if later.strip(): + nxt = later + break + if multi and _is_roman_page_line(stripped, nxt): + continue + kept.append(ln) + return "\n".join(kept).strip() + + +_HYPHEN_BREAK_RE = re.compile(r"(?<=[^\W\d_])-[ \t]*\n+[ \t]*([^\W\d_])") + + +def _join_hyphen_breaks(text: str) -> str: + """Join a hyphenated word split across lines. Leave a following capital header.""" + + def repl(match: re.Match[str]) -> str: + nxt = match.group(1) + if nxt.isupper(): + return match.group(0) + return nxt + + return _HYPHEN_BREAK_RE.sub(repl, text) + + def normalize_legal_text(value: Any) -> str: """NFKC + HTML strip. Keeps newlines so heading detection still works.""" if value is None: return "" - text = unicodedata.normalize("NFKC", str(value)) + text = unicodedata.normalize("NFKC", str(value)).replace("\x00", "") + if text.startswith("ÿþ") or text.startswith("þÿ"): + text = text[2:] + text = re.sub(r"[\x00-\x08\x0b\x0e-\x1f\x7f]", " ", text) + text = text.replace("\ufffd", " ") + text = re.sub(r"[\ue000-\uf8ff]", "", text) + text = _repair_latin1_utf8(text) + text = re.sub(r"\(cid:\d+\)", " ", text) + text = _ZW_RE.sub("", text).replace("ـ", "") + text = _STRIP_MARKS_RE.sub("", text) + text = re.sub(r"[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]", "-", text) + text = re.sub(r"[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]", " ", text) + text = text.replace("\u2028", "\n").replace("\u2029", "\n").replace("\f", "\n") + text = _join_hyphen_breaks(text) + text = _NUMERO_FOLD_RE.sub("nr. ", text) + text = re.sub(r"المادة\s*-\s*اختر\s*-\s*", "", text) + text = re.sub(r"(?m)^[ \t]*©+\s*", "", text) + text = re.sub(r"\b((?:19|20)\d{2}) \1\b", r"\1", text) + text = re.sub(r"(?<=[A-Za-z])!+(?=\d)", " ", text) + text = re.sub(r":!+", ":", text) + text = re.sub(r"(?m)!+\s*$", "", text) + text = _SPACED_KEYWORD_RE.sub(_squeeze_spaced_keyword, text) + text = re.sub(r"(?s)<!--.*?-->", " ", text) text = strip_html(text) + text = html_lib.unescape(text).replace("\xa0", " ") + text = re.sub(r"_{3,}", " ", text) + text = re.sub(r"\.{4,}", " ", text) + text = re.sub(r"(?m)^[ \t]*#{1,6}[ \t]+", "", text) + text = strip_chrome_lines(text) text = text.replace("\xa0", " ") + text = re.sub(r"~\$\S{0,16}", " ", text) + text = re.sub(r"\*\*([^*]{1,80})\*\*", r"\1", text) + text = re.sub(r"__([^_]{1,80})__", r"\1", text) + text = re.sub(r"'{3}([^']{1,80})'{3}", r"\1", text) + text = re.sub(r"^={2,6}\s*(.+?)\s*={2,6}\s*$", r"\1", text, flags=re.MULTILINE) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n[ \t]+", "\n", text) + text = re.sub(r"[ \t]+\n", "\n", text) + text = _join_hyphen_breaks(text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() @@ -147,6 +1200,8 @@ class StructureUnit: section_number: str = "" subsections: tuple[str, ...] = () hierarchy_path: str = "" + char_start: int = 0 + char_end: int = 0 def to_dict(self) -> dict[str, Any]: return { @@ -161,6 +1216,8 @@ class StructureUnit: "section_number": self.section_number, "subsections": list(self.subsections), "hierarchy_path": self.hierarchy_path, + "char_start": self.char_start, + "char_end": self.char_end, } @@ -190,116 +1247,880 @@ def _subsection_tokens(text: str) -> tuple[str, ...]: return tuple(seen) -def _units_from_regex( - text: str, matches: list[re.Match[str]], *, kind: str, lang: str -) -> list[StructureUnit]: - if len(matches) < MIN_SPLIT_HEADINGS: - return [] - units: list[StructureUnit] = [] - for i, match in enumerate(matches): - start = match.start() - end = matches[i + 1].start() if i + 1 < len(matches) else len(text) - chunk = text[start:end].strip() - if len(chunk) < 16: - continue - number = re.sub(r"\s+", "", match.group(0)) - heading = re.sub(r"\s+", " ", chunk.split("\n", 1)[0])[:240] - units.append( - StructureUnit( - kind=kind, - number=number, - heading=heading, - body=chunk, - article_number=number, - hierarchy_path=heading, - ) - ) - return units if len(units) >= MIN_SPLIT_HEADINGS else [] +def check_exclusive_cover(text: str, units: list[StructureUnit]) -> bool: + """True iff units are contiguous, non-overlapping, and cover *text* exactly.""" + if not units: + return not text + ordered = sorted(units, key=lambda u: u.char_start) + if ordered[0].char_start != 0 or ordered[-1].char_end != len(text): + return False + prev = 0 + for unit in ordered: + if unit.char_start != prev or unit.char_end < unit.char_start: + return False + if text[unit.char_start : unit.char_end] != unit.body: + return False + prev = unit.char_end + return True -def split_script_units(text: str, language: str) -> list[StructureUnit]: - """Article splits for scripts that must not use Latin TITLE/ARTICLE.""" +def _script_regex(language: str): from .profiles import iso_lang lang = iso_lang(language) if lang in {"zh", "zh-cn", "zh-tw"}: - prepared = re.sub( - r"(第[一二三四五六七八九十百千万零〇两0-9]+条(?:之[一二三四五六七八九十百0-9]+)?)", - r"\n\1", - text, - ) - return _units_from_regex(prepared, list(_ZH_ART_RE.finditer(prepared)), kind="article", lang="zh") - if lang in {"ar", "fa"}: - prepared = re.sub(r"(المادة|مادة)", r"\n\1", text) - return _units_from_regex(prepared, list(_AR_ART_RE.finditer(prepared)), kind="article", lang="ar") + return _ZH_ART_RE + if lang == "ar": + return _AR_ART_RE + if lang == "fa": + return _FA_ART_RE if lang == "ja": - prepared = re.sub(r"(第[0-9一二三四五六七八九十百]+条)", r"\n\1", text) - return _units_from_regex(prepared, list(_JA_ART_RE.finditer(prepared)), kind="article", lang="ja") - return [] + return _JA_ART_RE + if lang == "ko": + return _KO_ART_RE + if lang == "he": + return _HE_ART_RE + if lang == "th": + return _TH_ART_RE + if lang == "hi": + return _HI_ART_RE + if lang == "bn": + return _BN_ART_RE + if lang in {"ru", "uk", "be"}: + return _RU_ART_RE + if lang == "ka": + return _KA_ART_RE + if lang == "hy": + return _HY_ART_RE + if lang == "am": + return _AM_ART_RE + if lang == "ti": + return _TI_ART_RE + if lang == "bo": + return _BO_ART_RE + if lang == "ug": + return _UG_ART_RE + if lang == "lo": + return _LO_ART_RE + if lang == "km": + return _KM_ART_RE + if lang == "my": + return _MY_ART_RE + if lang == "uz": + return _UZ_ART_RE + if lang == "mn": + return _MN_ART_RE + if lang == "kk": + return _KK_ART_RE + if lang == "ne": + return _NE_ART_RE + if lang == "si": + return _SI_ART_RE + if lang == "ta": + return _TA_ART_RE + if lang == "te": + return _TE_ART_RE + if lang == "kn": + return _KN_ART_RE + if lang == "gu": + return _GU_ART_RE + if lang == "pa": + return _PA_ART_RE + if lang == "ml": + return _ML_ART_RE + if lang == "ur": + return _UR_ART_RE + if lang == "ky": + return _KY_ART_RE + if lang == "be": + return _BE_ART_RE + return None -def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]: - """Split *text* on legal headings. Empty list means keep the whole instrument. +def _detected_script_regexes(text: str, language: str) -> list: + found: list = [] + primary = _script_regex(language) + if primary is not None: + found.append(primary) + if re.search(r"[①-⑳⑴-⒇❶-❿⓫-⓴]", text): + found.append(_CIRCLED_ART_RE) + if re.search(r"[\u4e00-\u9fff]", text): + found.extend((_ZH_ART_RE, _JA_ART_RE, _ZH_KUAN_RE, _JA_KOU_RE, _CJK_ZHANG_RE, _CJK_BIAN_RE, _CJK_JIE_RE, _CJK_ENUM_RE, _CJK_PAREN_RE, _CJK_DIGIT_ENUM_RE)) + if re.search(r"[\uac00-\ud7af]", text): + found.extend((_KO_ART_RE, _KO_HANG_RE, _KO_HO_RE, _KO_GA_RE, _KO_JANG_RE, _KO_PYEON_RE, _KO_JEOL_RE)) + if re.search(r"[\u30a0-\u30ff]", text): + found.append(_JA_KATA_ENUM_RE) + if re.search(r"[\u0600-\u06ff]", text): + found.extend(( + _AR_ART_RE, _FA_ART_RE, _FA_TAB_RE, _FA_BAND_RE, _FA_FASL_RE, _AR_PARA_RE, _AR_QARAR_RE, _AR_DECREE_RE, + _AR_ABJAD_RE, _AR_ANNEX_RE, _AR_BAB_RE, _AR_FASL_RE, _AR_KITAB_RE, _AR_FARA_RE, _UR_CHAP_RE, _UG_ART_RE, _AR_POINT_RE, + )) + if re.search(r"[\u0590-\u05ff]", text): + found.extend(( + _HE_ART_RE, _HE_PARA_RE, _HE_ALEF_RE, _HE_PEREK_RE, _HE_SIMAN_RE, + _HE_HELEK_RE, _HE_TOS_RE, _HE_TAKANA_RE, _HE_KATAN_RE, + )) + if re.search(r"[\u0e00-\u0e7f]", text): + found.extend((_TH_ART_RE, _TH_PARA_RE, _TH_KO_RE, _TH_KHO_RE, _TH_HUAT_RE, _TH_LAK_RE, _TH_TON_RE)) + if re.search(r"[\u0900-\u097f]", text): + found.extend((_HI_ART_RE, _HI_DIGIT_ENUM_RE, _HI_CHAP_RE, _NE_CHAP_RE)) + if re.search(r"[\u0980-\u09ff]", text): + found.extend((_BN_ART_RE, _BN_DIGIT_ENUM_RE, _BN_CHAP_RE)) + if re.search(r"[\u0b80-\u0bff]", text): + found.append(_TA_ART_RE) + if re.search(r"[\u0c00-\u0c7f]", text): + found.append(_TE_ART_RE) + if re.search(r"[\u0c80-\u0cff]", text): + found.append(_KN_ART_RE) + if re.search(r"[\u0a80-\u0aff]", text): + found.append(_GU_ART_RE) + if re.search(r"[\u0a00-\u0a7f]", text): + found.append(_PA_ART_RE) + if re.search(r"[\u0d00-\u0d7f]", text): + found.append(_ML_ART_RE) + if re.search(r"[\u0e80-\u0eff]", text): + found.extend((_LO_ART_RE, _LO_PART_RE)) + if re.search(r"[\u1780-\u17ff]", text): + found.extend((_KM_ART_RE, _KM_CHAP_RE)) + if re.search(r"[\u1000-\u109f]", text): + found.extend((_MY_ART_RE, _MY_CHAP_RE)) + if re.search(r"[\u1200-\u137f]", text): + found.extend((_AM_ART_RE, _AM_CHAP_RE, _TI_ART_RE)) + if re.search(r"[\u0f00-\u0fff]", text): + found.append(_BO_ART_RE) + if re.search(r"[\u10a0-\u10ff]", text): + found.extend((_KA_ART_RE, _KA_AB_RE, _KA_CHAP_RE)) + if re.search(r"[\u0530-\u058f]", text): + found.extend((_HY_ART_RE, _HY_AB_RE, _HY_CHAP_RE)) + if re.search(r"[\u0400-\u04ff]", text): + found.extend((_CYR_AB_RE, _RU_TITLE_RE, _RU_CHAP_RE, _SR_PART_RE)) + if re.search(r"[\u0370-\u03ff]", text): + found.append(_EL_AB_RE) + if "модда" in text.casefold() or re.search(r"\bmodda\b", text, re.IGNORECASE): + found.append(_UZ_ART_RE) + if re.search(r"зүйл", text, re.IGNORECASE): + found.append(_MN_ART_RE) + if re.search(r"бап", text, re.IGNORECASE): + found.append(_KK_ART_RE) + if "दफा" in text: + found.append(_NE_ART_RE) + if "परिच्छेद" in text: + found.append(_NE_CHAP_RE) + if "වගන්තිය" in text: + found.append(_SI_ART_RE) + if "دفعہ" in text: + found.append(_UR_ART_RE) + if re.search(r"берене", text, re.IGNORECASE): + found.append(_KY_ART_RE) + if re.search(r"артыкул", text, re.IGNORECASE): + found.append(_BE_ART_RE) + if re.search(r"статья|стаття", text, re.IGNORECASE): + found.append(_RU_ART_RE) + if re.search(r"указ|постановление|приказ", text, re.IGNORECASE): + found.append(_RU_INST_RE) + # Preserve order, drop duplicate pattern objects. + out: list = [] + seen: set[int] = set() + for regex in found: + key = id(regex) + if key not in seen: + seen.add(key) + out.append(regex) + return out - Latin TITLE/ARTICLE splits are skipped for languages in - ``profiles.NO_LATIN_SPLIT_LANGS`` so Arabic/Chinese bodies are not - carved up on incidental English words. - """ - from .profiles import latin_split_allowed - if not text or len(text) < 16: - return [] - if language and not latin_split_allowed(language): - return split_script_units(text, language) - matches = list(_HEADING_RE.finditer(text)) - if len(matches) < MIN_SPLIT_HEADINGS: - return [] +def _lexicon_heading_re() -> re.Pattern[str]: + """Heading matcher generated from HEADING_LEXICON so new languages are data.""" + global _LEXICON_HEADING_RE, _LEXICON_KIND + if _LEXICON_HEADING_RE is not None: + return _LEXICON_HEADING_RE + from .profiles import HEADING_LEXICON + + words: list[str] = [] + kinds: dict[str, str] = {} + for token, hits in HEADING_LEXICON.items(): + token = (token or "").strip() + if len(token) < 2: + continue + kinds_found = [kind for kind, _lang in hits if kind in {"article", "section", "title", "chapter", "part"}] + if not kinds_found: + continue + folded = _latin_fold(token) + words.append(folded) + kinds[folded.casefold()] = kinds_found[0] + words.sort(key=len, reverse=True) + escaped = [re.escape(w) for w in words] + _LEXICON_HEADING_RE = re.compile( + _latin_fold( + r"(?im)" + _HEADING_START + r"(?:l['’])?(?P<lex>" + + "|".join(escaped) + + r")(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*(?P<lex_n>" + + _ARTICLE_N + + r")\)?" + ) + ) + _LEXICON_KIND = kinds + return _LEXICON_HEADING_RE + + +def _plausible_cw_number(raw: str) -> bool: + """Drop year-like '1902. Amendment' titles from keyword-less numbering.""" + digits = re.sub(r"\D", "", raw or "") + if not digits: + return False + value = int(digits) + if value <= 0 or value > 2000: + return False + if 1800 <= value <= 2099: + return False + return True + + +def _fold_digits_in_number(raw: str) -> str: + """Map Nd digits (١, १, ๑, …) to ASCII so retrieval numbers stay decimal.""" + if not raw: + return raw + out: list[str] = [] + changed = False + for ch in raw: + if unicodedata.category(ch) == "Nd": + digit = unicodedata.digit(ch) + if digit is not None: + mapped = str(digit) + out.append(mapped) + if mapped != ch: + changed = True + continue + out.append(ch) + return "".join(out) if changed else raw + + +def _unicode_digit_runs(text: str) -> list[str]: + """ASCII-fold Nd runs (Thai ๑, Myanmar ၁, Arabic-Indic, …).""" + runs: list[str] = [] + cur: list[str] = [] + for char in text: + if unicodedata.category(char) == "Nd": + cur.append(str(unicodedata.digit(char))) + elif cur: + runs.append("".join(cur)) + cur = [] + if cur: + runs.append("".join(cur)) + return runs + + +_AR_ORDINAL_NUM = ( + ("الحادية عشرة", "11"), + ("الثانية عشرة", "12"), + ("الثالثة عشرة", "13"), + ("الرابعة عشرة", "14"), + ("الخامسة عشرة", "15"), + ("السادسة عشرة", "16"), + ("السابعة عشرة", "17"), + ("الثامنة عشرة", "18"), + ("التاسعة عشرة", "19"), + ("الحادية والعشرون", "21"), + ("الثانية والعشرون", "22"), + ("الثالثة والعشرون", "23"), + ("الرابعة والعشرون", "24"), + ("الخامسة والعشرون", "25"), + ("السادسة والعشرون", "26"), + ("السابعة والعشرون", "27"), + ("الثامنة والعشرون", "28"), + ("التاسعة والعشرون", "29"), + ("العشرون", "20"), + ("الأولى", "1"), + ("الأولي", "1"), + ("األولى", "1"), + ("الاولى", "1"), + ("الثانية", "2"), + ("الثالثة", "3"), + ("الرابعة", "4"), + ("الخامسة", "5"), + ("السادسة", "6"), + ("السابعة", "7"), + ("الثامنة", "8"), + ("التاسعة", "9"), + ("العاشرة", "10"), + ("الأول", "1"), + ("الاول", "1"), + ("الثاني", "2"), + ("الثالث", "3"), + ("الرابع", "4"), + ("الخامس", "5"), + ("السادس", "6"), + ("السابع", "7"), + ("الثامن", "8"), + ("التاسع", "9"), + ("العاشر", "10"), +) +_HE_VALUES = { + "א": 1, "ב": 2, "ג": 3, "ד": 4, "ה": 5, "ו": 6, "ז": 7, "ח": 8, "ט": 9, + "י": 10, "כ": 20, "ך": 20, "ל": 30, "מ": 40, "ם": 40, "נ": 50, "ן": 50, + "ס": 60, "ע": 70, "פ": 80, "ף": 80, "צ": 90, "ץ": 90, "ק": 100, + "ר": 200, "ש": 300, "ת": 400, +} +_HE_ORDINAL_NUM = ( + ("ראשונה", "1"), + ("שנייה", "2"), + ("שניה", "2"), + ("שלישית", "3"), + ("רביעית", "4"), + ("חמישית", "5"), + ("שישית", "6"), +) +_ETH_VALUES = { + "፩": 1, "፪": 2, "፫": 3, "፬": 4, "፭": 5, "፮": 6, "፯": 7, "፰": 8, "፱": 9, + "፲": 10, "፳": 20, "፴": 30, "፵": 40, "፶": 50, "፷": 60, "፸": 70, "፹": 80, "፺": 90, + "፻": 100, "፼": 10000, +} +_FA_ORDINAL_NUM = ( + ("دوازدهم", "12"), + ("سیزدهم", "13"), + ("چهاردهم", "14"), + ("پانزدهم", "15"), + ("شانزدهم", "16"), + ("هفدهم", "17"), + ("هجدهم", "18"), + ("نوزدهم", "19"), + ("یازدهم", "11"), + ("بیستم", "20"), + ("چهارم", "4"), + ("چارم", "4"), + ("جارم", "4"), + ("پنجم", "5"), + ("ششم", "6"), + ("هفتم", "7"), + ("هشتم", "8"), + ("نهم", "9"), + ("دهم", "10"), + ("سوم", "3"), + ("دوم", "2"), + ("اولی", "1"), + ("اول", "1"), + ("نخست", "1"), +) +_CJK_DIGIT = { + "零": 0, "〇": 0, "一": 1, "二": 2, "三": 3, "四": 4, + "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, +} + + +def _cjk_numeral_value(text: str) -> str | None: + body = re.sub(r"[第条條項款章编編节節之조항호편절、]", "", text) + if not body or not all(ch in _CJK_DIGIT or ch == "十" or ch == "百" for ch in body): + return None + if body == "十": + return "10" + if body.startswith("十"): + return str(10 + _CJK_DIGIT.get(body[1], 0)) + if "百" in body: + left, right = body.split("百", 1) + if not left: + hundreds = 100 + elif left in _CJK_DIGIT: + hundreds = _CJK_DIGIT[left] * 100 + else: + return None + if not right: + return str(hundreds) + rest = _cjk_numeral_value(right) + if rest is None: + return None + return str(hundreds + int(rest)) + if "十" in body: + left, right = body.split("十", 1) + tens = _CJK_DIGIT.get(left, 0) * 10 + ones = _CJK_DIGIT.get(right, 0) if right else 0 + return str(tens + ones) + if body in _CJK_DIGIT: + return str(_CJK_DIGIT[body]) + return None + + +def _circled_to_int(char: str) -> str | None: + if not char: + return None + code = ord(char[0]) + if 0x2460 <= code <= 0x2473: + return str(code - 0x2460 + 1) + if 0x2474 <= code <= 0x2487: + return str(code - 0x2474 + 1) + if 0x2488 <= code <= 0x249B: + return str(code - 0x2488 + 1) + if 0x2776 <= code <= 0x277F: + return str(code - 0x2776 + 1) + if 0x24EB <= code <= 0x24F4: + return str(code - 0x24EB + 11) + return None + + +def _ethiopic_numeral_value(text: str) -> str | None: + chars = [ch for ch in text if ch in _ETH_VALUES] + if not chars: + return None + body = "".join(chars) + if "፼" in body: + left, right = body.split("፼", 1) + mul = _ethiopic_numeral_value(left) if left else "1" + rest = _ethiopic_numeral_value(right) if right else "0" + if mul is None or rest is None: + return None + return str(int(mul) * 10000 + int(rest)) + if "፻" in body: + left, right = body.split("፻", 1) + mul = sum(_ETH_VALUES[ch] for ch in left) if left else 1 + rest = sum(_ETH_VALUES[ch] for ch in right) + return str(mul * 100 + rest) + return str(sum(_ETH_VALUES[ch] for ch in chars)) + + +def _hebrew_letter_num(raw: str) -> str | None: + """Map פרק א' / תוספת שניה / סעיף יא to decimal. Long Hebrew words stay unmapped.""" + cleaned = re.sub(r"['׳״\"`]", "", raw) + for word, num in _HE_ORDINAL_NUM: + if word in cleaned: + return num + katan = re.search(r"סעיף\s+קטן\s*\(?\s*([א-ת])", cleaned) + if katan: + ch = katan.group(1) + return str(_HE_VALUES[ch]) if ch in _HE_VALUES else ch + match = re.search(r"(?:פרק|סימן|חלק|תוספת|סעיף)\s*(?!קטן)([א-ת]{1,3})", cleaned) + if not match: + return None + total = sum(_HE_VALUES.get(ch, 0) for ch in match.group(1)) + return str(total) if total else None + + +def _script_hit_kind(regex: re.Pattern[str]) -> str: + if regex is _RU_TITLE_RE or regex is _TH_LAK_RE: + return "title" + if regex in ( + _HE_PEREK_RE, _AR_BAB_RE, _TH_HUAT_RE, _CJK_ZHANG_RE, _KO_JANG_RE, + _RU_CHAP_RE, _KM_CHAP_RE, _MY_CHAP_RE, _KA_CHAP_RE, _HY_CHAP_RE, _AM_CHAP_RE, + _HI_CHAP_RE, _BN_CHAP_RE, _UR_CHAP_RE, _FA_FASL_RE, _NE_CHAP_RE, + ): + return "chapter" + if regex in (_HE_HELEK_RE, _AR_KITAB_RE, _CJK_BIAN_RE, _KO_PYEON_RE, _LO_PART_RE, _SR_PART_RE): + return "part" + if regex in ( + _HE_SIMAN_RE, + _HE_TOS_RE, + _HE_TAKANA_RE, + _HE_PARA_RE, + _HE_KATAN_RE, + _AR_ANNEX_RE, + _AR_PARA_RE, + _AR_FASL_RE, + _AR_FARA_RE, + _JA_KOU_RE, + _ZH_KUAN_RE, + _KO_HANG_RE, + _KO_HO_RE, + _TH_PARA_RE, + _TH_KHO_RE, + _TH_TON_RE, + _FA_TAB_RE, + _FA_BAND_RE, + _AR_POINT_RE, + _CJK_JIE_RE, + _KO_JEOL_RE, + ): + return "section" + return "article" + + +def _script_article_number(raw: str) -> str: + stripped = raw.strip() + for word, num in _AR_POINT_NUM: + if stripped.startswith(word): + return num + compact = raw.strip().strip("()[] \t\u3001\uff08\uff09.、-–—") + circled = _circled_to_int(compact) + if circled: + return circled + if compact and len(compact) <= 3: + first = compact[0] + if first in _HANGUL_GA: + return str(_HANGUL_GA.index(first) + 1) + if first in _KATA_ENUM: + return str(_KATA_ENUM.index(first) + 1) + if first in _AR_ABJAD_INDEX: + return _AR_ABJAD_INDEX[first] + if first in _HE_ALEF: + return str(_HE_ALEF.index(first) + 1) + if first in _TH_KO: + return str(_TH_KO.index(first) + 1) + low = first.casefold() + if low in _CYR_AB: + return str(_CYR_AB.index(low) + 1) + if low in _EL_AB: + return str(_EL_AB.index(low) + 1) + if first in _KA_AB: + return str(_KA_AB.index(first) + 1) + if first in _HY_AB: + return str(_HY_AB.index(first) + 1) + cjk_early = _cjk_numeral_value(compact) + if cjk_early: + return cjk_early + he = _hebrew_letter_num(raw) + if he: + return he + digits = _unicode_digit_runs(raw) + if digits: + if len(digits) >= 2 and re.search(r"[0-9٠-٩۰-۹]+-[0-9٠-٩۰-۹]+", raw): + return "-".join(digits[:2]) + return digits[0] + eth = _ethiopic_numeral_value(raw) + if eth: + return eth + compact = re.sub(r"[\s\u0640]+", "", raw) + for word, num in _AR_ORDINAL_NUM + _FA_ORDINAL_NUM: + needle = re.sub(r"[\s\u0640]+", "", word) + if needle and needle in compact: + return num + cjk = _cjk_numeral_value(compact) + if cjk: + return cjk + tail = re.search(r"([0-9٠-٩۰-۹]+|[IVXLCDM]{1,8})$", compact) + if tail: + return tail.group(1) + return compact + + +def _in_range_boilerplate(text: str, start: int) -> bool: + for regex in (_KO_RANGE_RE, _CJK_RANGE_RE): + for match in regex.finditer(text): + if match.start() <= start < match.end(): + return True + return False + + +def _kind_number_from_heading_match(match: re.Match) -> tuple[str, str]: + for name in ("title", "chapter", "part", "article", "section"): + if match.group(name): + return name, (match.group(f"{name}_n") or "").strip() + if match.group("section_sym"): + return "section", (match.group("section_sym_n") or "").strip() + if match.group("section_pre"): + return "section", (match.group("section_pre_n") or "").strip() + if match.group("grein"): + return "article", (match.group("grein_n") or "").strip() + if match.group("straipsnis"): + return "article", (match.group("straipsnis_n") or "").strip() + if match.group("artikulua"): + return "article", (match.group("artikulua_n") or "").strip() + if match.group("ledd"): + return "section", (match.group("ledd_n") or "").strip() + if match.group("kap"): + return "chapter", (match.group("kap_n") or "").strip() + if match.group("luku"): + return "chapter", (match.group("luku_n") or "").strip() + if match.group("fejezet"): + return "chapter", (match.group("fejezet_n") or "").strip() + if match.group("peatukk"): + return "chapter", (match.group("peatukk_n") or "").strip() + if match.group("skyrius"): + return "chapter", (match.group("skyrius_n") or "").strip() + if match.group("nodala"): + return "chapter", (match.group("nodala_n") or "").strip() + if match.group("kafli"): + return "chapter", (match.group("kafli_n") or "").strip() + if match.group("bob"): + return "chapter", (match.group("bob_n") or "").strip() + if match.group("tarau"): + return "chapter", (match.group("tarau_n") or "").strip() + if match.group("bolum"): + return "chapter", (match.group("bolum_n") or "").strip() + if match.group("modda"): + return "article", (match.group("modda_n") or "").strip() + if match.group("mn"): + return "article", (match.group("mn_n") or "").strip() + if match.group("kk"): + return "article", (match.group("kk_n") or "").strip() + if match.group("disp"): + return "article", (match.group("disp_n") or "").strip() + if match.group("mom"): + return "section", (match.group("mom_n") or "").strip() + if match.group("order"): + return "section", (match.group("order_n") or "").strip() + if match.group("kidogo"): + return "section", (match.group("kidogo_n") or "").strip() + if match.group("esresol"): + word = _latin_fold(match.group("esresol") or "").casefold() + return "section", { + "primero": "1", "segundo": "2", "tercero": "3", "cuarto": "4", + "quinto": "5", "sexto": "6", "septimo": "7", "octavo": "8", + "noveno": "9", "decimo": "10", + "erstens": "1", "zweitens": "2", "drittens": "3", "viertens": "4", "funftens": "5", + "premierement": "1", "deuxiemement": "2", "troisiemement": "3", + "quatriemement": "4", "cinquiemement": "5", + }.get(word, word) + return "", "" + + +@dataclass +class _Hit: + start: int + kind: str + number: str + heading: str + + +_PAREN_XREF_RE = re.compile( + r"(?i)^\s*(?:\([a-z0-9]{1,4}\))?\s+" + r"(?:is|are|or|and|of|have|has|was|were|by|to|for|from|in|that|shall)\b" +) + + +def _paren_letter_xref(raw: str, number: str, rest: str) -> bool: + """Skip 'paragraph (i) or …' / 'subsection (l)(b) is …' cross-references.""" + if len(number) != 1 or not number.isalpha() or "(" not in raw: + return False + return _PAREN_XREF_RE.match(rest) is not None + + +def _collect_hits(text: str, *, language: str, latin: bool) -> list[_Hit]: + hits: list[_Hit] = [] + folded = _latin_fold(text) if latin else text + if latin: + for match in _HEADING_RE.finditer(folded): + kind, number = _kind_number_from_heading_match(match) + if not kind: + continue + if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]): + continue + if _paren_letter_xref(match.group(0), number, folded[match.end() : match.end() + 48]): + continue + for gname in ( + "title_n", "chapter_n", "part_n", "article_n", "section_n", + "section_sym_n", "section_pre_n", "grein_n", "straipsnis_n", + "artikulua_n", "ledd_n", "kap_n", "luku_n", + "fejezet_n", "peatukk_n", "skyrius_n", "nodala_n", + "kafli_n", "bob_n", "tarau_n", "bolum_n", + "modda_n", "mn_n", "kk_n", "mom_n", "order_n", "kidogo_n", "disp_n", + ): + try: + start, end = match.span(gname) + except IndexError: + continue + if start >= 0: + number = text[start:end] + break + number = _fold_digits_in_number(number.strip().rstrip(".-:–—")) + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), kind, number, heading)) + for match in _lexicon_heading_re().finditer(folded): + if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]): + continue + token = (match.group("lex") or "").casefold() + kind = _LEXICON_KIND.get(token, "article") + start, end = match.span("lex_n") + number = _fold_digits_in_number( + (text[start:end] if start >= 0 else match.group("lex_n") or "").strip().rstrip(".-:–—") + ) + if not number: + continue + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), kind, number, heading)) + for match in _LATIN_LETTER_RE.finditer(text): + letter = match.group("paren") or match.group("bare") + if letter: + number = str(ord(letter) - 96) + else: + number = _ROMAN_LOWER.get(match.group("roman") or "", "") + if not number: + continue + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), "section", number, heading)) + for match in _LATIN_NUM_LIST_RE.finditer(text): + number = ( + match.group("nparen") + or match.group("nclose") + or match.group("nord") + or match.group("ndot") + or match.group("ncolon") + or match.group("ndash") + or "" + ) + dbl = match.group("dbl") + if dbl: + number = str(ord(dbl[0]) - 96) + if not number: + continue + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), "section", number, heading)) + for i, match in enumerate(_BULLET_RE.finditer(text), start=1): + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), "section", str(i), heading)) + for match in _DASH_NUM_RE.finditer(text): + number = (match.group("bn") or "").strip() + if not number: + continue + line_end = text.find("\n", match.start()) + if line_end < 0: + line_end = len(text) + heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] + hits.append(_Hit(match.start(), "section", number, heading)) + for regex in _detected_script_regexes(text, language): + for match in regex.finditer(text): + if _in_range_boilerplate(text, match.start()): + continue + if _SCRIPT_CITE_TAIL_RE.match(text[match.end() : match.end() + 48]): + continue + raw = match.group(0) + number = _fold_digits_in_number(_script_article_number(raw)) + heading = re.sub(r"\s+", " ", raw).strip()[:240] + hits.append(_Hit(match.start(), _script_hit_kind(regex), number, heading)) + if latin: + from .profiles import iso_lang + + lang = iso_lang(language) + keyword_hits = [h for h in hits if h.kind in {"article", "section"}] + if len(keyword_hits) < MIN_SPLIT_HEADINGS and lang in _CW_NUM_LANGS: + for match in _CW_NUM_RE.finditer(text): + number = (match.group("cw_n") or "").strip() + if not _plausible_cw_number(number): + continue + if _MONTH_START_RE.match(text[match.end() : match.end() + 16]): + continue + hits.append( + _Hit( + match.start(), + "section", + number, + match.group(0).strip()[:240], + ) + ) + hits.sort(key=lambda h: (h.start, -len(h.heading))) + merged: list[_Hit] = [] + seen_starts: set[int] = set() + for hit in hits: + if hit.start in seen_starts: + continue + seen_starts.add(hit.start) + merged.append(hit) + return merged + + +def _units_from_hits(text: str, hits: list[_Hit]) -> list[StructureUnit]: + if not hits: + return [ + StructureUnit(kind="preamble", number="", heading="", body=text, char_start=0, char_end=len(text)) + ] cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""} units: list[StructureUnit] = [] - for i, match in enumerate(matches): - start = match.start() - end = matches[i + 1].start() if i + 1 < len(matches) else len(text) - chunk = text[start:end].strip() - kind = "" - number = "" - for name in ("title", "chapter", "part", "article", "section"): - if match.group(name): - kind = name - number = (match.group(f"{name}_n") or "").strip() - break - if match.group("section_sym"): - kind = "section" - number = (match.group("section_sym_n") or "").strip() - if not kind or not number: - continue - cursor[kind] = number + if hits[0].start > 0: + units.append( + StructureUnit( + kind="preamble", + number="", + heading="", + body=text[0 : hits[0].start], + char_start=0, + char_end=hits[0].start, + ) + ) + for i, hit in enumerate(hits): + start = hit.start + end = hits[i + 1].start if i + 1 < len(hits) else len(text) + body = text[start:end] + cursor[hit.kind] = hit.number for lower, rank in _KIND_RANK.items(): - if rank > _KIND_RANK[kind]: + if rank > _KIND_RANK.get(hit.kind, 99): cursor[lower] = "" - if len(chunk) < MIN_UNIT_CHARS: - continue - rest = (match.group("rest") or "").strip(" .-:") - heading = re.sub(r"\s+", " ", match.group(0)).strip() - if rest and rest not in heading: - heading = f"{heading} {rest}".strip() units.append( StructureUnit( - kind=kind, - number=number, - heading=heading[:240], - body=chunk, + kind=hit.kind, + number=hit.number, + heading=hit.heading[:240], + body=body, title_number=cursor["title"], chapter_number=cursor["chapter"], part_number=cursor["part"], article_number=cursor["article"], section_number=cursor["section"], - subsections=_subsection_tokens(chunk), + subsections=_subsection_tokens(body), hierarchy_path=_cursor_path(cursor), + char_start=start, + char_end=end, ) ) - retrieval = [u for u in units if u.kind in {"article", "section"}] - if len(retrieval) >= MIN_SPLIT_HEADINGS: - return retrieval - if len(units) >= MIN_SPLIT_HEADINGS: - return units + return units + + +def segment_exclusive(text: str, *, language: str = "") -> list[StructureUnit]: + """Internal exclusive-span segmentation of *text* (includes preamble).""" + from .profiles import iso_lang, latin_split_allowed + + if not text: + return [] + latin = not language or latin_split_allowed(language) + hits = _collect_hits(text, language=language, latin=latin) + retrieval_like = [h for h in hits if h.kind in {"article", "section"}] + if ( + not latin + and len(retrieval_like) < MIN_SPLIT_HEADINGS + and iso_lang(language) in _LATIN_FALLBACK_LANGS + ): + hits = _collect_hits(text, language=language, latin=True) + return _units_from_hits(text, hits) + + +def split_script_units(text: str, language: str) -> list[StructureUnit]: + """Retrieval projection of script-specific exclusive spans.""" + internal = segment_exclusive(text, language=language) + retrieval = [u for u in internal if u.kind == "article" and len(u.body.strip()) >= 16] + return retrieval if len(retrieval) >= MIN_SPLIT_HEADINGS else [] + + +def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]: + """Retrieval units. Empty list means keep the whole instrument. + + Prefers article/section. When those are scarce, numbered chapter then title + headings (Cameroon CHAPITRE, Bolivia TÍTULO, Cape Verde CAPÍTULO). + """ + if not text or len(text) < 16: + return [] + from .profiles import latin_split_allowed + + internal = segment_exclusive(text, language=language) + + def _take(kinds: set[str]) -> list[StructureUnit]: + out: list[StructureUnit] = [] + for u in internal: + if u.kind not in kinds: + continue + min_len = 16 if u.number else MIN_UNIT_CHARS + if language and not latin_split_allowed(language): + min_len = 16 + if len(u.body.strip()) >= min_len: + out.append(u) + return out + + for kinds in ( + {"article", "section"}, + {"chapter"}, + {"part"}, + {"title"}, + ): + retrieval = _take(kinds) + if len(retrieval) >= MIN_SPLIT_HEADINGS: + return retrieval return [] diff --git a/country_laws_ir/upload.py b/country_laws_ir/upload.py index 182e81b8d9d799dce63653f45feaabdfa3c61e84..46ed2a99675995c8688692d9c03715ad95ada876 100644 --- a/country_laws_ir/upload.py +++ b/country_laws_ir/upload.py @@ -20,10 +20,82 @@ _OPERATOR_HINT = ( ) +CARD_FILES = ( + "README.md", + ".gitattributes", + "manifest.json", + "dataset_configs.json", + "normalization_report.json", +) + + class UploadError(RuntimeError): """Raised when a JusticeDAO upload cannot proceed.""" +def ensure_dataset_card(local_dir: Path) -> Path: + """Write a YAML dataset card if README.md is missing or is a Hub stub.""" + from .package import _write_readme + + local_dir = Path(local_dir) + readme = local_dir / "README.md" + text = readme.read_text(encoding="utf-8") if readme.is_file() else "" + if text.startswith("---") and "pretty_name:" in text: + return readme + manifest_path = local_dir / "manifest.json" + if not manifest_path.is_file(): + raise UploadError(f"cannot build dataset card; missing {manifest_path}") + import json + + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + country = manifest.get("country") or {} + source_meta = manifest.get("source") or { + "source_dataset": manifest.get("dataset_id") or "", + "source_revision": manifest.get("dataset_revision") or "", + } + hub_id = str(manifest.get("dataset_repo_id") or f"{TARGET_ORG}/ipfs_{country.get('slug', 'unknown')}_laws_ir") + _write_readme( + local_dir, + country, + source_meta, + manifest.get("counts") or {}, + manifest.get("bm25") or {}, + manifest.get("graph") or {}, + manifest.get("vector") or {}, + hub_id, + normalization_report=manifest.get("normalization"), + ) + return readme + + +def _commit_dataset_card(api: Any, local_dir: Path, repo_id: str) -> str: + """Always commit README/metadata after parquet upload. + + ``upload_large_folder`` often finishes LFS parquet commits while leaving + a Hub-generated stub README (no YAML card). Regular files are committed + here in a follow-up so the dataset page always has a parseable card. + """ + from huggingface_hub import CommitOperationAdd + + ensure_dataset_card(local_dir) + operations = [] + for name in CARD_FILES: + path = local_dir / name + if path.is_file(): + operations.append( + CommitOperationAdd(path_in_repo=name, path_or_fileobj=str(path)) + ) + if not operations: + return "" + info = api.create_commit( + repo_id=repo_id, + repo_type="dataset", + operations=operations, + commit_message="Add YAML dataset card and release metadata", + ) + return str(getattr(info, "oid", None) or getattr(info, "commit_id", None) or "") + + def _token_from_env() -> str: for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): value = (os.environ.get(key) or "").strip() @@ -92,6 +164,7 @@ def upload_release( n_files = sum(1 for path in local_dir.rglob("*") if path.is_file()) nbytes = sum(path.stat().st_size for path in local_dir.rglob("*") if path.is_file()) use_large = n_files >= 80 or nbytes >= 80 * 1024 * 1024 + method = "upload_folder" if use_large and hasattr(api, "upload_large_folder"): api.upload_large_folder( folder_path=str(local_dir), @@ -99,7 +172,19 @@ def upload_release( repo_type="dataset", ignore_patterns=ignore, ) - revision = "" + method = "upload_large_folder" + else: + api.upload_folder( + folder_path=str(local_dir), + repo_id=repo_id, + repo_type="dataset", + commit_message=commit_message + or f"Incremental country-laws-ir GraphRAG release for {repo_id}", + ignore_patterns=ignore, + ) + card_sha = _commit_dataset_card(api, local_dir, repo_id) + revision = card_sha + if not revision: try: from huggingface_hub import dataset_info as _dataset_info @@ -107,26 +192,10 @@ def upload_release( revision = str(getattr(pinned, "sha", "") or "") except Exception: revision = "" - return { - "url": f"https://huggingface.co/datasets/{repo_id}", - "repo_id": repo_id, - "revision": revision, - "local_dir": str(local_dir), - "method": "upload_large_folder", - } - info = api.upload_folder( - folder_path=str(local_dir), - repo_id=repo_id, - repo_type="dataset", - commit_message=commit_message - or f"Incremental country-laws-ir GraphRAG release for {repo_id}", - ignore_patterns=ignore, - ) - revision = getattr(info, "oid", None) or getattr(info, "commit_id", None) or "" return { "url": f"https://huggingface.co/datasets/{repo_id}", "repo_id": repo_id, "revision": revision, "local_dir": str(local_dir), - "method": "upload_folder", + "method": method, } diff --git a/country_laws_ir/verify.py b/country_laws_ir/verify.py index 1dc7970bebb9471cbe2372dd16dc7e87a63d786f..eabdf7a786538cbcc3a7b3cfda9230b675480a86 100644 --- a/country_laws_ir/verify.py +++ b/country_laws_ir/verify.py @@ -189,6 +189,112 @@ def check_heading_language(corpus: pd.DataFrame, report: dict[str, Any]) -> Chec ) +def check_reconstruction_grounded(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + """Parent reconstructed body must equal glue of child title/number/body.""" + from .reconstruct import expected_glue_from_children + + if corpus is None or corpus.empty: + return Check( + id="reconstruction_grounded", + severity="fail", + passed=True, + message="no corpus", + evidence={}, + ) + if "reconstructed_from_articles" not in corpus.columns: + return Check( + id="reconstruction_grounded", + severity="warn", + passed=True, + message="no reconstruction columns", + evidence={}, + ) + mismatches = 0 + checked = 0 + samples: list[str] = [] + laws = corpus[corpus["record_type"] == "law"] if "record_type" in corpus.columns else corpus + for rec in laws.itertuples(index=False): + if not bool(getattr(rec, "reconstructed_from_articles", False)): + continue + if str(getattr(rec, "reconstruction_gap_note", "") or "") in { + "rss_abort_slug", + "reconstruct_budget", + }: + continue + checked += 1 + iid = str(getattr(rec, "instrument_id", "") or "") + kids = corpus[ + (corpus["instrument_id"] == iid) & (corpus["record_type"].isin(["article", "section"])) + ] + children = [ + { + "id": str(getattr(k, "source_id", "") or ""), + "title": str(getattr(k, "article_title", "") or getattr(k, "title", "") or ""), + "article_number": str(getattr(k, "article_number", "") or ""), + "body": str(getattr(k, "body", "") or ""), + } + for k in kids.itertuples(index=False) + ] + expected = expected_glue_from_children(children) + body = str(getattr(rec, "body", "") or "") + if bool(getattr(rec, "reconstruction_truncated", False)): + if not expected.startswith(body) and body != expected[: len(body)]: + mismatches += 1 + if len(samples) < 5: + samples.append(iid) + continue + if body != expected: + mismatches += 1 + if len(samples) < 5: + samples.append(iid) + ok = mismatches == 0 + return Check( + id="reconstruction_grounded", + severity="fail", + passed=ok, + message="reconstructed parents match child glue" if ok else f"{mismatches} reconstructed parents fail glue", + evidence={"checked": checked, "mismatches": mismatches, "samples": samples}, + ) + + +def check_empty_parents_reconstructed(report: dict[str, Any]) -> Check: + n = int(report.get("n_empty_parents_with_articles_not_reconstructed") or 0) + return Check( + id="empty_parents_with_articles", + severity="fail", + passed=n == 0, + message="eligible empty parents all have law rows" if n == 0 else f"{n} empty parents with articles were dropped", + evidence={"n_empty_parents_with_articles_not_reconstructed": n}, + ) + + +def check_parent_laws(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: + """Fail if source had instruments but GraphRAG corpus has no law rows.""" + n_in = int(report.get("n_laws_in") or 0) + n_law_rows = 0 + if corpus is not None and not corpus.empty and "record_type" in corpus.columns: + n_law_rows = int((corpus["record_type"] == "law").sum()) + n_law_rows = int(report.get("n_law_rows") or n_law_rows) + if n_in > 0 and n_law_rows == 0: + return Check( + id="parent_laws", + severity="fail", + passed=False, + message=( + f"source has {n_in} laws but corpus has 0 law rows " + "(articles were indexed without parent instruments)" + ), + evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows}, + ) + return Check( + id="parent_laws", + severity="warn", + passed=True, + message=f"parent instruments present ({n_law_rows} law rows from {n_in} source laws)", + evidence={"n_laws_in": n_in, "n_law_rows": n_law_rows}, + ) + + def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: unit = str(report.get("unit") or "") n = int(len(corpus)) if corpus is not None else 0 @@ -204,7 +310,7 @@ def check_structure(corpus: pd.DataFrame, report: dict[str, Any]) -> Check: coverage = structured_rows / float(n) if n else 0.0 # Article or structured units are success. Pure law-level is a warning, not a fail: # many gazettes have no title/section markers. - if unit in {"article", "structured"} or coverage >= 0.5: + if unit in {"article", "structured", "law+article", "law+structured"} or coverage >= 0.5: return Check( id="legal_structure", severity="warn", @@ -237,6 +343,9 @@ def verify_normalized_corpus( check_no_invented_text(report), check_html_residual(corpus), check_short_bodies(corpus), + check_parent_laws(corpus, report), + check_reconstruction_grounded(corpus, report), + check_empty_parents_reconstructed(report), check_structure(corpus, report), check_heading_language(corpus, report), ] diff --git a/data/bm25/documents/part-000000.parquet b/data/bm25/documents/part-000000.parquet index 8d073956d4d70f240f300e2b4e3c9f3aef6ce135..9e1ed4cf831972bd2e5905c07b2de09eb831b3ca 100644 --- a/data/bm25/documents/part-000000.parquet +++ b/data/bm25/documents/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1ada5fae09d58135ef1645f7f78dc3bdd06b1493ae20df8f8047590ac12d6a2f -size 485765 +oid sha256:c065888f2fa474839976520b843b3f73b1ebb7220b8212002c73a4af9b03aee0 +size 487355 diff --git a/data/bm25/documents/part-000001.parquet b/data/bm25/documents/part-000001.parquet index 70eaaf26773168dba9e7953526b67db570ec703b..4535ac7a9687d0074c70db0ef94a53ead7646e03 100644 --- a/data/bm25/documents/part-000001.parquet +++ b/data/bm25/documents/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c5fe5409215e3118d72822421f12a454682e0f6828d2162e37995215e48ad634 -size 500552 +oid sha256:33c4cfa9da4305c1b56574a56763bb6c4d0ae5351bd3b4c665ed0b3bf1385076 +size 499835 diff --git a/data/bm25/documents/part-000002.parquet b/data/bm25/documents/part-000002.parquet index 8d1516b5ef8b36ef52ae6ee770be1e99d20cbc05..eb9e1ebc8dc679e482daa34fa9a9149714dc34aa 100644 --- a/data/bm25/documents/part-000002.parquet +++ b/data/bm25/documents/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5b5359219edeb4045c55fbf76ed8148d169c03a6f6aff51582b7d21236fb79b8 -size 493519 +oid sha256:f932e4f8db660e61f9e3a50c6cf8a9a699a7080c004961113fce21080075f4f8 +size 496432 diff --git a/data/bm25/documents/part-000003.parquet b/data/bm25/documents/part-000003.parquet index 97149376c0b1abf4a0b7f8cb2380052ad219937d..99cd4371f260d95a2265091ba47c53f911d3c678 100644 --- a/data/bm25/documents/part-000003.parquet +++ b/data/bm25/documents/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f874dd51f305437ca93c5fa0e84f311e97c5b33a4af799145df5cbbc0257ed72 -size 504590 +oid sha256:8b6e26b576989d30ab82a247e594d53147a93614ba142ad8062b2968c8deb4b7 +size 505482 diff --git a/data/bm25/documents/part-000004.parquet b/data/bm25/documents/part-000004.parquet index e844b8a9ad47c38a54eccaf80642ee3c8aa7eddf..9ca5df9891f96c21832285ec37726ea21fc5c376 100644 --- a/data/bm25/documents/part-000004.parquet +++ b/data/bm25/documents/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a94fd1bd4edec8b47f31a0d3d43aa9fac5d895914da15f31738b39850a03e6ff -size 511334 +oid sha256:5d70d64239199657eb35485dcc6cd8ec71b736a00d5917e52210d68978752f1b +size 508799 diff --git a/data/bm25/documents/part-000005.parquet b/data/bm25/documents/part-000005.parquet index 84608985f1b70b1a01055092e1349a338b23f6f9..8c01d1ebbc57148c83f854f8b59becd29ccdbbcd 100644 --- a/data/bm25/documents/part-000005.parquet +++ b/data/bm25/documents/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f693b1044c5963279d63a602e55c05690888810a27213bbdaabf070bc72cec7 -size 501837 +oid sha256:aadb7ff28df7bbf4fccf3d674394ada91b053b0962f26201d74322802a311e6c +size 503667 diff --git a/data/bm25/documents/part-000006.parquet b/data/bm25/documents/part-000006.parquet index 3ed8b25b89c199f85b452b16f325b7d948856170..33bc7d31411a1d2886e018ee6292758e3ff61be9 100644 --- a/data/bm25/documents/part-000006.parquet +++ b/data/bm25/documents/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6f63d9ef8337cbb98dedfb6333d6ab0b9dc3cd876f9f8fbcf2415eb85c94e937 -size 492502 +oid sha256:4221184bd101a67f482e294edd7cb6c7b7c90f2312c845821ca1d870f77b89cd +size 491080 diff --git a/data/bm25/documents/part-000007.parquet b/data/bm25/documents/part-000007.parquet index 24370d68f1c2baf0178b2a0f9f0f61d502114544..cc99067e34886eb6882b13d701c87b6598342ffa 100644 --- a/data/bm25/documents/part-000007.parquet +++ b/data/bm25/documents/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9fe10c5f024c3650781edc91b02c4a7da72bd0ca337cf5247274b48346f08b7f -size 491187 +oid sha256:60131bcfe18a60db2afd1173710b221c2029b5dd7e79ea4547e8214c2142a84b +size 495553 diff --git a/data/bm25/documents/part-000008.parquet b/data/bm25/documents/part-000008.parquet index c6be9d55b21bc730be540a94c2d30991b031eafd..d969c285729351621ca9a041eff077378220eb09 100644 --- a/data/bm25/documents/part-000008.parquet +++ b/data/bm25/documents/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0f8b1fa359c62f8efb1a267c0c62397e210a9cdc406b84bda7fec513926878be -size 495217 +oid sha256:3ea0a30937ff871b93bb02aaedba6d13ccccf296a47842399c2ec202f6aec086 +size 491408 diff --git a/data/bm25/documents/part-000009.parquet b/data/bm25/documents/part-000009.parquet index ac5f65de7f2183dc09fe2d68b4651a14c919f2b0..45a85e0a9bd2087ce3a4d7b2916f27edd7aefd24 100644 --- a/data/bm25/documents/part-000009.parquet +++ b/data/bm25/documents/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:01a2e1b45faab56e53d7a01cf410844be4eafe74c55fb038b47e9106e85cc80f -size 489021 +oid sha256:e88cc12717e9ba4abdba3b16c4ab5a6c02ef53891a935167abf5b14b4e0d579d +size 497033 diff --git a/data/bm25/documents/part-000010.parquet b/data/bm25/documents/part-000010.parquet index 1830f9d74e62e19a255a151cfe17d3c334134c70..4bbb35ae643457e8c3b255a83b88474066449991 100644 --- a/data/bm25/documents/part-000010.parquet +++ b/data/bm25/documents/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e850482bd3bcbc617145a72b44e17e29d47231e0b26dc4eede808b30e6af9964 -size 498169 +oid sha256:73cdacdb7a8110be019adcf103fc21656301bdcdb686687d104e669b7b31ba93 +size 499525 diff --git a/data/bm25/documents/part-000011.parquet b/data/bm25/documents/part-000011.parquet index b831fa29eb155155ad541eb6d5b1d36fbe7fe641..0c70e9626aa6ed909f2e4c03229d13100c3b46ac 100644 --- a/data/bm25/documents/part-000011.parquet +++ b/data/bm25/documents/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:aa522d4d6a2e21e8b09b5471a778fad204bd11232b5d29820fbca5a11b2d8b2c -size 492893 +oid sha256:aade0bbc484f9df761b9e2ee8fda8d364c85333feea6244128fbfbd54983caa6 +size 486245 diff --git a/data/bm25/documents/part-000012.parquet b/data/bm25/documents/part-000012.parquet index cd1ea442ae52e54e794ad4da900806ac7e12ce0d..09fa00496974ee6b44402d18899f134a92232272 100644 --- a/data/bm25/documents/part-000012.parquet +++ b/data/bm25/documents/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fa2203761e3cef8efdfa9cfb052f3a4ae30c02043280765c2eaa8c53099241ef -size 505169 +oid sha256:2c135c68403f885f15cb75a703dcc26312f12fe06731160286b21bddfff776de +size 506424 diff --git a/data/bm25/documents/part-000013.parquet b/data/bm25/documents/part-000013.parquet index bc7109477c9dcb0f51005cd2ee6fbadb9a4d8226..77f5f18baecb92dc2ff16acd99b6eec6728d5bd0 100644 --- a/data/bm25/documents/part-000013.parquet +++ b/data/bm25/documents/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3ea80ce60cfd6d321c4ba909a4a0de616a2b85af7d427f775fb9660e8c883563 -size 505845 +oid sha256:a39472d09ac724b3eabb51c82a22f5e727c1fc270e06d462d202a14cfb148cf9 +size 503267 diff --git a/data/bm25/documents/part-000014.parquet b/data/bm25/documents/part-000014.parquet index 28e85d83b1573843afc4d59243604e6c29150886..432f2fa792b1ae9088577e8c4b1da88c6c34a57b 100644 --- a/data/bm25/documents/part-000014.parquet +++ b/data/bm25/documents/part-000014.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:29897aa12312df023973dab20b209686a48d48f0e7fdc60c0b7322e854b4fb02 -size 510681 +oid sha256:c52f49df87a9f730f6a0f67c1b07c2be5bff91713985091456d7557c54fc147c +size 509448 diff --git a/data/bm25/documents/part-000015.parquet b/data/bm25/documents/part-000015.parquet index d6385796e28ecac51ba0734527863600f6c14395..154e1eed8efb3570dcaea5dcc464fe796125d88f 100644 --- a/data/bm25/documents/part-000015.parquet +++ b/data/bm25/documents/part-000015.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:24a242b100292efff447aa3782b06bc95edb7e263bcc7036e5d72bf0b62d20fb -size 503781 +oid sha256:606fc7335bdc010b17b952a166cc3dcd02c08cf4b0ca3bfc9206ab8d747108b2 +size 505179 diff --git a/data/bm25/documents/part-000016.parquet b/data/bm25/documents/part-000016.parquet index 2451383e958d3d922054f979f516de879444eca3..2dfb5a61701d38e40def29a2df0c3e432fa9a882 100644 --- a/data/bm25/documents/part-000016.parquet +++ b/data/bm25/documents/part-000016.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2d75a78e2112ad28998721c636a8e717ae0f4a78550f4bd13cd263e20fa4c46c -size 504733 +oid sha256:651dd7262cd268fef95c3f7582e64d8708fc8ffa193cd62cbbeee8ec980ee16d +size 504075 diff --git a/data/bm25/documents/part-000017.parquet b/data/bm25/documents/part-000017.parquet index 7f5a7ede1a9f2f4f27a4256f00e97337d1c5791a..5ecfd1f2417f66ad46d1769afb897edfbedd6e5a 100644 --- a/data/bm25/documents/part-000017.parquet +++ b/data/bm25/documents/part-000017.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c74e39b3e3d9a6b993b96d9f4cbcd4978a2a9cd1d02d672c8563ac186de6a2c2 -size 505458 +oid sha256:40585ca151a898ec18cca8b768ab12e34557b89a94aba8969e09b4c105126d4a +size 508869 diff --git a/data/bm25/documents/part-000018.parquet b/data/bm25/documents/part-000018.parquet index 175373b0442adb548415c3a9739e7c1139686cb9..43740dd123e32dd0260e705f0e71a02605aff789 100644 --- a/data/bm25/documents/part-000018.parquet +++ b/data/bm25/documents/part-000018.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:777187d045bb2afd4aa0e3cf3aa3b6ac0fe02959407f98940314286c57e6ad89 -size 503853 +oid sha256:52507a9a5ab48090b64835391cc054af772bbf2e2c2d56971b9453d85dec65f9 +size 497969 diff --git a/data/bm25/documents/part-000019.parquet b/data/bm25/documents/part-000019.parquet index 7f98d3b286a24309cf34afe828a0f205a09b476e..b5bc3d3421cf4915c78157ffb65bc00bbe6cfdb7 100644 --- a/data/bm25/documents/part-000019.parquet +++ b/data/bm25/documents/part-000019.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:acb2f36540b23ec2037b1e6ff95a40d6579d9f3de2310313684c0015ef818e22 -size 510549 +oid sha256:96bd435a1f4c9d5d8c983fc69fee16de39447e53ad2e1f263e3e41a6f81d5e3c +size 509130 diff --git a/data/bm25/documents/part-000020.parquet b/data/bm25/documents/part-000020.parquet index ef939f6a551c4ec0c161d709cec1cc70ba1d4ed2..526f5bd47112d7a59d12a380bdb8782020a02ac3 100644 --- a/data/bm25/documents/part-000020.parquet +++ b/data/bm25/documents/part-000020.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fdf9523612f067bc2218a3f844732b672bc1fee1fe97e120f0e09222801ce676 -size 457111 +oid sha256:9195d312ed4d1571bbf817bd26534b73b8ea672ffa4ff20879910df69bec30dd +size 510976 diff --git a/data/bm25/documents/part-000021.parquet b/data/bm25/documents/part-000021.parquet new file mode 100644 index 0000000000000000000000000000000000000000..721f5be570ec360918f5a01130edbdaf01c41432 --- /dev/null +++ b/data/bm25/documents/part-000021.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2698657a4d2ada690fd26638bfa1558df286165122449c87639c3f9cc128d9e7 +size 167437 diff --git a/data/bm25/postings/part-000000.parquet b/data/bm25/postings/part-000000.parquet index 11e4c6715c864b2f523be9dc4d17e1e6b9ae2df4..e3a0b7226662fd12bfa25187b9bc556abfcd39a5 100644 --- a/data/bm25/postings/part-000000.parquet +++ b/data/bm25/postings/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:65d6b559f4c232f41ea33e9bd9322c5429e05afb3fe3273f06b6b1e6556ca273 -size 1279186 +oid sha256:5ab9f72fdcc94217d83a66e6fb95be8d37fcb74c620b6b6a9b88dca120548f41 +size 1510373 diff --git a/data/bm25/postings/part-000001.parquet b/data/bm25/postings/part-000001.parquet index d55ca04f24da4fe16d717d793837702a2ceb6ab9..32aab2e7aa5019b4f042e031f921ebe4020f2d76 100644 --- a/data/bm25/postings/part-000001.parquet +++ b/data/bm25/postings/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:31c1bfcd48764824c09228e08e907d8ca73a1e69303fccec40e7667b1f100895 -size 735360 +oid sha256:675f800946e884d40ff3955f92772aa7b7bc0e3a94a5cb35682bfee6cfba9f77 +size 733010 diff --git a/data/bm25/postings/part-000002.parquet b/data/bm25/postings/part-000002.parquet index 167db6532084f2c37c0aaa8734514ba823e8ea21..7e92dd920f816b4ccf1cafafb3c6592fa853e9c3 100644 --- a/data/bm25/postings/part-000002.parquet +++ b/data/bm25/postings/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4b1b538688853a1df4995baa73732b1fe51f7d866901c66277b2c8fa1434f3c7 -size 351924 +oid sha256:8072e5221dc876526181f556634aa7dc8c38e786f2004c91027a750e2a51c99a +size 461247 diff --git a/data/bm25/postings/part-000003.parquet b/data/bm25/postings/part-000003.parquet index 64b88069a84613850398cbbd1e8b31c6ee9af1fd..a57635cf3eb1aa45e7ad3538edd4766983b0893d 100644 --- a/data/bm25/postings/part-000003.parquet +++ b/data/bm25/postings/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:61b39dc3e19668d597ae41d536306f230e939600a1d8cbc4b184c5ccb3715df2 -size 1713442 +oid sha256:c521363e48e54681de87c993e44b977799b994f913dfe5e3514572194319bc13 +size 1702990 diff --git a/data/bm25/postings/part-000004.parquet b/data/bm25/postings/part-000004.parquet index 82df1cddeedcae0327e7ab1933dbd4759b774d9d..d95f4d7736019f047bbe7f5526c2e7e18343fec1 100644 --- a/data/bm25/postings/part-000004.parquet +++ b/data/bm25/postings/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3d19eec6b77d4477a8fed23911ec0040926d5bc7c4cd5ef1071ebc7e81901381 -size 1321551 +oid sha256:5f3fe8b91a0ce717c1967e30b0823ba2d008f86e509dcb4039e03503f6e92038 +size 1299935 diff --git a/data/bm25/postings/part-000005.parquet b/data/bm25/postings/part-000005.parquet index 2dbbe3d688a9db686db4a028980f513bff0888bc..6456d5c5eaa7b6d1f4e46d5c285cece27b26dbfd 100644 --- a/data/bm25/postings/part-000005.parquet +++ b/data/bm25/postings/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5230a0a90a0700384b4a05a171225c5e41bf4f2866ef31fe6d8889b0df69d4cc -size 1300168 +oid sha256:f0dc34df9f7466a34ab48a2dd4c2b8e89ea5ff5555d5d565e72dd7418df96df9 +size 1413889 diff --git a/data/bm25/postings/part-000006.parquet b/data/bm25/postings/part-000006.parquet index debd27c1488ff7e6182ab27b8b6f2d1f97ef847d..ea19b1c81324a22cadafceed508508e69fe0a820 100644 --- a/data/bm25/postings/part-000006.parquet +++ b/data/bm25/postings/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9f31651055262a42c3ad7cf0d12cb04c60116819e11db7247dc32d99d6fd8847 -size 1331255 +oid sha256:2f73d9ef084b60ed29204ffff6939377dd4f8524a7d8c709f73cdd3017598d9d +size 1127398 diff --git a/data/bm25/postings/part-000007.parquet b/data/bm25/postings/part-000007.parquet index 781a345dd2c649b73b897ee7b56f3d5671f29db1..3ef5600b7ee1b0c873868dc123d63eb7f0f90ccc 100644 --- a/data/bm25/postings/part-000007.parquet +++ b/data/bm25/postings/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c51dadd320e183f9540d2c7a4900604f8fd561e8eefa76e67a6333bdd4226efa -size 301342 +oid sha256:5d7aa7b36cb181c741c65f40df6938d45d53f38c479c122ad7e3dc15bf15970e +size 1340915 diff --git a/data/bm25/postings/part-000008.parquet b/data/bm25/postings/part-000008.parquet index b7c964efccd8954d0a4ab3803d996fe26e72416f..7b04d9ea33c7519d8b5c54084452821aa52b4648 100644 --- a/data/bm25/postings/part-000008.parquet +++ b/data/bm25/postings/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7a1846e9b845a72bb504b46abd61cf102cfb0f0bd5958a092f81c261c3d13e2a -size 1717430 +oid sha256:da57c3173215118303008ecbf0e8f10fa502ce4c570791a8e835a6307d60a361 +size 717091 diff --git a/data/bm25/postings/part-000009.parquet b/data/bm25/postings/part-000009.parquet index d7484651563db1c94f71b733a9f375596ceac658..06b742070e242f6900ace35e6579e2b7519f573e 100644 --- a/data/bm25/postings/part-000009.parquet +++ b/data/bm25/postings/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:98037d0c1ff0b3d68f71a5c0bc52a0687306eef024794e31506f804d72f64e5a -size 1570565 +oid sha256:12cc94246a6521309d017c78cb21aa505f72fe96caeb1b3aa106521b5bc9e0ff +size 1533387 diff --git a/data/bm25/postings/part-000010.parquet b/data/bm25/postings/part-000010.parquet index fc2fe4bcec3ebccfbf703e619c8695f5ad3b03d8..50e3851e9b594128a9e12016a169e3c2e2196907 100644 --- a/data/bm25/postings/part-000010.parquet +++ b/data/bm25/postings/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6c1807a583be985de9f90c1cc783fc655e058192186be7e1a00a995a8f0b984c -size 1411806 +oid sha256:9231582e8e504da562e3d2b4970b016b6d749707ff8b6d79f0302dde44f05b66 +size 1385541 diff --git a/data/bm25/postings/part-000011.parquet b/data/bm25/postings/part-000011.parquet index 0a2d677adc8194a97b94c4ffd48b5491f317396c..c3f04de66f4c21e9bd89664fcea68dece145272e 100644 --- a/data/bm25/postings/part-000011.parquet +++ b/data/bm25/postings/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f1bc4637c59dc4335713c250ceff2dae1e9df6ad25259faf75082c6f2590b3f3 -size 505567 +oid sha256:bab524995baace339043157026a561eec9f26d249d99d0937a92bb1e85ec2745 +size 1128986 diff --git a/data/bm25/postings/part-000012.parquet b/data/bm25/postings/part-000012.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a28307bf30aa7f3580facebb96da988ff0e8c2a3 --- /dev/null +++ b/data/bm25/postings/part-000012.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a24bd5c09a79430db564db7a0a3dbe3de81e7dda3216f98238210ceba3a6f782 +size 1488551 diff --git a/data/bm25/postings/part-000013.parquet b/data/bm25/postings/part-000013.parquet new file mode 100644 index 0000000000000000000000000000000000000000..814eb0df887b3962ba5fcd3cc99f901b082dcfd3 --- /dev/null +++ b/data/bm25/postings/part-000013.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa2993980b56722f0fe3dd8596b5021667aa2b05dda259d23602a5e34012e50f +size 125233 diff --git a/data/corpus/part-000000.parquet b/data/corpus/part-000000.parquet index 34726b35d5a503912f60c7e1a425700038504362..e7dbfa38d14fb9d6d184365e9f66ebbef6596427 100644 --- a/data/corpus/part-000000.parquet +++ b/data/corpus/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2e1f71399f659b434b70283214aac226070bb1c0e803dc8c9aaa4d3c7439905d -size 1207577 +oid sha256:7c06ca348db7210a723d39a6eee0fdafba30e0081199149c70e669c76a68423f +size 1325528 diff --git a/data/corpus/part-000001.parquet b/data/corpus/part-000001.parquet index 9533b1a864fd05178bfd1b0e710539413fc34ab6..decf1222df45f44886977b132bf69e6cf786dfab 100644 --- a/data/corpus/part-000001.parquet +++ b/data/corpus/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a340c25da2e9e690f6b4d20851e39bf9ca1242b816f76e6a60780b3b2fbaa23a -size 1735031 +oid sha256:e6e6b3306e308e99c13b6c6ef59b6b38b0083b31c96fd925081d742c5229d354 +size 2425952 diff --git a/data/corpus/part-000002.parquet b/data/corpus/part-000002.parquet index 702eeb8bd5ede408916395de3a12ffb340ee77a5..b4f5a64867fde89d59fe77ae5f7188a5815a8aba 100644 --- a/data/corpus/part-000002.parquet +++ b/data/corpus/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7a8ef541a94c479e25e95184d6771dbb9a8f9a9aeeffc9c60010b5fbf4d8764 -size 1486022 +oid sha256:8fc9202d6eb52192a91064cbad48685abb0a8cb448e53d2f6f850bfb26778d53 +size 1587901 diff --git a/data/corpus/part-000003.parquet b/data/corpus/part-000003.parquet index a5c31bc7f600e28cf0e5b62b31fd18bad4b2519e..bf3cabc231dfa486d37a59cf2946b016314de9d2 100644 --- a/data/corpus/part-000003.parquet +++ b/data/corpus/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f8f66b80da09da29c48bb1501a16d7dbe7ded88f5d8561e7b2e5874ecc37dce9 -size 1571730 +oid sha256:ec3539371d470c8a43e488d3d4663ef96f39161ffc1ed0c38aff63a860828455 +size 1645812 diff --git a/data/corpus/part-000004.parquet b/data/corpus/part-000004.parquet index cdba34b7e6e9df1b8ab9ea0930d1942c338dc2fa..227a8be91d7956b663146e30740584ead333304f 100644 --- a/data/corpus/part-000004.parquet +++ b/data/corpus/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5f675c7735c919c4aa0b3af2a5974718ca6612cb7e8201a7f819e92fb3261805 -size 1464078 +oid sha256:b1278a5d8a8302effce85b8bcd5dde9a30b351c8de06d07808a3a3b2f501676f +size 1579525 diff --git a/data/corpus/part-000005.parquet b/data/corpus/part-000005.parquet index 77c0675c3d1ab194bdcbaa3415c7f086c8b3dd3e..bb19d533c1e50f8eb258367c0f16c00f4a1eae8a 100644 --- a/data/corpus/part-000005.parquet +++ b/data/corpus/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b01d64f40745407172157048aec5bb1444cd646e139d18a7c0366c4ce4bb6bee -size 1309809 +oid sha256:5829faf4a6f51f1e46fd2a1a7c1cac300094d777a51ede5e3dd560bbe2620b90 +size 1430500 diff --git a/data/corpus/part-000006.parquet b/data/corpus/part-000006.parquet index 45615d85559886d3b93726ed501e641c1da633cd..85d0bfc7e22e77c8097f40d02bccde0c79833686 100644 --- a/data/corpus/part-000006.parquet +++ b/data/corpus/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:49f99316ffacaa4ef4a40757904caba26cc542e09567e62e65626283aa4bbf2f -size 1336583 +oid sha256:1735457ba1c3ffc4543467422cf751abfc26428bdf9bdc8776f4a8fe4d03b1bc +size 1391211 diff --git a/data/corpus/part-000007.parquet b/data/corpus/part-000007.parquet index 93996bab683b2eab652c47fdb0a8cce930fbe9f6..182979a35000f8e97f68296c939af062abf7f485 100644 --- a/data/corpus/part-000007.parquet +++ b/data/corpus/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:95c128dd38a8d1bfdde84a3662cc44c22f9ed371a1ea408434ac09c298cb369d -size 1175945 +oid sha256:f1697deb0aa39b4b18687935a4d81546c7524a19ad6e0cc15ac9db39e30702f5 +size 1575037 diff --git a/data/corpus/part-000008.parquet b/data/corpus/part-000008.parquet index cf860230eb52195495d884c1e90e47d2aa463684..b5f6a4560fa69125bf87929fb383a0bb09178b30 100644 --- a/data/corpus/part-000008.parquet +++ b/data/corpus/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a401239a2df0ffbd9663b7498d93b325bda228b9a82a79bbd8c2782674988a23 -size 1296256 +oid sha256:1b5a05ba475c8f86b6be100850f4880970575ee2f5a68507d11d2677a910a1d7 +size 1232907 diff --git a/data/corpus/part-000009.parquet b/data/corpus/part-000009.parquet index dc7c91befb97505cb15222fb33860d458bbe06ed..cd50550460e6a2aa27f8b6a14762710cbab95518 100644 --- a/data/corpus/part-000009.parquet +++ b/data/corpus/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b0e198e646e7b77b331f70d88c798dac84879fa6bd667a502edee01618443a6e -size 1343331 +oid sha256:53c8e1a03441d570c5298031006193bb7540fd7766e0afc75e51d218ec78ddb5 +size 1621269 diff --git a/data/corpus/part-000010.parquet b/data/corpus/part-000010.parquet index 5d779a30bd1d41cd138acf6a3ae9ba85fbd4ed0c..43c6faac5d6501807236c0fb8f3b77fe81ded87b 100644 --- a/data/corpus/part-000010.parquet +++ b/data/corpus/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ef5b31060f422439f7008ff5a83f66cbc95c6dcaff6b0e6093e4687021e160f2 -size 1488115 +oid sha256:a43d02e8168f80b754d0e56064e258985ddc85ee9a5a317c00b2e81fe7003b19 +size 1576364 diff --git a/data/corpus/part-000011.parquet b/data/corpus/part-000011.parquet index 4685e9911ced4cb7a57f8c7a38bd78c6d77b0a6f..f28d5c5e55ea0df954ebbc683c7f6946fce390d6 100644 --- a/data/corpus/part-000011.parquet +++ b/data/corpus/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f7fea52d5ff923f39e38b9c73c646fa8035e083200bd461457dc63fe31550b4d -size 1303028 +oid sha256:a254cf4378cdee1e505f1a428dc17e91cc31b9b221a1bb286e153760e6666a02 +size 1344364 diff --git a/data/corpus/part-000012.parquet b/data/corpus/part-000012.parquet index 069b1c8584ea096aab35615075b43f2cbf964a51..9f73e4f8df12ae85f7a7ae49501a8db351b2139e 100644 --- a/data/corpus/part-000012.parquet +++ b/data/corpus/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3a0ff4f1c2be30facc0baa255f6eab7d39c1afe5d4ef142193462eb86c26cf86 -size 1622434 +oid sha256:e91771082024af33d735c12db8e7a192b1e8fcc556e2cfea067569bf286bb464 +size 1689408 diff --git a/data/corpus/part-000013.parquet b/data/corpus/part-000013.parquet index 13f918ecae008c663cad8a01362f9402570a2fa7..74ffca6938a807bae2c960c431fa06b5452debed 100644 --- a/data/corpus/part-000013.parquet +++ b/data/corpus/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:cee5e7f6965e6406126a300055475769dafd8825a11b2d446bf474c48699e27b -size 1538474 +oid sha256:8ee503afe4215224e6ccecbda67345a3e16476288106beccd76bb72b03ae2c09 +size 1726759 diff --git a/data/corpus/part-000014.parquet b/data/corpus/part-000014.parquet index 4924c2c2328d4d86990a1e09f0436c29a9499429..7a958c508aca9a2f7d187f8b61825ba1036f927a 100644 --- a/data/corpus/part-000014.parquet +++ b/data/corpus/part-000014.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:af604d643af81b6d171fc7abea555873c178f25b312de4935067f96691e7120c -size 1590184 +oid sha256:61aff6a0d65ec9831cba3dcfda3e7b0d04903182e10bf7972e74f41011a56480 +size 1703929 diff --git a/data/corpus/part-000015.parquet b/data/corpus/part-000015.parquet index c0dad4a546505422658064fe744d6e0076e4bbce..a879d6b47753a862fdbf2fac5010500e3e4cd7ef 100644 --- a/data/corpus/part-000015.parquet +++ b/data/corpus/part-000015.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a52f178ce0c40e5ecdd0838b3647205ced8e3b67c44e8c8bc49fb5bd17cb60d5 -size 1651190 +oid sha256:860f01f66e449efff622e46d8eefdd025282e97f4a532be6a76948836e2c7764 +size 2001174 diff --git a/data/corpus/part-000016.parquet b/data/corpus/part-000016.parquet index 226249989e2be354aeb8c6df71a8369aca1034ab..0941838fbfbe21e5ea2d65485be0a14ebfd8eedb 100644 --- a/data/corpus/part-000016.parquet +++ b/data/corpus/part-000016.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:beeb814ad01b7eae0c198937dae38b00a7a1583203c0809f8597fa863fefbd46 -size 1447384 +oid sha256:a499bcd1858ef76f2f9080fd22b670528ba3484f08ee611f666d3f681e3a6e38 +size 1523990 diff --git a/data/corpus/part-000017.parquet b/data/corpus/part-000017.parquet index 99abae89b51873bf079fc2fb78c938800c4ab8a1..78b4fab3ae4275c12050ab14e0ef7a961f3cc7f5 100644 --- a/data/corpus/part-000017.parquet +++ b/data/corpus/part-000017.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fb35602b4fe8d0d0776d5f79e69fabcc92f9f33afdc0a9c0e5c0b05dc06bbfc2 -size 1303865 +oid sha256:a796d70159a4ad14b641970c7779e83a2a36a91a48f7b9900fe4aff4059e6cee +size 1525413 diff --git a/data/corpus/part-000018.parquet b/data/corpus/part-000018.parquet index 6031a08636148adfbc6d88ced061b7e7ef0aa81d..175d77be7456f5b2ca3727aec69499e183202065 100644 --- a/data/corpus/part-000018.parquet +++ b/data/corpus/part-000018.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:cb268574d743e8ec4feb77006c81d9454d3fc2a1857a96f1f48777c1febc0a31 -size 1339978 +oid sha256:ed3a575086cf4243047ca8ad68bdc198d7f4257e0d548934daffc523aa1c153d +size 1486759 diff --git a/data/corpus/part-000019.parquet b/data/corpus/part-000019.parquet index 196f15ffdf4d3c802a1714548a58a828928798f0..45cb6ffc2a1753d7e5c0a806cc3b8dbed581a6bc 100644 --- a/data/corpus/part-000019.parquet +++ b/data/corpus/part-000019.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f3e2301927c78e85f0fd05a3990db7d1e5502f1ebfba973b5fef573c71b0b336 -size 1273787 +oid sha256:549af64454c93c30ba3591df988c7bd22fdd1f54120f3518bd762e9856cb3c15 +size 1419906 diff --git a/data/corpus/part-000020.parquet b/data/corpus/part-000020.parquet index 6064d4863e113ac2bca120c9a0ce0a1868cd6c26..7680d477e21dcdc821e929bcd8baf0c427af2902 100644 --- a/data/corpus/part-000020.parquet +++ b/data/corpus/part-000020.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e398582bc1e2cc77d0fcb82054e0d7ee9bd7f94378fb5f483d1a3b23ba929fc5 -size 1362524 +oid sha256:cc1048f27df9539f47b5bf16316a7dd3837fadf2784f4a33cb1020d5c4cc2ec9 +size 1553440 diff --git a/data/corpus/part-000021.parquet b/data/corpus/part-000021.parquet new file mode 100644 index 0000000000000000000000000000000000000000..afc8e189c3840957cd41819c998efcc395780202 --- /dev/null +++ b/data/corpus/part-000021.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6acd2b35469883fc15e6c29edd3b136f0c5683ab1624c0887314583c72e4e713 +size 557744 diff --git a/data/graph/nodes/part-000000.parquet b/data/graph/nodes/part-000000.parquet index a526fbd0eb732501ec943971093872ffd5f1abb2..47c31f0d14f33058b18868d16c9501ba7f57c53f 100644 --- a/data/graph/nodes/part-000000.parquet +++ b/data/graph/nodes/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d2d2c47b0442489b8f97ba66e7f5419f3163593abef5249847e969d3ae9f97e3 -size 342223 +oid sha256:d5c42fa687557959070ae398aeb356899a1c98e6fb1feada6918a551750e803e +size 341035 diff --git a/data/graph/nodes/part-000001.parquet b/data/graph/nodes/part-000001.parquet index 742c7a4719f9dbae64f0467bcdd28ef64e66a3f0..47169a409474d89be42b213ea84247001deb3f7e 100644 --- a/data/graph/nodes/part-000001.parquet +++ b/data/graph/nodes/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1c22173abafb348bdcedb2d7556a1024c90f531ffa746f234050ca8d9aa80757 -size 343438 +oid sha256:d5372317ccac4d9a898802b372d1d52a881c68f77570c31efd324f860b498b7a +size 342075 diff --git a/data/graph/nodes/part-000003.parquet b/data/graph/nodes/part-000003.parquet index a1d9c7120a981e74806d8e74051d4e8230828765..77c3028a641cf9a105feb3fda4cb72f59a36c4ff 100644 --- a/data/graph/nodes/part-000003.parquet +++ b/data/graph/nodes/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:961a0bc0593ea11e8c7fa44182db42d12f8ace2a2d52394e152aada407f911f6 -size 343561 +oid sha256:a73e7b29bd740852db7652456669c5c40e7bf3b181095323f2966278a4b7714c +size 342618 diff --git a/data/graph/nodes/part-000004.parquet b/data/graph/nodes/part-000004.parquet index 3b86135f0709a249594fc77ab1440a08654ada41..61668cb6da48c7853f839f274455f0006b69c6ec 100644 --- a/data/graph/nodes/part-000004.parquet +++ b/data/graph/nodes/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:348b4e67ac76ebf862962ecab11f0c8bc61d2cef2c13fcace318fd3462785303 -size 343212 +oid sha256:381bad52b61048c71a457704c56a94ab3a2625e92bb18e84fd1ff2f28cc1d399 +size 341140 diff --git a/data/graph/nodes/part-000005.parquet b/data/graph/nodes/part-000005.parquet index a7aed8d3dae27117f832ca656d3069df4808e4bb..101e451a84998e267c7ff23e922e7f31080680ae 100644 --- a/data/graph/nodes/part-000005.parquet +++ b/data/graph/nodes/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8168779a53b8a3a9e72307cc1d24163360838f3b43d23cb453291dbd30f43ec9 -size 343547 +oid sha256:aac1a57890e5b0bf3bdf6d53c5916bd7fe93b269f0fa178cfe47b8f61f9ad8a6 +size 343925 diff --git a/data/graph/nodes/part-000007.parquet b/data/graph/nodes/part-000007.parquet index d5a75cd84743d577a926fdf77b94ee9db41b7c80..e6976eab087c8c58b42a41162e74757b5810285b 100644 --- a/data/graph/nodes/part-000007.parquet +++ b/data/graph/nodes/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0cf31db632f69930a19ff0f9eeedb4a65b1dadb7412555537f1ddbacd0656533 -size 343425 +oid sha256:06521debb386c0f9f9a10ac71c9ed30e625cebb97c5b1c5cf875fbd499e373b2 +size 340475 diff --git a/data/graph/nodes/part-000008.parquet b/data/graph/nodes/part-000008.parquet index cc14dd134e22e396088b8a7e8396102df9d1ebe9..b80829cdee0eabe4a4b1821cf2b2e5b96211e695 100644 --- a/data/graph/nodes/part-000008.parquet +++ b/data/graph/nodes/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f30f67e1abf7b8b78765912df5fc563e26fe329085c614ae26a3efb82e8410ce -size 342643 +oid sha256:8429359491e39a0a5cb00fcdec80b2827149844faa040057a8f1de3d55884036 +size 342611 diff --git a/data/graph/nodes/part-000009.parquet b/data/graph/nodes/part-000009.parquet index 9ad11c56f42b4a52b4270a77daa5d0391bdcf5e9..19114a0dcc377e8e5036b848223655141b525c7a 100644 --- a/data/graph/nodes/part-000009.parquet +++ b/data/graph/nodes/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a5084a1f42b265e13bc829eb9a97e4763f36edb8fc8c5224e3bacc31ef291f0f -size 343602 +oid sha256:77530b4a6517dce5e1bad56bf1060785e3339f9d7602fda15703b3897a0cfb69 +size 341900 diff --git a/data/graph/nodes/part-000010.parquet b/data/graph/nodes/part-000010.parquet index 281cec9da2b10bbffb488a31a3a9e81814a48220..bb51054b65aa510fe11a382ec6dec127e077d1c5 100644 --- a/data/graph/nodes/part-000010.parquet +++ b/data/graph/nodes/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4e8854637572c0de84bfd3921a6793d3d600655a1b4c760ddbad9533de3d1900 -size 342916 +oid sha256:ddd8f7d57aea37425861e769635a60db650971d65cf0b17799b9309a105ac4ab +size 342750 diff --git a/data/graph/nodes/part-000011.parquet b/data/graph/nodes/part-000011.parquet index f10966f424bbf115440e4184ac3a6331a1771315..4aebcea4d52355b0f7f4c1784f42917542657578 100644 --- a/data/graph/nodes/part-000011.parquet +++ b/data/graph/nodes/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a83b7cee72cd9a11616413cf71a02ca81a4d352ecc98a53bc2f398232d1a17c5 -size 343416 +oid sha256:2b9326503d5d152b8c71f562dc342acad90f35a0982a0e05aff9e91d929296e7 +size 342968 diff --git a/data/graph/nodes/part-000012.parquet b/data/graph/nodes/part-000012.parquet index dbc4016cedf856bbcd698fecca3569a69d8dc5b0..4f44d65bc788cdf6af55416f25575714cccd833a 100644 --- a/data/graph/nodes/part-000012.parquet +++ b/data/graph/nodes/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4edf51034c1077d4d8e0b3f25b088dd8f93063cdd3584f3841973a969afe5a51 -size 343624 +oid sha256:8a501f0fcd845ce6c29a9a35932029d678deb924eecf4d77c6024f9906f8d0f6 +size 343062 diff --git a/data/graph/nodes/part-000013.parquet b/data/graph/nodes/part-000013.parquet index ce0a166c5cb7f80621224cd65b874a9ed029a465..0554559face92db3fa054084bcc93254d5ced521 100644 --- a/data/graph/nodes/part-000013.parquet +++ b/data/graph/nodes/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:58772d4cf080371e3d595c8dd530eb79a47ca104cb84e6baf1475ba6031e63c3 -size 342476 +oid sha256:f5d59e36b7652f8fd69722c35d41e8724ff4713131937a20fed85f2d0cd6d50d +size 343043 diff --git a/data/graph/nodes/part-000014.parquet b/data/graph/nodes/part-000014.parquet index 136c19847508b25494f218631966f56a1811f86a..90462ddac6bf916e7032830b09b3e1aff2a69c0c 100644 --- a/data/graph/nodes/part-000014.parquet +++ b/data/graph/nodes/part-000014.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:84f784b1b700d14530d043bdb463b30684f660def56d525ad700adcc385774a5 -size 344232 +oid sha256:ec677d6c9f1c866667d122c2dac484f489ff49cf2b581adea7ba883d33c332e8 +size 340751 diff --git a/data/graph/nodes/part-000015.parquet b/data/graph/nodes/part-000015.parquet index 625d21e45df4755ef63ebeda44081467476053a5..da55ea71f24a6619e21882ce383a51b147a26807 100644 --- a/data/graph/nodes/part-000015.parquet +++ b/data/graph/nodes/part-000015.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d8045566426758d0d4135ee81b451df8fa390a5d366d88f6be46cc2b8ac34369 -size 342447 +oid sha256:f0960abde405f96ff4438c6565616b2673c3d366104361cb7ea6f31c771d680f +size 341156 diff --git a/data/graph/nodes/part-000016.parquet b/data/graph/nodes/part-000016.parquet index d76f81c8da8384d362e1c578dfc211c724acccf2..784c4738b513322be8de112644a94447937f7bf9 100644 --- a/data/graph/nodes/part-000016.parquet +++ b/data/graph/nodes/part-000016.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:095e7ea653cf2e4e52493ae863c18592a62299681cae27700903af2054583235 -size 342444 +oid sha256:b22ccc1452bd7ddbaddfedb54343c18da64bd4798bf8c03ce146fdebf9356777 +size 342247 diff --git a/data/graph/nodes/part-000017.parquet b/data/graph/nodes/part-000017.parquet index 9659d2d4ef18cd5794e2aa0746ddc5cd75a4ab71..b17c2065a0b1bba330a9fb2d68f54136f77f7a49 100644 --- a/data/graph/nodes/part-000017.parquet +++ b/data/graph/nodes/part-000017.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f1eb98f2044eac46f64441b54bbbae6d7731d7ff8afa079f5349d589cdfe79b5 -size 343580 +oid sha256:87871c97cb56ef056fac0c1d5f78ae6f37a149d3435882a215852c896ce3f936 +size 341242 diff --git a/data/graph/nodes/part-000018.parquet b/data/graph/nodes/part-000018.parquet index d79e038f270ee7d79461d9fdc8faf9bd9fbb63ba..e153972e87894f5cfb0ea104b57a3bb2c0af5420 100644 --- a/data/graph/nodes/part-000018.parquet +++ b/data/graph/nodes/part-000018.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8d2e7ffdb51593aa9da9bb4837a9228eb67185132cfb503142d7ec6f7739a66f -size 343782 +oid sha256:907acb6b3550e751ea14710851786f608edd5856b14d2ccb633b0d980303736a +size 340896 diff --git a/data/graph/nodes/part-000019.parquet b/data/graph/nodes/part-000019.parquet index ccea299da5c9b11b1183f3033d544264aac56281..e66d72cbc5dafc0fcf35f93b33ce7fb983a1a757 100644 --- a/data/graph/nodes/part-000019.parquet +++ b/data/graph/nodes/part-000019.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:52a641e58a7e14c9fa647a16de5f82732f0a178b86dcffc5ca4c993997cf42f2 -size 342998 +oid sha256:bbfe155c6a4dd6941f64eddbe51c408a3ed2fbed4d167799cc96e778f6bad4f3 +size 343023 diff --git a/data/graph/nodes/part-000020.parquet b/data/graph/nodes/part-000020.parquet index 8d8ea6b27874e580843cbb753d8b0bd94551f7e0..c1310413bed9c28d12891e9ed2d0a37cc87e59a3 100644 --- a/data/graph/nodes/part-000020.parquet +++ b/data/graph/nodes/part-000020.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:23758c6866504ab021fe4756431af077dbff9353e08b7caa1d3de2788423e16d -size 343555 +oid sha256:2edc3ae6113c32390660d2d38d6a5c46ba9e28d002573a839c95b9eab041e8b9 +size 341595 diff --git a/data/graph/nodes/part-000021.parquet b/data/graph/nodes/part-000021.parquet index 64a8143e8c01e6ad1618529fab595b3db7d9c9ce..528dfcf148ada0d35f931adb194512be526e5ef8 100644 --- a/data/graph/nodes/part-000021.parquet +++ b/data/graph/nodes/part-000021.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f3602f8be41db67d40f6774db9d913c60426c23c40aab7f559ef0e280e4ad9dd -size 298296 +oid sha256:43527fe277ceb9066d50e617dd995cc42fbb20b8ae66a085dd48ad9dfb9278cf +size 341192 diff --git a/data/graph/nodes/part-000022.parquet b/data/graph/nodes/part-000022.parquet new file mode 100644 index 0000000000000000000000000000000000000000..c7ae9def962e7e70045dd4464303cc1f9ac83be2 --- /dev/null +++ b/data/graph/nodes/part-000022.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:173c38dfec25bb6479d5b2bfb4959f5585d6592cde7391c9c4e9e175389e6b64 +size 187002 diff --git a/data/vectors/part-000000.parquet b/data/vectors/part-000000.parquet index 32b6d554cc962d1dcc3248bdf091c354a4f91086..c3f6818819fb4724618d0a5ae3f8e6e0be5a03dc 100644 --- a/data/vectors/part-000000.parquet +++ b/data/vectors/part-000000.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:510335001a9ffdac1e4a1092399ee239165ce829573ab8aebeca0c385c0c48d4 -size 6655080 +oid sha256:789741bfcbb31dab5bfaf5685009128e0f22bca82b6be331dae78ab2a8a442ca +size 7289308 diff --git a/data/vectors/part-000001.parquet b/data/vectors/part-000001.parquet index c9feee53484881f4b1ebcc36e72ec3bf9cc7c60b..07dcc1df68129d7fe0cd99fc6a3b89f75f0cfc83 100644 --- a/data/vectors/part-000001.parquet +++ b/data/vectors/part-000001.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0df59cac38b5f3123b19d86d4e34aad814e9b8045c6709578fca3f544598f79e -size 7344726 +oid sha256:02670118fa9d99621514638c153b40153a0e457e63fc736ad2be8bbf11705ea7 +size 7418770 diff --git a/data/vectors/part-000002.parquet b/data/vectors/part-000002.parquet index 887c095cb9a2e15540270fcd8a3c8b6e30fd784a..24217a0b5def461961145771c9d8bf8477216020 100644 --- a/data/vectors/part-000002.parquet +++ b/data/vectors/part-000002.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:edef26bc7804995ca3adc2870caf5080bcfb4e74316d3cfcb89be5814dcc40ae -size 7443541 +oid sha256:a60007c6c30ed4ac2af623e8e740c772e4bb4326cc2a921bade9692ff82585f7 +size 7498540 diff --git a/data/vectors/part-000003.parquet b/data/vectors/part-000003.parquet index f1ca971e1a1d7df85040b3333f998d757dd1c7c3..07c700fd5c8bede5c7703ab796b0b41d2a5eced3 100644 --- a/data/vectors/part-000003.parquet +++ b/data/vectors/part-000003.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:246fcc6c99e885ec877eb4bd92646463b40f13767d3aa5f5286dfa50aaf3e074 -size 7488121 +oid sha256:8de383be4b51015fffca16938e84f0eb1f99ff2d60c4df30e360d90924aafeae +size 7371489 diff --git a/data/vectors/part-000004.parquet b/data/vectors/part-000004.parquet index ded928802c5ed5a4327ba58da2f5014837d800bd..444debb22500a195309cb81162d02cc1d82510b2 100644 --- a/data/vectors/part-000004.parquet +++ b/data/vectors/part-000004.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:305429380eefc63483ce1d14cd2dab52b5c84a6c419c932577efa0541c99a9d0 -size 7520849 +oid sha256:9cd40129f19ef5ff828cd36c31160138d0cea2b255718dc61883f9fca4dfbfdc +size 7417435 diff --git a/data/vectors/part-000005.parquet b/data/vectors/part-000005.parquet index 9999b346220b9bd4da4003b85badc89023d056e1..19150c3ca92bdabda45e2fa19a9f69598a03757f 100644 --- a/data/vectors/part-000005.parquet +++ b/data/vectors/part-000005.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:31469fff56753e16d91b6bde32ef147d31dd518fb01eac62c662b94a05170423 -size 7511827 +oid sha256:fcc90297f24bca09a27b40d7b9cc06b132f18160b7bb0f75dadb86d0c67f505d +size 7500738 diff --git a/data/vectors/part-000006.parquet b/data/vectors/part-000006.parquet index 1b38d8bc36f61fb3d72c557dfc83227cb1ba4316..e254239b678b976d12715bacdc05bd559050d2a9 100644 --- a/data/vectors/part-000006.parquet +++ b/data/vectors/part-000006.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ff6919d777231a6f4826e4ce0a3ead7cb327cc3083e906d5a272c2027e3dffac -size 7478505 +oid sha256:1862903bea9349e7627bef7cfd95d4771da20f1a51787a307c5f6d7df899bbbf +size 7510504 diff --git a/data/vectors/part-000007.parquet b/data/vectors/part-000007.parquet index 0b0226dfce08597f3341185a0c8dfb5c4f63b425..b05fe60237b972df800c23bea7e1caba42eb232a 100644 --- a/data/vectors/part-000007.parquet +++ b/data/vectors/part-000007.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9430f1fb7af80acd8e6af5d05dcde305c1bdac10d64f096242e237e7e9f7cfff -size 7430260 +oid sha256:72e6531ace0d325bfc8176701b2d3730cf6112f190d16eef8a12578b986346e6 +size 7482136 diff --git a/data/vectors/part-000008.parquet b/data/vectors/part-000008.parquet index c13cfff2b1d0c45a357eb2945ac2c078324e4d2d..4c8db7d6858d5b338aeffce130b5ff59c740acb4 100644 --- a/data/vectors/part-000008.parquet +++ b/data/vectors/part-000008.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:456d7c49f3e0692b58c4dc67b200efebae6636b3853fce07a663657b602d4714 -size 7175927 +oid sha256:bf57af470ea0252e2133139814c350820f0adfe7879716d889967dcf2e8036a5 +size 7507698 diff --git a/data/vectors/part-000009.parquet b/data/vectors/part-000009.parquet index a01168470a8629f3f3b1e0844c3e5741eb20e487..2fa2ce291826da4b3e935cd83464481995ef1ecf 100644 --- a/data/vectors/part-000009.parquet +++ b/data/vectors/part-000009.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7d6dc6fe1345ec84203121f24fd3f3c690a00a44e0e8c2611e424fbdd802393f -size 7466398 +oid sha256:06e02828d8c022f56a5c1c77c73a491cb1f3a8402bb9e70b907275982d336a58 +size 6721672 diff --git a/data/vectors/part-000010.parquet b/data/vectors/part-000010.parquet index e3551e8e2b76836f8233745c2669aaa148f5712b..6530334dcd705ba236af8d7373fd4a44e1e8d499 100644 --- a/data/vectors/part-000010.parquet +++ b/data/vectors/part-000010.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:73ea3b54ce15e660f5ec243bad2032bd4213a64527be3f31709098e9c93085fd -size 7359440 +oid sha256:ffd2dad6d71172f3d26465727060777423a9bf64b4912823e8fc91fa02dc8e9a +size 6763618 diff --git a/data/vectors/part-000011.parquet b/data/vectors/part-000011.parquet index 16392b2345c278d7b95e779911e3d092d736cd1a..4e9c365913167985c70ff83dda0bc2230767c87d 100644 --- a/data/vectors/part-000011.parquet +++ b/data/vectors/part-000011.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ead5f8cb8889f3a857bc2b587cd793a4f3b61de5c985247553f40c303ed49eae -size 7452937 +oid sha256:f33f917b621118ded09cf13c50f0ebadb619787043828304b5a72d61d0696f9f +size 6943580 diff --git a/data/vectors/part-000012.parquet b/data/vectors/part-000012.parquet index 0739e288dca0c8148357a7ac8e6c4f6d400c9286..de9658f77dc375eac26efc32749a4176f58f4906 100644 --- a/data/vectors/part-000012.parquet +++ b/data/vectors/part-000012.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b3c6ca0ce5dc21063a898f6f9a3dadd472330f907e9e2ff5baa29c453eb4c2ee -size 7520655 +oid sha256:97ae2ba274dc2603106d75db6a917648c4e637c2fedf2728d105ec15486cb9c1 +size 7448889 diff --git a/data/vectors/part-000013.parquet b/data/vectors/part-000013.parquet index 441ce96ad3a28be3c1ec3bffd317172da73d2952..c2fdfb5bf84c77511230caa337a0efcd351aef85 100644 --- a/data/vectors/part-000013.parquet +++ b/data/vectors/part-000013.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a5d9f9007d4144c9dd228931f2da638c7ba0ee666de135eadc1ee0895d06d112 -size 7485571 +oid sha256:46815103427d8e9112af6d2c192c25a6e3ba539cc9b8aa7f68edd6072981c61e +size 7276237 diff --git a/data/vectors/part-000014.parquet b/data/vectors/part-000014.parquet index c9323a6fbddf32b1456eea79b9f9ba7c668bfbfc..a087310b4ca3ece36e66ee9f21f1fa6b34f46c49 100644 --- a/data/vectors/part-000014.parquet +++ b/data/vectors/part-000014.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4901e85c09557644d02a55a82248b770d0180da2bb2817f002ce1721b7f4b900 -size 7506265 +oid sha256:d4c4aa6eb0892fc28f1c490855c7845b976de8805a4d610c1e6e5899c0a067af +size 7484161 diff --git a/data/vectors/part-000015.parquet b/data/vectors/part-000015.parquet index 9446355f50cc18368580a7232f03ab6140bfc4d6..8b42c7aa2f320e28819089c19f695b622c5f4c6d 100644 --- a/data/vectors/part-000015.parquet +++ b/data/vectors/part-000015.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:44b3f16f66988299bda065b8cc6c79ad9e41524a3141307c3e1a15af85bfe96b -size 7505097 +oid sha256:6282fa11b92e11cecf6700aab929a9ad4d6dfd2f87ba259d0ad73ba7bca7294f +size 7311862 diff --git a/data/vectors/part-000016.parquet b/data/vectors/part-000016.parquet index 54cf6e63784c495de9c8c8a7f149d618a6d285cf..deb0b8af1ef9cbf4fb3d032fd341645c4a4ff68e 100644 --- a/data/vectors/part-000016.parquet +++ b/data/vectors/part-000016.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ae010ac48acfaf54561676e1914ef59a9a02322246427aebaa7f6b8f1bfeaeed -size 7412097 +oid sha256:6253129238fcfe47d9508efe767e156dd0bef85cf9f8954b9505cede2c7b2a92 +size 7429311 diff --git a/data/vectors/part-000017.parquet b/data/vectors/part-000017.parquet index aacaff180a6f55d52772dfbabbf326a73d1edab4..eed173e8c6d9eeed6605d3640bfbd21ca5f0eb2f 100644 --- a/data/vectors/part-000017.parquet +++ b/data/vectors/part-000017.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1df9b926432eed748c2d8c0da7abbcec1e3d223e86ca1c6bab36386536a217a6 -size 7358729 +oid sha256:e454af189c2d7074e288712c87fed38ac5ec81af79338e41dcd63167dfc1e8df +size 7516376 diff --git a/data/vectors/part-000018.parquet b/data/vectors/part-000018.parquet index f831dfbd5071672e63e98280813e2f799bd63288..8d1be575b1f31b82b415c0c8e70f28e847e135a3 100644 --- a/data/vectors/part-000018.parquet +++ b/data/vectors/part-000018.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8d2a8b18ea5156ce2307eab459f6d95dab1707f03e9892c0a9af7eff0ac72c1d -size 6887911 +oid sha256:bc50f44846337e35dab8e655e5eceae4258d2d6bb641c9192f3b961aed4094c9 +size 7501082 diff --git a/data/vectors/part-000019.parquet b/data/vectors/part-000019.parquet index 26320d18b9445d3e5f9b1473f0b7a747a5eb368e..c70f0f1e1cbbb3b20b411219ef1d4656d7a0d969 100644 --- a/data/vectors/part-000019.parquet +++ b/data/vectors/part-000019.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d63d01e70f5b7bf4476b417dd0719a7098c22d2f468c93979c5064209d531c08 -size 7080641 +oid sha256:3f45cc11f22e1c79d2c0b09bebd643a47929453ec75b99fb7d84091529fc762f +size 7510609 diff --git a/data/vectors/part-000020.parquet b/data/vectors/part-000020.parquet index 5026a4f83ef37698568b852cd2cbfc275fbf243e..db87d0af2d28b4b75acb8a42027f388a8b776d02 100644 --- a/data/vectors/part-000020.parquet +++ b/data/vectors/part-000020.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d740bd385805f7f162b4953acf638c787ade48b82f62d6c295060a2d8fc53702 -size 6659050 +oid sha256:c6ce88dbbbf233075a2efa0e720dd0aefbfd4226e041a02a37f04663c183d0af +size 7520975 diff --git a/data/vectors/part-000021.parquet b/data/vectors/part-000021.parquet new file mode 100644 index 0000000000000000000000000000000000000000..0dcea4531badf6269a7ceb2a9ee746a5a87d2c20 --- /dev/null +++ b/data/vectors/part-000021.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45ee52040fad1340027cf1470264a404b326da871b11433087862ae4665b35a3 +size 2540421 diff --git a/indexes/bm25_document_chunks.parquet b/indexes/bm25_document_chunks.parquet index 66a84f6c78027cab448d75fa75fef25cb1efd925..4d049ba9f2a2bac3fb5002b336ead1478b62b298 100644 --- a/indexes/bm25_document_chunks.parquet +++ b/indexes/bm25_document_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2cffe9b238e3b53a0b194318a5493b88203a2de6c16b9f90c927391f6b3a6fd8 -size 7624 +oid sha256:9d8b44f4f80106ab0b07a89c4ecfbb939801618ac57f944e27bf34f8c246298c +size 7757 diff --git a/indexes/bm25_keyword_shards.parquet b/indexes/bm25_keyword_shards.parquet index 6740b1dd38f787059320b304b3e8056f03896ea7..3fdbca1c1c5abaca7a8019c87f61b6ccb2bd2aec 100644 --- a/indexes/bm25_keyword_shards.parquet +++ b/indexes/bm25_keyword_shards.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bfe651aba07c93bcb1434ef8e8d807f44e135dfc9c033b332b43ef201999360c -size 6199 +oid sha256:23eb41435f190d44cbdb3885144bc4d0e3098948af304856f3777975abb2c6ba +size 6388 diff --git a/indexes/corpus_chunks.parquet b/indexes/corpus_chunks.parquet index 52c85ab1909fec5cc919eb8fa95e6d3179699320..5572ceea9cdbb67424fa18ad290d90dd518542a0 100644 --- a/indexes/corpus_chunks.parquet +++ b/indexes/corpus_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:10406e8707588c0792a752a9f562f80943b4fb7bec603208a06601eedca55aa2 -size 11783 +oid sha256:e54adea0461abd8641eee5b61d165271dac6dbd56345b3664a291785da47688e +size 11908 diff --git a/indexes/graph_edge_chunks.parquet b/indexes/graph_edge_chunks.parquet index 4428d6261d631ef3fdda3aeb4f13a0a4355bae91..29d95052296d3efd74dded38958b37a3b7b30b4b 100644 --- a/indexes/graph_edge_chunks.parquet +++ b/indexes/graph_edge_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6bd0cca90f901291f40e68ca26529a54a51b6d15e2ecd49aca40608c0eca508d -size 31646 +oid sha256:004c58fe263f63497053135d0990abb5aea8ac638c521eb541405569f2442eb0 +size 32198 diff --git a/indexes/graph_in_adjacency.parquet b/indexes/graph_in_adjacency.parquet index 655aac528b5314ca6b16a1bfb945ea81148d0725..d85434867a8d7ca074d083dfbedb829d528c489e 100644 --- a/indexes/graph_in_adjacency.parquet +++ b/indexes/graph_in_adjacency.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bd0aea1ee13b0f2400bff9bb494469cc3d8882043be0e2df16a89d249926e076 -size 18209 +oid sha256:d0b773492b16ff0f93c38782248c8a005de255698976c4aef4fac811aee420a9 +size 18327 diff --git a/indexes/graph_node_chunks.parquet b/indexes/graph_node_chunks.parquet index ebc3abf6326943d4826a6a8809b8a9152b65204c..76edb2e5fc5e8d31aa8e44532b7c1b9799258e3e 100644 --- a/indexes/graph_node_chunks.parquet +++ b/indexes/graph_node_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bc57bde2108ea92a3a831c6ca02439376770899eee422c899a0c4fcd29029650 -size 8681 +oid sha256:249307f4fdf898178ec778685752d7b30d48df636d4e6daad4e30abdff7b8301 +size 8863 diff --git a/indexes/graph_out_adjacency.parquet b/indexes/graph_out_adjacency.parquet index 5be3521c0c890645af310271a2d55a2fcc22c03b..662268bd0fc55a1a61d36a84c64bef9c58710ad2 100644 --- a/indexes/graph_out_adjacency.parquet +++ b/indexes/graph_out_adjacency.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:dc8c92fbf2e293fbe43d1304b22544f2a2c298fab7ee83a6c34e8420874d702d -size 19845 +oid sha256:03c8c8a983612a70bcbfa07ea4c6c403e47bc514039e40502a5f40c348a8bb9d +size 20056 diff --git a/indexes/vector_chunks.parquet b/indexes/vector_chunks.parquet index bd020eb278eee6d665b0873197df1e9fe8c5a506..878c1db1b059d47a23656c8ad20bcba11b010610 100644 --- a/indexes/vector_chunks.parquet +++ b/indexes/vector_chunks.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fe5decbc2d778078ea2f98d77569d8eac94e4f102410c78cc57b3650cad9561b -size 112739 +oid sha256:8cb76df15df416a5df99117003973e8bd4b87759d6370eb33f610ec5fed8e78e +size 119343 diff --git a/manifest.json b/manifest.json index 8cae9c256a17799332e089ae4272ddafa51a0120..64c4235b067450576d742eedb0d9c4defbda14db 100644 --- a/manifest.json +++ b/manifest.json @@ -18,36 +18,36 @@ "b": 0.75, "title_weight": 5.0, "body_weight": 1.0, - "average_document_length": 118.51053590618137, + "average_document_length": 196.17368939602235, "tokenizer": "hf-graphrag-bm25-tokens/v1", "max_query_terms": 64, "posting_rows_per_record": 4096, "terms_per_shard": 4096 }, "counts": { - "bm25_document_chunks": 21, - "bm25_documents": 85612, - "bm25_keyword_shards": 12, - "bm25_posting_rows": 46601, - "bm25_postings": 3595440, - "bm25_terms": 46254, - "corpus_chunks": 21, - "corpus_rows": 85615, + "bm25_document_chunks": 22, + "bm25_documents": 87288, + "bm25_keyword_shards": 14, + "bm25_posting_rows": 53745, + "bm25_postings": 4330185, + "bm25_terms": 53350, + "corpus_chunks": 22, + "corpus_rows": 87291, "graph_edge_chunks": 0, - "graph_edges": 599305, + "graph_edges": 611037, "graph_incoming_adjacency_edges": 0, "graph_incoming_adjacency_rows": 0, "graph_incoming_adjacency_shards": 0, "graph_node_chunks": 0, - "graph_nodes": 89587, + "graph_nodes": 92331, "graph_outgoing_adjacency_edges": 0, "graph_outgoing_adjacency_rows": 0, "graph_outgoing_adjacency_shards": 0, - "vector_chunks": 21, - "vector_rows": 85615, - "n_laws": 0, - "n_articles": 85615, - "bm25_token_instances": 10145924 + "vector_chunks": 22, + "vector_rows": 87291, + "n_laws": 1678, + "n_articles": 85613, + "bm25_token_instances": 17123609 }, "parquet": { "compression": "zstd", @@ -86,7 +86,7 @@ "default_probe_centroids": 4, "centroid_count": 32, "shard_count": 32, - "n_vectors": 85615, + "n_vectors": 87291, "status": "embedded" }, "canonical_fields": [ @@ -127,14 +127,14 @@ "articles_sha256": "6905c6e49a0b0cdaaad5191fead3950e04aa11f4f8bd4deeadd29fd610c196e8", "n_laws_in": 1678, "n_articles_in": 86041, - "unit": "article", + "unit": "law+article", "article_law_coverage": 51.275923718712754, "sparse_article_fallback": false, "drops": { "empty_body": 0, "missing_instrument": 0, - "duplicate_cid": 426, - "duplicate_source_kept_first": 426 + "duplicate_cid": 428, + "duplicate_source_kept_first": 428 }, "drop_samples": { "empty_body": [], @@ -144,27 +144,27 @@ "hk-cap109-en-sch-3-129", "hk-cap109-zh-hant-sch-1-114", "hk-cap109-zh-hant-sch-3-129", + "hk-cap112-en-sch-2-902", "hk-cap112-en-sch-3-1201", "hk-cap112-en-sch-3-726", "hk-cap112-zh-hant-sch-1-1199", + "hk-cap112-zh-hant-sch-2-902", "hk-cap112-zh-hant-sch-3-1175", "hk-cap112-zh-hant-sch-3-1201", "hk-cap112-zh-hant-sch-3-726", "hk-cap156-en-sch-1-201", "hk-cap156-en-sch-1-204", - "hk-cap156-en-sch-10-170", - "hk-cap156-en-sch-11-171", - "hk-cap156-en-sch-12-172", - "hk-cap156-en-sch-13-173", - "hk-cap156-en-sch-14-174", - "hk-cap156-en-sch-15-175", - "hk-cap156-en-sch-16-176", - "hk-cap156-en-sch-17-177" + "hk-cap156-en-sch-2-202", + "hk-cap156-en-sch-2-205", + "hk-cap156-en-sch-4-164", + "hk-cap156-en-sch-5-165", + "hk-cap156-en-sch-6-166", + "hk-cap156-en-sch-7-167" ] }, "language_breakdown": { - "en": 42842, - "zh-Hant": 42773 + "en": 43680, + "zh-Hant": 43611 }, "quality_flags": { "articles_table_empty": false, @@ -180,7 +180,7 @@ "eli_present": false, "never_invented_legal_text": true, "empty_bodies_dropped": 0, - "duplicate_cids_dropped": 426 + "duplicate_cids_dropped": 428 }, "schema_surprises": [ "laws.article_count dtype=int32", @@ -188,21 +188,31 @@ "laws.eli non-null=0/1678", "laws.language values=['en', 'zh-Hant']" ], - "n_out": 85615, + "n_out": 87291, "never_invented_legal_text": true, - "n_before_dedupe": 86041, - "n_dropped_total": 426, + "n_reconstructed_parents": 0, + "n_reconstructed_truncated": 0, + "n_reconstructed_stubs": 0, + "n_empty_parents_with_articles_not_reconstructed": 0, + "n_thin_instruments_replaced": 0, + "n_statute_rows_kept_as_law": 0, + "n_before_dedupe": 87719, + "n_law_rows": 1678, + "n_child_rows": 85613, + "n_instruments": 1678, + "n_dropped_total": 428, "record_type_breakdown": { - "article": 85615 + "article": 85613, + "law": 1678 }, "jurisdiction_breakdown": { - "HK": 85615 + "HK": 87291 }, "snapshot_dates": [ "2026-09-03" ], "heading_language_counts": { - "en": 22 + "en": 179 }, "heading_language_majority": "en", "document_language_majority": "en", @@ -210,7 +220,7 @@ "schema_version": "country-laws-normalize-verify/v1", "slug": "", "admitted": true, - "n_checks": 7, + "n_checks": 10, "n_failed": 0, "failed_ids": [], "checks": [ @@ -220,8 +230,8 @@ "passed": true, "message": "normalized corpus has rows", "evidence": { - "n_out": 85615, - "n_dropped": 426 + "n_out": 87291, + "n_dropped": 428 } }, { @@ -250,7 +260,7 @@ "passed": true, "message": "HTML tags stripped from legal bodies", "evidence": { - "n_bodies": 85615, + "n_bodies": 87291, "n_with_tags": 0, "fraction": 0.0, "samples": [] @@ -262,20 +272,50 @@ "passed": true, "message": "most legal units have usable body length", "evidence": { - "n_short": 12392, - "n_bodies": 85615, - "fraction": 0.1447409916486597 + "n_short": 12484, + "n_bodies": 87291, + "fraction": 0.1430158893814941 + } + }, + { + "id": "parent_laws", + "severity": "warn", + "passed": true, + "message": "parent instruments present (1678 law rows from 1678 source laws)", + "evidence": { + "n_laws_in": 1678, + "n_law_rows": 1678 + } + }, + { + "id": "reconstruction_grounded", + "severity": "fail", + "passed": true, + "message": "reconstructed parents match child glue", + "evidence": { + "checked": 0, + "mismatches": 0, + "samples": [] + } + }, + { + "id": "empty_parents_with_articles", + "severity": "fail", + "passed": true, + "message": "eligible empty parents all have law rows", + "evidence": { + "n_empty_parents_with_articles_not_reconstructed": 0 } }, { "id": "legal_structure", "severity": "warn", "passed": true, - "message": "retrieval units are structured (article, coverage=1.00)", + "message": "retrieval units are structured (law+article, coverage=0.98)", "evidence": { - "unit": "article", - "structured_rows": 85615, - "coverage": 1.0 + "unit": "law+article", + "structured_rows": 85613, + "coverage": 0.9807769414945412 } }, { @@ -287,7 +327,7 @@ "document_language": "en", "heading_language": "en", "heading_counts": { - "en": 22 + "en": 179 } } } @@ -325,27 +365,27 @@ }, "indexes": { "bm25_document_chunks": { - "cid": "bafkreibm77u3eohdwu5awgkddcsuso4iea5c3zwbnopzbsjhhepwwotp3a", - "sha256": "2cffe9b238e3b53a0b194318a5493b88203a2de6c16b9f90c927391f6b3a6fd8", - "size_bytes": 7624, + "cid": "bafkreie5rncpj6aba2vqwb5itrhm7o4ttaawdcwfp6ke4j57gt4merrjrq", + "sha256": "9d8b44f4f80106ab0b07a89c4ecfbb939801618ac57f944e27bf34f8c246298c", + "size_bytes": 7757, "relative_path": "indexes/bm25_document_chunks.parquet" }, "bm25_keyword_shards": { - "cid": "bafkreif74zi2xid4so6lcq2o7dunqb7ujyjv37e4am5tgk2d54qbtgjwbq", - "sha256": "bfe651aba07c93bcb1434ef8e8d807f44e135dfc9c033b332b43ef201999360c", - "size_bytes": 6199, + "cid": "bafkreibd5naugxyzbvcmxwzyqukexrgq4meyssfpgbefn43xpf22xmwgxi", + "sha256": "23eb41435f190d44cbdb3885144bc4d0e3098948af304856f3777975abb2c6ba", + "size_bytes": 6388, "relative_path": "indexes/bm25_keyword_shards.parquet" }, "corpus_chunks": { - "cid": "bafkreiaqibxiob2yrqdzfj2svh2wf6ajio2pw67mmazaridgahxnzjk2ui", - "sha256": "10406e8707588c0792a752a9f562f80943b4fb7bec603208a06601eedca55aa2", - "size_bytes": 11783, + "cid": "bafkreihfjlpkarq2xwded3xfwyormutr3ldnxvldiwzwmsrjc6c5ur3iry", + "sha256": "e54adea0461abd8641eee5b61d165271dac6dbd56345b3664a291785da47688e", + "size_bytes": 11908, "relative_path": "indexes/corpus_chunks.parquet" }, "graph_edge_chunks": { - "cid": "bafkreidl2dgksd4qcki7idtizitffgsuuunw2fpc5tkjvssamcga5ssqru", - "sha256": "6bd0cca90f901291f40e68ca26529a54a51b6d15e2ecd49aca40608c0eca508d", - "size_bytes": 31646, + "cid": "bafkreiaajrmp4jr7mnexauytluezbk5vv2ukyy4mkiplkqkakvu7erbowa", + "sha256": "004c58fe263f63497053135d0990abb5aea8ac638c521eb541405569f2442eb0", + "size_bytes": 32198, "relative_path": "indexes/graph_edge_chunks.parquet" }, "graph_incoming_adjacency": { @@ -353,9 +393,9 @@ "present": false }, "graph_node_chunks": { - "cid": "bafkreif4k666eeeovevdvay4nsqciojxm5yithxoiiwitgqmj7gssauwka", - "sha256": "bc57bde2108ea92a3a831c6ca02439376770899eee422c899a0c4fcd29029650", - "size_bytes": 8681, + "cid": "bafkreibesmd7j7pytaly5r3ynblvfv5tbven6y3njzw2vvhdbk67664dae", + "sha256": "249307f4fdf898178ec778685752d7b30d48df636d4e6daad4e30abdff7b8301", + "size_bytes": 8863, "relative_path": "indexes/graph_node_chunks.parquet" }, "graph_outgoing_adjacency": { @@ -363,9 +403,9 @@ "present": false }, "vector_chunks": { - "cid": "bafkreih6lxwlyllxqb4oul4y252wtwhkzfhe6ebecddyzrl3gzimvwkwdm", - "sha256": "fe5decbc2d778078ea2f98d77569d8eac94e4f102410c78cc57b3650cad9561b", - "size_bytes": 112739, + "cid": "bafkreiemw5w7cxpuc2s57giroabzopul2s4howowg4hlgp3bb3c75whhry", + "sha256": "8cb76df15df416a5df99117003973e8bd4b87759d6370eb33f610ec5fed8e78e", + "size_bytes": 119343, "relative_path": "indexes/vector_chunks.parquet" } }, @@ -421,38 +461,38 @@ "incremental": { "kind": "full_rebuild", "mode": "auto", - "reason": "operator forced full rebuild", + "reason": "CID overlap is empty; delta equals a full rebuild", "source_revision": "e12d7058e26d35c3d1fff4cabe6a18a66e8ce3bc", "prior_revision": "e12d7058e26d35c3d1fff4cabe6a18a66e8ce3bc", "source_fingerprint": "e12d7058e26d35c3d1fff4cabe6a18a66e8ce3bc|a318e63b8e47c5c2600497ce2fc3688296b049cbfd9ab68acc2e2b00b6b3a772|6905c6e49a0b0cdaaad5191fead3950e04aa11f4f8bd4deeadd29fd610c196e8", - "prior_fingerprint": "e12d7058e26d35c3d1fff4cabe6a18a66e8ce3bc||", + "prior_fingerprint": "e12d7058e26d35c3d1fff4cabe6a18a66e8ce3bc|a318e63b8e47c5c2600497ce2fc3688296b049cbfd9ab68acc2e2b00b6b3a772|6905c6e49a0b0cdaaad5191fead3950e04aa11f4f8bd4deeadd29fd610c196e8", "delta": { - "n_added": 71514, - "n_removed": 71471, - "n_unchanged": 14101, - "prior_count": 85572, - "current_count": 85615, - "changed_ratio": 0.8352975529988904, - "equivalent_to_full": false, + "n_added": 87291, + "n_removed": 85615, + "n_unchanged": 0, + "prior_count": 85615, + "current_count": 87291, + "changed_ratio": 1.0, + "equivalent_to_full": true, "added_cids_sample": [ + "bafkreia227bwle7csusxdv47wvqfp4ukulbczyyghajxv44igc3dl37wze", + "bafkreia22bnsqgscyqdlzrzkykyzdivhuh7cipewl3pylaofokbznj5l4m", + "bafkreia22ekub2zkk2xfpv3w24n5o7ilkpvkjbgzpbgjpf7slzp6jxj3z4", + "bafkreia22kiawma3qdqy5mjteuc5bsfwtvahyrcc45bb2xsv65j7vh6plm", + "bafkreia22l55gzcgv5usatfmckktlkpdjp346slbliownn5zuuj3mqorhm", + "bafkreia22mx27w5oc2n6vujnztcqerqpnrmf6h43esjrdw3yiz4bqviav4", + "bafkreia22u3ynwizpfdzqjc2tgspucrrigmvpf6wxx3phdkenjcnttbgqm", + "bafkreia232h774yq7icuuc32rfro46r7cdp7jotvrraopaej4g4ytikzky" + ], + "removed_cids_sample": [ "bafkreia224uirwbtfjv4mapie3ag7v27ntrgnqhlcq4hadi7e2th3xamye", "bafkreia227miown5wpqxydaohzwcjqfzfbi6cqi343hctaylmw3bcw2hhq", + "bafkreia227og2jo54semlgpwyda4qufuhcb3gzmzt6im23wx6qnhqq4y2i", "bafkreia227tx7byszabxaxpyz2nukmqjsq6yxfyjm4shnqicrv426za7rm", "bafkreia22c4whfcqjvrwf5fbsdup4ylmyroldza2wnsxdkixkv2ow36sm4", "bafkreia22hcwnxp7rsj4lcrkweuwetsaz5uboqumyzehfh7uikzrfcg62i", "bafkreia22hehel7wwi6qoim27yklrrfr4rble2i2xgeasrz7deeuhhvgbi", - "bafkreia22kovzznmke62vrwbziy5l7pzkotxubbt5ckd3r63oflu2aruoi", - "bafkreia22s3o33vnjtlqepubq4dllbq4ud5gain3fgdfd3kbxpoddfi43a" - ], - "removed_cids_sample": [ - "bafkreia223owj6vdy2ea6vsfrfbjuv2tbbm4bqnywj3iwhaxia4czp655e", - "bafkreia22aivsw6fkl6nlx6v7z2z7rwdrjkmyzwjvapfejtrxnt3zs53ca", - "bafkreia22auocbra4ynjedn7hdyd7jzku7gkp75fwgncrqcjkyi2a6ehda", - "bafkreia22ea64jdcgy5ccaus33ddy3ieaui6nntwgiadupgnvdtrl4uopu", - "bafkreia22iemhnffy76bs7xhuagbrcvuzi7ex4kki2hsi7nfzbxpjodow4", - "bafkreia22od22sl7ktwzpi4vck45wxl5sesj32xu3hsmp6wpkgyztfxelu", - "bafkreia22pjgp4k3lfyvu7tkqhmdbmajikse5ton7pookyg667as4a6k5a", - "bafkreia22pph2fydtnhp2u75qtchxnne5yudaotbpnopy5nqccrrhc2nzq" + "bafkreia22kovzznmke62vrwbziy5l7pzkotxubbt5ckd3r63oflu2aruoi" ] }, "reuse_embeddings": false, @@ -460,9 +500,9 @@ "equivalent_to_full": true, "schema_version": "country-laws-ir-graphrag/v1", "vectors": { - "n_docs": 85615, + "n_docs": 87291, "n_reused": 0, - "n_encoded": 85615, + "n_encoded": 87291, "n_missing": 0, "model_name": "thenlper/gte-small", "model_revision": "17e1f347d17fe144873b1201da91788898c639cd", @@ -477,7 +517,7 @@ "schema_version": "country-laws-ir-graphrag/v1", "bm25": { "bm25": { - "average_document_length": 118.51053590618137, + "average_document_length": 196.17368939602235, "b": 0.75, "body_weight": 1.0, "k1": 1.2, @@ -493,35 +533,35 @@ "bm25_keyword_index": "indexes/bm25_keyword_shards.parquet" }, "counts": { - "bm25_document_chunks": 21, - "bm25_documents": 85612, - "bm25_keyword_shards": 12, - "bm25_posting_rows": 46601, - "bm25_postings": 3595440, - "bm25_terms": 46254, - "bm25_token_instances": 10145924 + "bm25_document_chunks": 22, + "bm25_documents": 87288, + "bm25_keyword_shards": 14, + "bm25_posting_rows": 53745, + "bm25_postings": 4330185, + "bm25_terms": 53350, + "bm25_token_instances": 17123609 }, "indexes": { "bm25_document_chunks": { - "cid": "bafkreibm77u3eohdwu5awgkddcsuso4iea5c3zwbnopzbsjhhepwwotp3a", + "cid": "bafkreie5rncpj6aba2vqwb5itrhm7o4ttaawdcwfp6ke4j57gt4merrjrq", "relative_path": "indexes/bm25_document_chunks.parquet", - "row_count": 21, - "sha256": "2cffe9b238e3b53a0b194318a5493b88203a2de6c16b9f90c927391f6b3a6fd8", - "size_bytes": 7624 + "row_count": 22, + "sha256": "9d8b44f4f80106ab0b07a89c4ecfbb939801618ac57f944e27bf34f8c246298c", + "size_bytes": 7757 }, "bm25_keyword_shards": { - "cid": "bafkreif74zi2xid4so6lcq2o7dunqb7ujyjv37e4am5tgk2d54qbtgjwbq", + "cid": "bafkreibd5naugxyzbvcmxwzyqukexrgq4meyssfpgbefn43xpf22xmwgxi", "relative_path": "indexes/bm25_keyword_shards.parquet", - "row_count": 12, - "sha256": "bfe651aba07c93bcb1434ef8e8d807f44e135dfc9c033b332b43ef201999360c", - "size_bytes": 6199 + "row_count": 14, + "sha256": "23eb41435f190d44cbdb3885144bc4d0e3098948af304856f3777975abb2c6ba", + "size_bytes": 6388 } }, "schema_version": "hf-graphrag-bm25-layout/v1" }, "graph": { - "node_count": 89587, - "edge_count": 599305, + "node_count": 92331, + "edge_count": 611037, "adjacency": "data/graph/adjacency/{out,in}/*.parquet" }, "sqlite": false, diff --git a/normalization_report.json b/normalization_report.json index 2b9423d9f359b609fc3665ef19e12cbbb6269898..09461131aa552b1b60b6452509b25243dc10089c 100644 --- a/normalization_report.json +++ b/normalization_report.json @@ -5,14 +5,14 @@ "articles_sha256": "6905c6e49a0b0cdaaad5191fead3950e04aa11f4f8bd4deeadd29fd610c196e8", "n_laws_in": 1678, "n_articles_in": 86041, - "unit": "article", + "unit": "law+article", "article_law_coverage": 51.275923718712754, "sparse_article_fallback": false, "drops": { "empty_body": 0, "missing_instrument": 0, - "duplicate_cid": 426, - "duplicate_source_kept_first": 426 + "duplicate_cid": 428, + "duplicate_source_kept_first": 428 }, "drop_samples": { "empty_body": [], @@ -22,27 +22,27 @@ "hk-cap109-en-sch-3-129", "hk-cap109-zh-hant-sch-1-114", "hk-cap109-zh-hant-sch-3-129", + "hk-cap112-en-sch-2-902", "hk-cap112-en-sch-3-1201", "hk-cap112-en-sch-3-726", "hk-cap112-zh-hant-sch-1-1199", + "hk-cap112-zh-hant-sch-2-902", "hk-cap112-zh-hant-sch-3-1175", "hk-cap112-zh-hant-sch-3-1201", "hk-cap112-zh-hant-sch-3-726", "hk-cap156-en-sch-1-201", "hk-cap156-en-sch-1-204", - "hk-cap156-en-sch-10-170", - "hk-cap156-en-sch-11-171", - "hk-cap156-en-sch-12-172", - "hk-cap156-en-sch-13-173", - "hk-cap156-en-sch-14-174", - "hk-cap156-en-sch-15-175", - "hk-cap156-en-sch-16-176", - "hk-cap156-en-sch-17-177" + "hk-cap156-en-sch-2-202", + "hk-cap156-en-sch-2-205", + "hk-cap156-en-sch-4-164", + "hk-cap156-en-sch-5-165", + "hk-cap156-en-sch-6-166", + "hk-cap156-en-sch-7-167" ] }, "language_breakdown": { - "en": 42842, - "zh-Hant": 42773 + "en": 43680, + "zh-Hant": 43611 }, "quality_flags": { "articles_table_empty": false, @@ -58,7 +58,7 @@ "eli_present": false, "never_invented_legal_text": true, "empty_bodies_dropped": 0, - "duplicate_cids_dropped": 426 + "duplicate_cids_dropped": 428 }, "schema_surprises": [ "laws.article_count dtype=int32", @@ -66,21 +66,31 @@ "laws.eli non-null=0/1678", "laws.language values=['en', 'zh-Hant']" ], - "n_out": 85615, + "n_out": 87291, "never_invented_legal_text": true, - "n_before_dedupe": 86041, - "n_dropped_total": 426, + "n_reconstructed_parents": 0, + "n_reconstructed_truncated": 0, + "n_reconstructed_stubs": 0, + "n_empty_parents_with_articles_not_reconstructed": 0, + "n_thin_instruments_replaced": 0, + "n_statute_rows_kept_as_law": 0, + "n_before_dedupe": 87719, + "n_law_rows": 1678, + "n_child_rows": 85613, + "n_instruments": 1678, + "n_dropped_total": 428, "record_type_breakdown": { - "article": 85615 + "article": 85613, + "law": 1678 }, "jurisdiction_breakdown": { - "HK": 85615 + "HK": 87291 }, "snapshot_dates": [ "2026-09-03" ], "heading_language_counts": { - "en": 22 + "en": 179 }, "heading_language_majority": "en", "document_language_majority": "en", @@ -88,7 +98,7 @@ "schema_version": "country-laws-normalize-verify/v1", "slug": "", "admitted": true, - "n_checks": 7, + "n_checks": 10, "n_failed": 0, "failed_ids": [], "checks": [ @@ -98,8 +108,8 @@ "passed": true, "message": "normalized corpus has rows", "evidence": { - "n_out": 85615, - "n_dropped": 426 + "n_out": 87291, + "n_dropped": 428 } }, { @@ -128,7 +138,7 @@ "passed": true, "message": "HTML tags stripped from legal bodies", "evidence": { - "n_bodies": 85615, + "n_bodies": 87291, "n_with_tags": 0, "fraction": 0.0, "samples": [] @@ -140,20 +150,50 @@ "passed": true, "message": "most legal units have usable body length", "evidence": { - "n_short": 12392, - "n_bodies": 85615, - "fraction": 0.1447409916486597 + "n_short": 12484, + "n_bodies": 87291, + "fraction": 0.1430158893814941 + } + }, + { + "id": "parent_laws", + "severity": "warn", + "passed": true, + "message": "parent instruments present (1678 law rows from 1678 source laws)", + "evidence": { + "n_laws_in": 1678, + "n_law_rows": 1678 + } + }, + { + "id": "reconstruction_grounded", + "severity": "fail", + "passed": true, + "message": "reconstructed parents match child glue", + "evidence": { + "checked": 0, + "mismatches": 0, + "samples": [] + } + }, + { + "id": "empty_parents_with_articles", + "severity": "fail", + "passed": true, + "message": "eligible empty parents all have law rows", + "evidence": { + "n_empty_parents_with_articles_not_reconstructed": 0 } }, { "id": "legal_structure", "severity": "warn", "passed": true, - "message": "retrieval units are structured (article, coverage=1.00)", + "message": "retrieval units are structured (law+article, coverage=0.98)", "evidence": { - "unit": "article", - "structured_rows": 85615, - "coverage": 1.0 + "unit": "law+article", + "structured_rows": 85613, + "coverage": 0.9807769414945412 } }, { @@ -165,7 +205,7 @@ "document_language": "en", "heading_language": "en", "heading_counts": { - "en": 22 + "en": 179 } } } diff --git a/normalize.py b/normalize.py index b3c348f675dd13ca6f9184c6ffffce5cdfead2d8..1d77e3281ac66ffa99064e6afbcc5f1917da8a98 100644 --- a/normalize.py +++ b/normalize.py @@ -12,6 +12,7 @@ from __future__ import annotations import json import os +import re from collections import Counter from pathlib import Path from typing import Any @@ -24,7 +25,13 @@ from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION from .auth import configure_hf, public_token from .cidutil import cid_of_json, sha256_file, sha256_hex from .schema import SchemaError, validate_articles, validate_laws -from .structure import normalize_legal_text, split_structured_units +from .reconstruct import ( + article_sort_key, + parent_needs_reconstruct, + reconstruct_on, + reconstruct_parent, +) +from .structure import StructureUnit, normalize_legal_text, split_structured_units COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py" EMPTY_ARTICLE_COLUMNS = ( @@ -311,6 +318,249 @@ def _hierarchy_fields( } +def _compact_line(text: str) -> str: + return re.sub(r"\s+", " ", text or "").strip().casefold() + + +def _is_title_shell(body: str, title: str) -> bool: + """True when the article row is only its heading, repeated once.""" + folded_body = _compact_line(body) + folded_title = _compact_line(title) + if len(folded_title) < 24 or not folded_body: + return False + return folded_body == folded_title or folded_body == f"{folded_title} {folded_title}" + + +_NOTICE_RE = re.compile( + r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|" + r"\bnews item\b|\bnotice board\b)" +) + + +def _instrument_record_type(metadata: dict[str, Any], title: str) -> str: + """A normative instrument is a law, even when its title says Article. + + Newsletters, blogs, and press notices are not laws. A provision inside a + law stays an article; this label is only for the instrument itself. + """ + meta = metadata or {} + document_type = str(meta.get("document_type") or "").strip().casefold() + meta_type = str(meta.get("record_type") or "").strip().casefold() + if _NOTICE_RE.search(title or "") or document_type in { + "newsletter", + "blog", + "press", + "press_release", + "notice", + }: + return "notice" + if document_type in {"gazette", "gazette_pdf"} and meta_type not in { + "law", + "statute", + "constitution", + }: + return "notice" + return "law" + + +def _unit_record_type(unit: Any, instrument_type: str, *, n_units: int, parent_body: str) -> str: + """One unit that is the whole instrument keeps the instrument label.""" + if instrument_type == "notice": + return "notice" + if ( + n_units == 1 + and parent_body + and len(getattr(unit, "body", "") or "") >= int(0.8 * len(parent_body)) + ): + return "law" + kind = getattr(unit, "kind", "") or "" + if kind in {"article", "section"}: + return kind + return "article" + + +def _children_are_rich(kids: list[dict[str, Any]], parent_body: str) -> bool: + """True when the article rows already carry the statute, not just headings.""" + if not kids: + return False + total = sum(len((kid.get("body") or "").strip()) for kid in kids) + if total >= max(int(len(parent_body) * 0.5), 200): + return True + return any( + len((kid.get("body") or "").strip()) >= 80 + and not _is_title_shell(kid.get("body") or "", kid.get("title") or "") + for kid in kids + ) + + +def _article_copies_parent( + kid: dict[str, Any], parent_body: str, parent_title: str +) -> bool: + """True when this row is the statute, not a provision inside it. + + Collectors sometimes store the whole law again in the article table, with + the law's own title and no article number. A numbered provision whose body + is shorter than the statute stays a provision. + """ + body = (kid.get("body") or "").strip() + parent = (parent_body or "").strip() + if not body or not parent: + return False + if _compact_line(body) == _compact_line(parent): + return True + same_title = _compact_line(kid.get("title") or "") == _compact_line(parent_title) + no_number = not str(kid.get("article_number") or "").strip() + if not same_title or not no_number or len(parent) < 200: + return False + if len(body) < int(0.85 * len(parent)): + return False + return body[:200] in parent or parent[:200] in body + + +def _needs_parent_split( + kids: list[dict[str, Any]], parent_body: str, parent_title: str = "" +) -> bool: + """Split the parent when it holds the text and the article rows do not.""" + if len(parent_body) < 250 or len(parent_body) > 1_200_000: + return False + provisions = [ + kid + for kid in kids + if not _article_copies_parent(kid, parent_body, parent_title) + ] + return not _children_are_rich(provisions, parent_body) + + +_REAL_HEADING_RE = re.compile( + r"(?i)^(?:article|art\.?|artikel|articulo|artículo|section|sec\.?|§|" + r"مادة|المادة|clause|regulation|rule|schedule)\b" +) + + +def _is_provision_heading(unit: StructureUnit) -> bool: + """A numbered article or section stays its own row even when the text is short.""" + head = (unit.heading or unit.body or "").strip() + return _REAL_HEADING_RE.match(head) is not None + + +def _merge_units(parts: list[StructureUnit]) -> StructureUnit: + first = parts[0] + body = "\n\n".join(part.body.strip() for part in parts if part.body and part.body.strip()) + return StructureUnit( + kind=first.kind, + number=first.number, + heading=first.heading, + body=body, + title_number=first.title_number, + chapter_number=first.chapter_number, + part_number=first.part_number, + article_number=first.article_number, + section_number=first.section_number, + subsections=first.subsections, + hierarchy_path=first.hierarchy_path, + char_start=first.char_start, + char_end=parts[-1].char_end, + ) + + +def _thicken_units(units: list[StructureUnit]) -> list[StructureUnit]: + """Join one-line splits onto the previous provision. + + A provision of at least 80 characters stays its own row. Shorter pieces, + such as a lettered clause or a heading with no sentence, stay in the + previous provision. When every piece is that short, they are grouped into + passages of at least 240 characters. Fewer than two passages means the + statute stays a single law row. + """ + if len(units) < 2: + return [] + kept: list[StructureUnit] = [] + pending: list[StructureUnit] = [] + for unit in units: + if len((unit.body or "").strip()) >= 80 or _is_provision_heading(unit): + if pending: + kept.append(_merge_units([*pending, unit])) + pending = [] + else: + kept.append(unit) + elif kept: + kept[-1] = _merge_units([kept[-1], unit]) + else: + pending.append(unit) + if pending and kept: + kept[-1] = _merge_units([kept[-1], *pending]) + elif pending: + buf: list[StructureUnit] = [] + size = 0 + for unit in pending: + buf.append(unit) + size += len((unit.body or "").strip()) + if size >= 240: + kept.append(_merge_units(buf)) + buf = [] + size = 0 + if buf and kept: + kept[-1] = _merge_units([kept[-1], *buf]) + elif buf and size >= 240: + kept.append(_merge_units(buf)) + if len(kept) < 2: + return [] + return kept + + +def _copy_is_notice(kid: dict[str, Any]) -> bool: + meta = dict(kid.get("metadata") or {}) + if kid.get("record_type") and "record_type" not in meta: + meta["record_type"] = kid["record_type"] + return _instrument_record_type(meta, kid.get("title") or "") == "notice" + + +def _prefer_notice_from_copies(parent: dict[str, Any], kids: list[dict[str, Any]]) -> None: + """A statute row that is only a newsletter stays a notice.""" + doc = str((parent.get("metadata") or {}).get("document_type") or "").casefold() + if doc in {"law", "statute", "constitution"}: + return + for kid in kids: + if _article_copies_parent( + kid, parent.get("body") or "", parent.get("instrument_title") or "" + ) and _copy_is_notice(kid): + parent["metadata"] = { + **(parent.get("metadata") or {}), + "document_type": "newsletter", + } + return + + +def _expand_title_shell(parent: str, title: str, sibling_titles: set[str]) -> str | None: + """Copy the parent span from this heading to the next sibling heading. + + The span is taken only from lines already in the parent. A short heading + such as "Article 1" is left alone, because it matches too many lines. + """ + key = _compact_line(title) + peers = {item for item in sibling_titles if item and item != key and len(item) >= 24} + if len(key) < 24 or not peers or not parent: + return None + lines = [ln.strip() for ln in parent.splitlines() if ln.strip()] + compact = [_compact_line(ln) for ln in lines] + best = "" + for index, folded in enumerate(compact): + if folded != key: + continue + chunk = [lines[index]] + for later, later_folded in zip(lines[index + 1 :], compact[index + 1 :]): + if later_folded in peers: + break + chunk.append(later) + text = "\n".join(chunk).strip() + if len(text) > len(best): + best = text + # The heading alone is not enough. Require a following sentence from the parent. + if len(best) < len(key) + 40: + return None + return best + + def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): @@ -399,6 +649,34 @@ def _base_record( } if extra: rec.update(extra) + from .citations import assign_citation, citation_fields + + slug = "" + if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): + slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws") + year = "" + if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit(): + year = snapshot_date[:4] + extra = extra or {} + rec.update( + citation_fields( + assign_citation( + eli=str(rec.get("eli") or extra.get("eli") or ""), + official_identifier=str( + rec.get("official_identifier") or extra.get("official_identifier") or "" + ), + identifier=str(rec.get("identifier") or extra.get("identifier") or ""), + instrument_title=instrument_title, + article_number=article_number, + section_number=str(extra.get("section_number") or ""), + record_type=record_type, + jurisdiction=jurisdiction, + country=str(extra.get("country") or ""), + slug=slug, + year=year, + ) + ) + ) rec["entry_cid"] = _entry_cid(rec) rec["title_length"] = len(title_for_bm25) rec["body_length"] = len(body) @@ -455,16 +733,163 @@ def build_corpus( "schema_surprises": list(source_meta.get("schema_surprises") or []), "n_out": 0, "never_invented_legal_text": True, + "n_reconstructed_parents": 0, + "n_reconstructed_truncated": 0, + "n_reconstructed_stubs": 0, + "n_empty_parents_with_articles_not_reconstructed": 0, + "n_thin_instruments_replaced": 0, + "n_statute_rows_kept_as_law": 0, } entries: list[dict[str, Any]] = [] + slug = "" + if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): + slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws") + + children_by_law: dict[str, list[dict[str, Any]]] = {} + if not articles_empty: + for _, row in articles.iterrows(): + lid = _row_get(row, "law_id") + if not lid: + continue + children_by_law.setdefault(lid, []).append( + { + "id": _row_get(row, "id"), + "title": _row_get(row, "title"), + "article_number": _row_get(row, "article_number"), + "body": _row_get(row, "text"), + "record_type": _row_get(row, "record_type"), + "metadata": _parse_meta(_row_get(row, "metadata_json")), + "row": row, + } + ) + + reconstructed_ids: set[str] = set() + running_extra_bytes = 0 + + def _append_law_row( + instrument_id: str, + parent: dict[str, Any], + recon=None, + ) -> None: + body = parent["body"] + recon_extra: dict[str, Any] = {} + coverage = _coverage_from( + parent["row"], + parent["metadata"], + articles_empty=articles_empty, + sparse_fallback=sparse_fallback, + ) + if recon is not None and recon.reconstructed_from_articles: + body = recon.body + recon_extra = recon.extra_fields() + coverage = f"{coverage}; reconstructed_from_articles" + if not body: + kids = children_by_law.get(instrument_id) or [] + if kids: + report["n_empty_parents_with_articles_not_reconstructed"] += 1 + report["drops"]["empty_body"] += 1 + if len(report["drop_samples"]["empty_body"]) < 20: + report["drop_samples"]["empty_body"].append(instrument_id) + return + meta = parent["metadata"] + entries.append( + _base_record( + record_type=_instrument_record_type(meta, parent["instrument_title"]), + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number="", + article_title="", + body=body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage=coverage, + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=instrument_id, + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": "", + "article_id": "", + "reconstructed_from_articles": False, + **_hierarchy_fields( + parent["instrument_title"], body, "", language=parent["language"] + ), + **recon_extra, + }, + ) + ) if sparse_fallback: report["schema_surprises"].append( f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units" ) - if use_articles: + for instrument_id, parent in law_map.items(): + kids = children_by_law.get(instrument_id) or [] + recon = None + if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)): + recon = reconstruct_parent( + slug=slug, + parent_body=parent["body"], + parent_title=parent["instrument_title"], + children=[ + { + "id": k["id"], + "title": k["title"], + "article_number": k["article_number"], + "body": k["body"], + } + for k in kids + ], + running_extra_bytes=running_extra_bytes, + sha256_hex=sha256_hex, + ) + running_extra_bytes += recon.extra_bytes + reconstructed_ids.add(instrument_id) + report["n_reconstructed_parents"] += 1 + if recon.reconstruction_truncated: + report["n_reconstructed_truncated"] += 1 + if recon.is_stub: + report["n_reconstructed_stubs"] += 1 + _prefer_notice_from_copies(parent, kids) + _append_law_row(instrument_id, parent, recon) + + emit_articles = use_articles or bool(reconstructed_ids) + skip_body_split = emit_articles + sibling_titles = { + instrument_id: {_compact_line(kid["title"]) for kid in kids} + for instrument_id, kids in children_by_law.items() + } + promoted: dict[str, list[Any]] = {} + if emit_articles: + for instrument_id, parent in law_map.items(): + kids = children_by_law.get(instrument_id) or [] + if not _needs_parent_split(kids, parent["body"], parent["instrument_title"]): + continue + units = split_structured_units(parent["body"], language=parent["language"]) + covered = sum(len(unit.body) for unit in units) + thick = _thicken_units(units) + if len(thick) >= 2 and covered >= int(0.35 * len(parent["body"])): + promoted[instrument_id] = thick + if promoted: + report["n_thin_instruments_replaced"] = len(promoted) + report["schema_surprises"].append( + "parent headings used for " + f"{len(promoted)} instruments whose article rows were missing or thin" + ) + + if emit_articles: for _, row in articles.iterrows(): source_id = _row_get(row, "id") instrument_id = _row_get(row, "law_id") @@ -477,6 +902,27 @@ def build_corpus( report["drop_samples"]["empty_body"].append(source_id) continue parent = law_map.get(instrument_id) + if parent and _article_copies_parent( + { + "body": body, + "title": article_title, + "article_number": article_number, + }, + parent["body"], + parent["instrument_title"], + ): + report["n_statute_rows_kept_as_law"] += 1 + continue + if instrument_id in promoted: + continue + if parent and _is_title_shell(body, article_title): + expanded = _expand_title_shell( + parent["body"], + article_title, + sibling_titles.get(instrument_id) or set(), + ) + if expanded: + body = expanded if not parent: report["drops"]["missing_instrument"] += 1 if len(report["drop_samples"]["missing_instrument"]) < 20: @@ -487,9 +933,10 @@ def build_corpus( meta = parent["metadata"] art_meta = _parse_meta(_row_get(row, "metadata_json")) merged_meta = {**meta, **art_meta} + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) entries.append( _base_record( - record_type="article", + record_type="notice" if instrument_type == "notice" else "article", source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, @@ -521,22 +968,76 @@ def build_corpus( }, ) ) - else: + for instrument_id, units in promoted.items(): + parent = law_map[instrument_id] + meta = parent["metadata"] + report["unit"] = "structured" + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) + for unit in units: + entries.append( + _base_record( + record_type=_unit_record_type( + unit, + instrument_type, + n_units=len(units), + parent_body=parent["body"], + ), + source_dataset=source_dataset, + source_revision=source_revision, + instrument_id=instrument_id, + instrument_title=parent["instrument_title"], + law_cid=parent["law_cid"], + article_number=unit.article_number or unit.number, + article_title=unit.heading, + body=unit.body, + jurisdiction=parent["jurisdiction"], + language=parent["language"], + source_url=parent["source_url"], + snapshot_date=_snapshot_date(parent["row"], meta, source_meta), + coverage="structured (thin article rows replaced from the parent law)", + license_expr=parent["license"], + collector=_collector(meta, source_dataset), + source_id=f"{instrument_id}-{unit.kind}-{unit.number}", + extra={ + "eli": parent["eli"], + "identifier": parent["identifier"], + "official_identifier": parent["official_identifier"], + "source_type": parent["source_type"], + "country": parent["country"], + "law_status": parent["law_status"], + "parent_law_id": instrument_id, + "article_id": "", + "hierarchy_kind": unit.kind, + "hierarchy_path": unit.hierarchy_path, + "title_number": unit.title_number, + "chapter_number": unit.chapter_number, + "part_number": unit.part_number, + "section_number": unit.section_number, + "subsections": list(unit.subsections), + }, + ) + ) + elif not skip_body_split: for instrument_id, parent in law_map.items(): body = parent["body"] if not body: - report["drops"]["empty_body"] += 1 - if len(report["drop_samples"]["empty_body"]) < 20: - report["drop_samples"]["empty_body"].append(instrument_id) continue meta = parent["metadata"] - units = split_structured_units(body, language=parent["language"]) + units = _thicken_units( + split_structured_units(body, language=parent["language"]) + ) if units: report["unit"] = "structured" + instrument_type = _instrument_record_type(meta, parent["instrument_title"]) for unit in units: entries.append( _base_record( - record_type=unit.kind if unit.kind in {"article", "section"} else "article", + record_type=_unit_record_type( + unit, + instrument_type, + n_units=len(units), + parent_body=body, + ), source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, @@ -572,49 +1073,11 @@ def build_corpus( }, ) ) - continue - entries.append( - _base_record( - record_type="law", - source_dataset=source_dataset, - source_revision=source_revision, - instrument_id=instrument_id, - instrument_title=parent["instrument_title"], - law_cid=parent["law_cid"], - article_number="", - article_title="", - body=body, - jurisdiction=parent["jurisdiction"], - language=parent["language"], - source_url=parent["source_url"], - snapshot_date=_snapshot_date(parent["row"], meta, source_meta), - coverage=_coverage_from( - parent["row"], meta, articles_empty=True, sparse_fallback=sparse_fallback - ), - license_expr=parent["license"], - collector=_collector(meta, source_dataset), - source_id=instrument_id, - extra={ - "eli": parent["eli"], - "identifier": parent["identifier"], - "official_identifier": parent["official_identifier"], - "source_type": parent["source_type"], - "country": parent["country"], - "law_status": parent["law_status"], - "parent_law_id": "", - "article_id": "", - **_hierarchy_fields( - parent["instrument_title"], body, "", language=parent["language"] - ), - }, - ) - ) entries.sort( key=lambda r: ( r["instrument_id"], - r.get("article_number") or "", - r["source_id"], + article_sort_key(r.get("article_number") or "", r["source_id"]), ) ) n_before = len(entries) @@ -639,6 +1102,20 @@ def build_corpus( raise SchemaError("Duplicate entry_cid remained after dedupe") report["n_before_dedupe"] = n_before report["n_out"] = int(len(df)) + if not df.empty and "record_type" in df.columns: + n_law_rows = int((df["record_type"] == "law").sum()) + n_child_rows = int(df["record_type"].isin(["article", "section"]).sum()) + report["n_law_rows"] = n_law_rows + report["n_child_rows"] = n_child_rows + report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows + if n_law_rows and n_child_rows: + report["unit"] = ( + "law+structured" if report.get("unit") == "structured" else "law+article" + ) + elif n_law_rows: + report["unit"] = "law" + elif n_child_rows: + report["unit"] = "article" report["n_dropped_total"] = ( report["drops"]["empty_body"] + report["drops"]["missing_instrument"] diff --git a/query.py b/query.py index 9cd3a1da6f2ac29b2287609ec1bc797fd55c4774..d1f4db567a8944a31bc19a28c6fb6b78aed632f8 100644 --- a/query.py +++ b/query.py @@ -158,6 +158,11 @@ class Release: hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"])) return hits[:limit] + def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]: + from .duckdb_store import cite_search + + return cite_search(self.root, citation, cite_format=cite_format, limit=limit) + def _print(rows: list[dict]) -> None: print(json.dumps(rows, indent=2, ensure_ascii=False)) @@ -189,6 +194,16 @@ def main(argv: list[str] | None = None) -> int: ) p_n.add_argument("--limit", type=int, default=25) + p_cite = sub.add_parser("cite") + p_cite.add_argument("citation") + p_cite.add_argument( + "--format", + dest="cite_format", + default="any", + choices=["any", "bluebook", "official"], + ) + p_cite.add_argument("--limit", type=int, default=25) + args = ap.parse_args(argv) rel = Release(Path(args.local_dir)) if args.cmd == "bm25": @@ -197,6 +212,8 @@ def main(argv: list[str] | None = None) -> int: _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device)) elif args.cmd == "graph" and args.graph_cmd == "neighbors": _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit)) + elif args.cmd == "cite": + _print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit)) return 0 diff --git a/reports/normalization.json b/reports/normalization.json index 2b9423d9f359b609fc3665ef19e12cbbb6269898..09461131aa552b1b60b6452509b25243dc10089c 100644 --- a/reports/normalization.json +++ b/reports/normalization.json @@ -5,14 +5,14 @@ "articles_sha256": "6905c6e49a0b0cdaaad5191fead3950e04aa11f4f8bd4deeadd29fd610c196e8", "n_laws_in": 1678, "n_articles_in": 86041, - "unit": "article", + "unit": "law+article", "article_law_coverage": 51.275923718712754, "sparse_article_fallback": false, "drops": { "empty_body": 0, "missing_instrument": 0, - "duplicate_cid": 426, - "duplicate_source_kept_first": 426 + "duplicate_cid": 428, + "duplicate_source_kept_first": 428 }, "drop_samples": { "empty_body": [], @@ -22,27 +22,27 @@ "hk-cap109-en-sch-3-129", "hk-cap109-zh-hant-sch-1-114", "hk-cap109-zh-hant-sch-3-129", + "hk-cap112-en-sch-2-902", "hk-cap112-en-sch-3-1201", "hk-cap112-en-sch-3-726", "hk-cap112-zh-hant-sch-1-1199", + "hk-cap112-zh-hant-sch-2-902", "hk-cap112-zh-hant-sch-3-1175", "hk-cap112-zh-hant-sch-3-1201", "hk-cap112-zh-hant-sch-3-726", "hk-cap156-en-sch-1-201", "hk-cap156-en-sch-1-204", - "hk-cap156-en-sch-10-170", - "hk-cap156-en-sch-11-171", - "hk-cap156-en-sch-12-172", - "hk-cap156-en-sch-13-173", - "hk-cap156-en-sch-14-174", - "hk-cap156-en-sch-15-175", - "hk-cap156-en-sch-16-176", - "hk-cap156-en-sch-17-177" + "hk-cap156-en-sch-2-202", + "hk-cap156-en-sch-2-205", + "hk-cap156-en-sch-4-164", + "hk-cap156-en-sch-5-165", + "hk-cap156-en-sch-6-166", + "hk-cap156-en-sch-7-167" ] }, "language_breakdown": { - "en": 42842, - "zh-Hant": 42773 + "en": 43680, + "zh-Hant": 43611 }, "quality_flags": { "articles_table_empty": false, @@ -58,7 +58,7 @@ "eli_present": false, "never_invented_legal_text": true, "empty_bodies_dropped": 0, - "duplicate_cids_dropped": 426 + "duplicate_cids_dropped": 428 }, "schema_surprises": [ "laws.article_count dtype=int32", @@ -66,21 +66,31 @@ "laws.eli non-null=0/1678", "laws.language values=['en', 'zh-Hant']" ], - "n_out": 85615, + "n_out": 87291, "never_invented_legal_text": true, - "n_before_dedupe": 86041, - "n_dropped_total": 426, + "n_reconstructed_parents": 0, + "n_reconstructed_truncated": 0, + "n_reconstructed_stubs": 0, + "n_empty_parents_with_articles_not_reconstructed": 0, + "n_thin_instruments_replaced": 0, + "n_statute_rows_kept_as_law": 0, + "n_before_dedupe": 87719, + "n_law_rows": 1678, + "n_child_rows": 85613, + "n_instruments": 1678, + "n_dropped_total": 428, "record_type_breakdown": { - "article": 85615 + "article": 85613, + "law": 1678 }, "jurisdiction_breakdown": { - "HK": 85615 + "HK": 87291 }, "snapshot_dates": [ "2026-09-03" ], "heading_language_counts": { - "en": 22 + "en": 179 }, "heading_language_majority": "en", "document_language_majority": "en", @@ -88,7 +98,7 @@ "schema_version": "country-laws-normalize-verify/v1", "slug": "", "admitted": true, - "n_checks": 7, + "n_checks": 10, "n_failed": 0, "failed_ids": [], "checks": [ @@ -98,8 +108,8 @@ "passed": true, "message": "normalized corpus has rows", "evidence": { - "n_out": 85615, - "n_dropped": 426 + "n_out": 87291, + "n_dropped": 428 } }, { @@ -128,7 +138,7 @@ "passed": true, "message": "HTML tags stripped from legal bodies", "evidence": { - "n_bodies": 85615, + "n_bodies": 87291, "n_with_tags": 0, "fraction": 0.0, "samples": [] @@ -140,20 +150,50 @@ "passed": true, "message": "most legal units have usable body length", "evidence": { - "n_short": 12392, - "n_bodies": 85615, - "fraction": 0.1447409916486597 + "n_short": 12484, + "n_bodies": 87291, + "fraction": 0.1430158893814941 + } + }, + { + "id": "parent_laws", + "severity": "warn", + "passed": true, + "message": "parent instruments present (1678 law rows from 1678 source laws)", + "evidence": { + "n_laws_in": 1678, + "n_law_rows": 1678 + } + }, + { + "id": "reconstruction_grounded", + "severity": "fail", + "passed": true, + "message": "reconstructed parents match child glue", + "evidence": { + "checked": 0, + "mismatches": 0, + "samples": [] + } + }, + { + "id": "empty_parents_with_articles", + "severity": "fail", + "passed": true, + "message": "eligible empty parents all have law rows", + "evidence": { + "n_empty_parents_with_articles_not_reconstructed": 0 } }, { "id": "legal_structure", "severity": "warn", "passed": true, - "message": "retrieval units are structured (article, coverage=1.00)", + "message": "retrieval units are structured (law+article, coverage=0.98)", "evidence": { - "unit": "article", - "structured_rows": 85615, - "coverage": 1.0 + "unit": "law+article", + "structured_rows": 85613, + "coverage": 0.9807769414945412 } }, { @@ -165,7 +205,7 @@ "document_language": "en", "heading_language": "en", "heading_counts": { - "en": 22 + "en": 179 } } }