endomorphosis commited on
Commit
99100b1
·
verified ·
1 Parent(s): a8c2ac0

Add scrapers_and_normalizers overlay (general_legal_scrapers/subnational_general, data/* untouched) [3/3]

Browse files
Files changed (20) hide show
  1. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/__init__.py +15 -0
  2. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/code_type.py +76 -0
  3. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/date.py +89 -0
  4. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/format.py +67 -0
  5. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/geography.py +49 -0
  6. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/section.py +74 -0
  7. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/legal_corpus/docs/JURISDICTION_IMPLEMENTATION.md +100 -0
  8. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/common.py +159 -0
  9. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_indexes.py +663 -0
  10. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_package.py +447 -0
  11. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/normalized_package.py +483 -0
  12. scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/unified_package.py +824 -0
  13. scrapers_and_normalizers/scripts/scrapers/legal/README.md +144 -0
  14. scrapers_and_normalizers/scripts/scrapers/legal/courtlistener_docket_ingest.py +30 -0
  15. scrapers_and_normalizers/scripts/scrapers/legal/federal_register_scraper.py +7 -0
  16. scrapers_and_normalizers/scripts/scrapers/legal/municipal_laws_scraper.py +7 -0
  17. scrapers_and_normalizers/scripts/scrapers/legal/netherlands_laws_scraper.py +3 -0
  18. scrapers_and_normalizers/scripts/scrapers/legal/recap_archive_scraper.py +7 -0
  19. scrapers_and_normalizers/scripts/scrapers/legal/state_laws_scraper.py +7 -0
  20. scrapers_and_normalizers/scripts/scrapers/legal/us_code_scraper.py +7 -0
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checker sub-package: re-exports all check functions for convenient import."""
2
+
3
+ from .geography import check_geography
4
+ from .code_type import check_code_type
5
+ from .section import check_section
6
+ from .date import check_date
7
+ from .format import check_format
8
+
9
+ __all__ = [
10
+ "check_geography",
11
+ "check_code_type",
12
+ "check_section",
13
+ "check_date",
14
+ "check_format",
15
+ ]
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/code_type.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code-type checker: validates Municipal / County Code type against GNIS class_code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Optional
7
+
8
+ from ..constants import MUNICIPAL_CLASS_CODES, COUNTY_CLASS_CODES, CONSOLIDATED_CLASS_CODES
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Bug #22 fix: use class_code values (C1-C7, H1/H4-H6, C8), NOT feature_class strings.
13
+ # Frozensets are defined in constants.py for shared use across the package.
14
+ _MUNICIPAL_CLASS_CODES = MUNICIPAL_CLASS_CODES
15
+ _COUNTY_CLASS_CODES = COUNTY_CLASS_CODES
16
+ _CONSOLIDATED_CLASS_CODES = CONSOLIDATED_CLASS_CODES
17
+
18
+
19
+ def check_code_type(citation: dict, reference_db) -> Optional[str]:
20
+ """Validate that the citation's code type (Municipal/County/City Code) matches the GNIS class_code.
21
+
22
+ Per the Bluebook PRD:
23
+ - ``C1``–``C7`` → Municipal Code
24
+ - ``H1``, ``H4``–``H6`` → County Code
25
+ - ``C8`` → consolidated city (accepts either Municipal or County Code)
26
+
27
+ Args:
28
+ citation: Citation dict. Must contain ``gnis`` and ``code_type`` fields.
29
+ reference_db: An open database connection whose ``locations`` table has a
30
+ ``class_code`` column keyed by ``gnis``.
31
+
32
+ Returns:
33
+ ``None`` when the code type is valid; an error string otherwise.
34
+ """
35
+ gnis = citation.get("gnis")
36
+ cited_code_type = citation.get("code_type") or citation.get("bluebook_code_type")
37
+
38
+ if gnis is None or not cited_code_type:
39
+ return "Missing gnis or code_type in citation"
40
+
41
+ try:
42
+ result = reference_db.execute(
43
+ "SELECT class_code FROM locations WHERE gnis = ?", [int(gnis)]
44
+ ).fetchone()
45
+ except Exception as exc:
46
+ logger.error("Database error during code-type check for gnis %s: %s", gnis, exc)
47
+ return f"Database error checking code type for gnis {gnis}: {exc}"
48
+
49
+ if result is None:
50
+ return f"GNIS {gnis} not found in reference database"
51
+
52
+ class_code: str = str(result[0]).strip()
53
+ cited_code_type = cited_code_type.strip()
54
+
55
+ if class_code in _MUNICIPAL_CLASS_CODES:
56
+ expected = "Municipal Code"
57
+ elif class_code in _COUNTY_CLASS_CODES:
58
+ expected = "County Code"
59
+ elif class_code in _CONSOLIDATED_CLASS_CODES:
60
+ # Consolidated city-counties are valid as either type.
61
+ if cited_code_type in ("Municipal Code", "County Code", "City Code"):
62
+ return None
63
+ return (
64
+ f"Code type '{cited_code_type}' not valid for consolidated city "
65
+ f"(class_code={class_code}); expected 'Municipal Code' or 'County Code'"
66
+ )
67
+ else:
68
+ return f"Unknown class_code '{class_code}' for gnis {gnis}"
69
+
70
+ if cited_code_type != expected:
71
+ return (
72
+ f"Code type mismatch for gnis {gnis} (class_code={class_code}): "
73
+ f"citation says '{cited_code_type}', should be '{expected}'"
74
+ )
75
+
76
+ return None # valid
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/date.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Date checker: validates the citation year is reasonable and consistent.
2
+
3
+ Fixes:
4
+ - Bug #9: returns ``None`` (not the string ``'Date check passed'``) on success.
5
+ - Deferred feature #26: implements document date cross-reference check.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Optional
12
+
13
+ _YEAR_PATTERN = re.compile(r"\b(1[7-9]\d{2}|20[0-2]\d)\b")
14
+ _CITATION_YEAR_PATTERN = re.compile(r"\((\d{4})\)$")
15
+
16
+ _MIN_YEAR = 1776
17
+ _MAX_YEAR = 2025
18
+
19
+
20
+ def _extract_year_from_string(text: str) -> Optional[int]:
21
+ """Return the first plausible 4-digit year found in *text*, or ``None``."""
22
+ m = _YEAR_PATTERN.search(str(text))
23
+ return int(m.group(1)) if m else None
24
+
25
+
26
+ def check_date(citation: dict, documents: Optional[list[dict]] = None) -> Optional[str]:
27
+ """Validate the citation year.
28
+
29
+ Checks (in order):
30
+ 1. Range check: year must be in ``[1776, 2025]``.
31
+ 2. Metadata cross-reference: year extracted from ``bluebook_citation`` must
32
+ match the year from the ``date`` / ``year`` field (if both are present).
33
+ 3. Document cross-reference: the year must appear in at least one document
34
+ (if documents are provided). This implements the previously deferred
35
+ TODO in the original code.
36
+
37
+ Args:
38
+ citation: Citation dict. Year is read from ``bluebook_citation`` (trailing
39
+ ``(YYYY)`` pattern) and/or the ``date`` / ``year`` field.
40
+ documents: Optional list of document dicts with ``html_body`` or ``content``.
41
+
42
+ Returns:
43
+ ``None`` when all checks pass; an error string otherwise.
44
+ """
45
+ # --- Extract year from bluebook_citation string ---
46
+ citation_year: Optional[int] = None
47
+ bluebook = citation.get("bluebook_citation", "")
48
+ if bluebook:
49
+ m = _CITATION_YEAR_PATTERN.search(bluebook.strip())
50
+ if m:
51
+ citation_year = int(m.group(1))
52
+
53
+ # --- Extract year from metadata field ---
54
+ metadata_year: Optional[int] = None
55
+ raw_date = citation.get("date") or citation.get("year")
56
+ if raw_date is not None:
57
+ if isinstance(raw_date, int):
58
+ metadata_year = raw_date
59
+ else:
60
+ metadata_year = _extract_year_from_string(str(raw_date))
61
+
62
+ # Decide which year to use for range checking (prefer citation string).
63
+ year = citation_year if citation_year is not None else metadata_year
64
+
65
+ if year is None:
66
+ return "Could not extract a valid year from citation or metadata"
67
+
68
+ # 1. Range check.
69
+ if not (_MIN_YEAR <= year <= _MAX_YEAR):
70
+ return f"Year {year} is outside the valid range ({_MIN_YEAR}–{_MAX_YEAR})"
71
+
72
+ # 2. Metadata cross-reference.
73
+ if citation_year is not None and metadata_year is not None:
74
+ if citation_year != metadata_year:
75
+ return (
76
+ f"Year mismatch: bluebook_citation says {citation_year}, "
77
+ f"metadata date says {metadata_year}"
78
+ )
79
+
80
+ # 3. Document cross-reference (deferred feature now implemented).
81
+ if documents:
82
+ year_str = str(year)
83
+ found_in_doc = any(
84
+ year_str in (doc.get("html_body") or doc.get("content") or "") for doc in documents
85
+ )
86
+ if not found_in_doc:
87
+ return f"Year {year} not found in any source document"
88
+
89
+ return None # all checks passed
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/format.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Format checker: validates the ``bluebook_citation`` string against Bluebook Rule 12.9.
2
+
3
+ Deferred feature #27 fix: validates the full citation STRING, not individual
4
+ title/url/section fields.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Optional
11
+
12
+ from ..constants import BLUEBOOK_STATE_ABBREVS, MIN_CITATION_YEAR, MAX_CITATION_YEAR
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Bluebook Rule 12.9 pattern
16
+ # Format: "Place, State Abbrev., Code Type, §Section (Year)"
17
+ # Example: "Garland, Ark., County Code, §14-75 (2007)"
18
+ # ---------------------------------------------------------------------------
19
+ _BLUEBOOK_PATTERN = re.compile(
20
+ r"^(?P<place>[^,]+),\s+"
21
+ # State abbreviation: handles all Bluebook forms:
22
+ # single-word e.g. "Ala." "Alaska" "Ohio"
23
+ # all-caps e.g. "N.H." "D.C." "S.C."
24
+ # two-word e.g. "W. Va."
25
+ r"(?P<state>[A-Z][A-Za-z.]*\.?(?:\s[A-Z][a-z]+\.?)?),\s+"
26
+ r"(?P<code_type>(?:Municipal|County|City)\s+Code),\s+"
27
+ r"§(?P<section>[\d]+(?:[-.][\d]+)*)\s+"
28
+ r"\((?P<year>\d{4})\)$"
29
+ )
30
+
31
+
32
+ def check_format(citation: dict) -> Optional[str]:
33
+ """Validate the ``bluebook_citation`` string against Bluebook Rule 12.9 format.
34
+
35
+ Args:
36
+ citation: Citation dict containing a ``bluebook_citation`` field.
37
+
38
+ Returns:
39
+ ``None`` when the format is valid; a descriptive error string otherwise.
40
+ """
41
+ raw = citation.get("bluebook_citation")
42
+ if not raw:
43
+ return "Missing bluebook_citation field"
44
+
45
+ text = raw.strip()
46
+ m = _BLUEBOOK_PATTERN.match(text)
47
+ if not m:
48
+ return (
49
+ f"bluebook_citation does not match Bluebook Rule 12.9 format "
50
+ f"'Place, State, Code Type, §Section (Year)': {text!r}"
51
+ )
52
+
53
+ state_abbrev = m.group("state")
54
+ if state_abbrev not in BLUEBOOK_STATE_ABBREVS:
55
+ return (
56
+ f"Unrecognised Bluebook state abbreviation '{state_abbrev}' "
57
+ f"in bluebook_citation: {text!r}"
58
+ )
59
+
60
+ year = int(m.group("year"))
61
+ if not (MIN_CITATION_YEAR <= year <= MAX_CITATION_YEAR):
62
+ return (
63
+ f"Year {year} in bluebook_citation is outside the valid range "
64
+ f"({MIN_CITATION_YEAR}–{MAX_CITATION_YEAR}): {text!r}"
65
+ )
66
+
67
+ return None # valid
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/geography.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geography checker: validates that a citation's state matches the GNIS record."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Optional
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def check_geography(citation: dict, reference_db) -> Optional[str]:
12
+ """Validate that the place name and state in the citation match the GNIS reference data.
13
+
14
+ Args:
15
+ citation: Citation dict. Must contain ``gnis`` and
16
+ ``bluebook_state_code`` fields.
17
+ reference_db: An open database connection whose ``locations`` table
18
+ has a ``state_code`` column keyed by ``gnis``.
19
+
20
+ Returns:
21
+ ``None`` when the geography is valid; an error string otherwise.
22
+ """
23
+ gnis = citation.get("gnis")
24
+ # Bug #21 fix: use 'bluebook_state_code', NOT 'state'
25
+ cited_state = citation.get("bluebook_state_code")
26
+
27
+ if gnis is None or cited_state is None:
28
+ return "Missing gnis or bluebook_state_code in citation"
29
+
30
+ try:
31
+ # Parameterized query — never interpolate user data into SQL strings
32
+ result = reference_db.execute(
33
+ "SELECT state_code FROM locations WHERE gnis = ?", [int(gnis)]
34
+ ).fetchone()
35
+ except Exception as exc:
36
+ logger.error("Database error during geography check for gnis %s: %s", gnis, exc)
37
+ return f"Database error checking geography for gnis {gnis}: {exc}"
38
+
39
+ if result is None:
40
+ return f"GNIS {gnis} not found in reference database"
41
+
42
+ actual_state = result[0]
43
+ if str(cited_state).strip().lower() != str(actual_state).strip().lower():
44
+ return (
45
+ f"State mismatch for gnis {gnis}: "
46
+ f"citation says '{cited_state}', reference says '{actual_state}'"
47
+ )
48
+
49
+ return None # valid
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/bluebook_citation_validator/checkers/section.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section checker: validates that the cited section exists in source HTML documents.
2
+
3
+ Bug #23 fix: correct signature is ``(citation: dict, documents: list[dict])``,
4
+ **not** ``(citation_section: str, html_body: str)``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Optional
11
+
12
+
13
+ def _extract_section_number(citation: dict) -> Optional[str]:
14
+ """Extract a bare section number from the citation dict.
15
+
16
+ Tries (in order):
17
+ 1. ``citation['title_num']`` — explicit section field.
18
+ 2. The section captured from ``citation['bluebook_citation']`` via the
19
+ ``§<section>`` pattern.
20
+
21
+ Returns the number string (e.g. ``"14-75"``) or ``None``.
22
+ """
23
+ title_num = citation.get("title_num") or citation.get("section")
24
+ if title_num:
25
+ # Strip any leading §/S whitespace.
26
+ cleaned = re.sub(r"^[§S]\s*", "", str(title_num).strip())
27
+ if cleaned:
28
+ return cleaned
29
+
30
+ bluebook = citation.get("bluebook_citation", "")
31
+ # Pattern: §14-75 or § 14-75 in the citation string
32
+ m = re.search(r"§\s*([\d]+(?:[-.][\d]+)*)", bluebook)
33
+ if m:
34
+ return m.group(1)
35
+
36
+ return None
37
+
38
+
39
+ def check_section(citation: dict, documents: list[dict]) -> Optional[str]:
40
+ """Validate that the section referenced in the citation exists in the source HTML.
41
+
42
+ Args:
43
+ citation: Citation dict. Section is extracted from ``title_num`` or
44
+ ``bluebook_citation``.
45
+ documents: List of document dicts, each containing ``html_body`` or
46
+ ``content`` text.
47
+
48
+ Returns:
49
+ ``None`` when the section is found; an error string otherwise.
50
+ """
51
+ section_number = _extract_section_number(citation)
52
+ if not section_number:
53
+ return "Could not extract section number from citation"
54
+
55
+ if not documents:
56
+ return f"No documents provided; cannot verify section {section_number}"
57
+
58
+ escaped = re.escape(section_number)
59
+ patterns = [
60
+ re.compile(rf"§\s*{escaped}\b", re.IGNORECASE),
61
+ re.compile(rf"\bsection\s+{escaped}\b", re.IGNORECASE),
62
+ re.compile(rf"\bsec\.\s*{escaped}\b", re.IGNORECASE),
63
+ re.compile(rf"\bs\s+{escaped}\b", re.IGNORECASE),
64
+ ]
65
+
66
+ for doc in documents:
67
+ body = doc.get("html_body") or doc.get("content") or ""
68
+ if not body:
69
+ continue
70
+ for pattern in patterns:
71
+ if pattern.search(body):
72
+ return None # found — valid
73
+
74
+ return f"Section {section_number} not found in any source document"
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/legal_corpus/docs/JURISDICTION_IMPLEMENTATION.md ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Legal Corpus Jurisdiction Implementation Guide
2
+
3
+ This framework defines the reusable legal corpus pipeline contracts used by the
4
+ Netherlands BWBR implementation. Future jurisdictions should implement the same
5
+ interfaces without weakening Netherlands behavior or reusing unofficial source
6
+ logic.
7
+
8
+ ## Required Spec
9
+
10
+ Every jurisdiction must expose a `JurisdictionSpec` with:
11
+
12
+ - stable `jurisdiction_id`, `slug`, display name, country code, and language codes
13
+ - authoritative source descriptions
14
+ - default raw/catalog paths, if the jurisdiction supports durable acquisition
15
+ - Hugging Face repo ids for each published package variant
16
+ - aliases used by the registry and CLI dispatchers
17
+
18
+ ## Required Components
19
+
20
+ Every production jurisdiction must provide concrete implementations for:
21
+
22
+ - `DiscoveryProvider`: official-source discovery, catalog import, queuing, and
23
+ coverage reporting
24
+ - `FetchProvider`: resumable fetching/scraping from official source records
25
+ - `Parser`: source-document parsing into law and article records
26
+ - `HierarchyExtractor`: normalized hierarchy extraction for books, titles,
27
+ chapters, divisions, paragraphs, articles, or local equivalents
28
+ - `StatusClassifier`: official metadata based status/version classification
29
+ - `CIDGenerator`: deterministic content-address generation for law and article
30
+ payloads
31
+ - `PackageBuilder`: normalized and CID package builders
32
+ - `VectorIndexBuilder`: dense retrieval index builder
33
+ - `BM25IndexBuilder`: sparse retrieval index builder
34
+ - `JsonLdGraphBuilder`: JSON-LD graph builder
35
+ - `HuggingFacePublisher`: upload and remote verification
36
+ - `IntegrityValidator`: duplicate, parent/child, status inheritance, CID, and
37
+ graph validation
38
+
39
+ ## Status Semantics
40
+
41
+ Jurisdictions must preserve inactive and historical law. They must not delete a
42
+ law merely because it is old, repealed, superseded, or no longer current.
43
+
44
+ Each law row and article row should carry:
45
+
46
+ - `law_status`: one of `current`, `historical`, `repealed`, `superseded`,
47
+ `unknown`
48
+ - `is_current`
49
+ - `valid_from`
50
+ - `valid_to`
51
+ - `effective_date`
52
+ - `retrieved_at`
53
+ - `status_source`
54
+ - `status_confidence`
55
+ - `status_note`
56
+ - version fields where available
57
+
58
+ Article rows must inherit the parent law status/version fields unless official
59
+ article-level metadata proves a different value. If official metadata cannot
60
+ determine status, use `unknown`.
61
+
62
+ ## CID And Packaging Rules
63
+
64
+ CID generation must be deterministic for the exact normalized row payload. If
65
+ status/version fields are part of that payload, CID values are expected to change
66
+ when those fields change. Package manifests and all downstream indexes must be
67
+ rebuilt consistently from the same row set.
68
+
69
+ ## Completeness And Integrity
70
+
71
+ Jurisdictions with durable ingestion should converge through explicit states
72
+ such as discovered, queued, downloading, downloaded, parsed, packaged, uploaded,
73
+ verified, failed, and permanently skipped. Coverage reports must distinguish
74
+ processed, remaining, transient failures, permanent failures, and intentionally
75
+ skipped identifiers.
76
+
77
+ Integrity validation should detect duplicate source identifiers, duplicate CIDs,
78
+ orphan article rows, missing parent law rows, status inheritance drift, and
79
+ broken graph edges.
80
+
81
+ ## Publication
82
+
83
+ Dataset cards must state corpus scope, scrape date, exact row counts,
84
+ status-labeling semantics, limitations, and that the dataset is not legal advice.
85
+ Do not claim full jurisdiction coverage unless every discovered official
86
+ identifier has been parsed, intentionally skipped, or permanently failed with an
87
+ explanation.
88
+
89
+ ## First Implementation
90
+
91
+ The Netherlands implementation lives in
92
+ `ipfs_datasets_py.processors.legal_scrapers.netherlands_laws.jurisdiction` and
93
+ adapts the existing BWBR catalog-backed pipeline behind these interfaces. Its
94
+ existing CLI commands remain backward compatible.
95
+
96
+ Harvested Hugging Face gazette collectors are wrapped by
97
+ `ipfs_datasets_py.processors.legal_scrapers.international` behind the same
98
+ interfaces. Use `scrape_legal_data(jurisdiction, mode="snapshot"|"collect"|"native")`
99
+ as the unified API. Snapshot corpora are research snapshots, not official
100
+ consolidations, and are not legal advice.
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/common.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for Netherlands laws packaging builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import pyarrow as pa
12
+ import pyarrow.parquet as pq
13
+
14
+ from ipfs_datasets_py.utils.cid_utils import cid_for_bytes
15
+
16
+
17
+ PARSER_NOISE_PHRASES = [
18
+ "Toon relaties in LiDO",
19
+ "Maak een permanente link",
20
+ "Toon wetstechnische informatie",
21
+ "Geen andere versie om mee te vergelijken",
22
+ "Druk de regeling af",
23
+ "Druk het regelingonderdeel af",
24
+ "Sla de regeling op",
25
+ "Sla het regelingonderdeel op",
26
+ ]
27
+
28
+ PARSER_NOISE_PATTERNS = [
29
+ re.compile(rf"\b{re.escape(phrase)}\b", re.IGNORECASE) for phrase in PARSER_NOISE_PHRASES
30
+ ]
31
+ _WHITESPACE_RE = re.compile(r"\s+")
32
+
33
+
34
+ def iter_jsonl(path: Path):
35
+ with path.open("r", encoding="utf-8") as handle:
36
+ for line in handle:
37
+ line = line.strip()
38
+ if line:
39
+ yield json.loads(line)
40
+
41
+
42
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
43
+ rows: list[dict[str, Any]] = []
44
+ for row in iter_jsonl(path):
45
+ rows.append(row)
46
+ return rows
47
+
48
+
49
+ def count_jsonl(path: Path) -> int:
50
+ count = 0
51
+ with path.open("r", encoding="utf-8") as handle:
52
+ for line in handle:
53
+ if line.strip():
54
+ count += 1
55
+ return count
56
+
57
+
58
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ with path.open("w", encoding="utf-8") as handle:
61
+ for row in rows:
62
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
63
+
64
+
65
+ def clean_legal_text(text: Any) -> str:
66
+ """Remove official website UI chrome from scraped legal text."""
67
+ if text is None:
68
+ return ""
69
+ cleaned = str(text)
70
+ for pattern in PARSER_NOISE_PATTERNS:
71
+ cleaned = pattern.sub(" ", cleaned)
72
+ return _WHITESPACE_RE.sub(" ", cleaned).strip()
73
+
74
+
75
+ def stable_row_key(row: dict[str, Any]) -> str:
76
+ return json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)
77
+
78
+
79
+ def disambiguate_duplicate_article_identifiers(rows: list[dict[str, Any]]) -> int:
80
+ """Make repeated scraper article IDs unique by appending a hierarchy-derived suffix."""
81
+ groups: dict[str, list[dict[str, Any]]] = {}
82
+ for row in rows:
83
+ identifier = str(row.get("article_identifier") or "")
84
+ if not identifier:
85
+ continue
86
+ groups.setdefault(identifier, []).append(row)
87
+
88
+ changed = 0
89
+ for identifier, group in groups.items():
90
+ if len(group) < 2:
91
+ continue
92
+ for row in group:
93
+ basis = {
94
+ "citation": row.get("citation"),
95
+ "hierarchy_path": row.get("hierarchy_path"),
96
+ "hierarchy_path_text": row.get("hierarchy_path_text"),
97
+ "article_number": row.get("article_number"),
98
+ "text": row.get("text"),
99
+ }
100
+ suffix = hashlib.sha256(stable_row_key(basis).encode("utf-8")).hexdigest()[:12]
101
+ row["article_identifier"] = f"{identifier}:path:{suffix}"
102
+ changed += 1
103
+ return changed
104
+
105
+
106
+ def _parquet_safe(value: Any) -> Any:
107
+ if value == {}:
108
+ return None
109
+ if isinstance(value, dict):
110
+ return {key: _parquet_safe(item) for key, item in value.items()}
111
+ if isinstance(value, list):
112
+ return [_parquet_safe(item) for item in value]
113
+ return value
114
+
115
+
116
+ def _jsonify_complex(value: Any) -> Any:
117
+ if isinstance(value, (dict, list)):
118
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
119
+ return value
120
+
121
+
122
+ def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None:
123
+ path.parent.mkdir(parents=True, exist_ok=True)
124
+ safe_rows = [{key: _parquet_safe(value) for key, value in row.items()} for row in rows]
125
+ try:
126
+ table = pa.Table.from_pylist(safe_rows)
127
+ except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError):
128
+ table = pa.Table.from_pylist(
129
+ [{key: _jsonify_complex(value) for key, value in row.items()} for row in safe_rows]
130
+ )
131
+ pq.write_table(table, path, compression="zstd")
132
+
133
+
134
+ def sha256(path: Path) -> str:
135
+ digest = hashlib.sha256()
136
+ with path.open("rb") as handle:
137
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
138
+ digest.update(chunk)
139
+ return digest.hexdigest()
140
+
141
+
142
+ def file_cid(path: Path) -> str:
143
+ return cid_for_bytes(path.read_bytes())
144
+
145
+
146
+ def file_manifest_entry(path: Path, records: int | None = None) -> dict[str, Any]:
147
+ entry: dict[str, Any] = {
148
+ "bytes": path.stat().st_size,
149
+ "sha256": sha256(path),
150
+ "file_cid": file_cid(path),
151
+ }
152
+ if records is not None:
153
+ entry["records"] = records
154
+ return entry
155
+
156
+
157
+ def write_json(path: Path, obj: Any) -> None:
158
+ path.parent.mkdir(parents=True, exist_ok=True)
159
+ path.write_text(json.dumps(obj, indent=2, ensure_ascii=False), encoding="utf-8")
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_indexes.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build CID-keyed vector, BM25, and JSON-LD indexes for Netherlands laws."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import pickle
8
+ import re
9
+ from collections import Counter, defaultdict
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from ipfs_datasets_py.utils.cid_utils import cid_for_obj
14
+
15
+ from .common import (
16
+ file_cid,
17
+ file_manifest_entry,
18
+ read_jsonl,
19
+ write_json,
20
+ write_jsonl,
21
+ write_parquet,
22
+ )
23
+ from ..paths import (
24
+ BM25_INDEX_DATASET_NAME,
25
+ DEFAULT_HF_REPO_IDS,
26
+ HF_DATA_DIR,
27
+ IPFS_DATASET_NAME,
28
+ KNOWLEDGE_GRAPH_DATASET_NAME,
29
+ VECTOR_INDEX_DATASET_NAME,
30
+ )
31
+
32
+
33
+ DEFAULT_SOURCE_DIR = HF_DATA_DIR / IPFS_DATASET_NAME
34
+ DEFAULT_VECTOR_OUT_DIR = HF_DATA_DIR / VECTOR_INDEX_DATASET_NAME
35
+ DEFAULT_BM25_OUT_DIR = HF_DATA_DIR / BM25_INDEX_DATASET_NAME
36
+ DEFAULT_KG_OUT_DIR = HF_DATA_DIR / KNOWLEDGE_GRAPH_DATASET_NAME
37
+ TOKENIZER_RE = re.compile(r"[0-9A-Za-zÀ-ÿ_]+", re.UNICODE)
38
+
39
+
40
+ def tokenise(text: str) -> list[str]:
41
+ return [match.group(0).lower() for match in TOKENIZER_RE.finditer(text or "")]
42
+
43
+
44
+ def load_source_rows(source_dir: Path | None = None) -> list[dict[str, Any]]:
45
+ source_dir = source_dir or DEFAULT_SOURCE_DIR
46
+ laws = read_jsonl(source_dir / "data/laws/ipfs_netherlands_laws.jsonl")
47
+ articles = read_jsonl(source_dir / "data/articles/ipfs_netherlands_laws_articles.jsonl")
48
+ corpus: list[dict[str, Any]] = []
49
+ for row in laws:
50
+ corpus.append(
51
+ {
52
+ "record_type": "law",
53
+ "source_cid": row["cid"],
54
+ "law_cid": row["cid"],
55
+ "law_identifier": row.get("law_identifier"),
56
+ "article_identifier": None,
57
+ "title": row.get("title") or row.get("citation") or row.get("law_identifier"),
58
+ "citation": row.get("citation"),
59
+ "content_address": row.get("content_address"),
60
+ "source_url": row.get("source_url"),
61
+ "law_status": row.get("law_status"),
62
+ "is_current": row.get("is_current"),
63
+ "valid_from": row.get("valid_from"),
64
+ "valid_to": row.get("valid_to"),
65
+ "effective_date": row.get("effective_date"),
66
+ "retrieved_at": row.get("retrieved_at"),
67
+ "status_source": row.get("status_source"),
68
+ "status_confidence": row.get("status_confidence"),
69
+ "status_note": row.get("status_note"),
70
+ "text": row.get("text") or "",
71
+ }
72
+ )
73
+ for row in articles:
74
+ corpus.append(
75
+ {
76
+ "record_type": "article",
77
+ "source_cid": row["cid"],
78
+ "law_cid": row.get("law_cid"),
79
+ "law_identifier": row.get("law_identifier"),
80
+ "article_identifier": row.get("article_identifier"),
81
+ "title": row.get("citation") or row.get("article_identifier"),
82
+ "citation": row.get("citation"),
83
+ "content_address": row.get("content_address"),
84
+ "source_url": None,
85
+ "law_status": row.get("law_status"),
86
+ "is_current": row.get("is_current"),
87
+ "valid_from": row.get("valid_from"),
88
+ "valid_to": row.get("valid_to"),
89
+ "effective_date": row.get("effective_date"),
90
+ "retrieved_at": row.get("retrieved_at"),
91
+ "status_source": row.get("status_source"),
92
+ "status_confidence": row.get("status_confidence"),
93
+ "status_note": row.get("status_note"),
94
+ "text": row.get("text") or "",
95
+ }
96
+ )
97
+ return corpus
98
+
99
+
100
+ def load_source_run_metadata(source_dir: Path | None = None) -> dict[str, Any]:
101
+ source_dir = source_dir or DEFAULT_SOURCE_DIR
102
+ metadata_path = source_dir / "data/metadata/netherlands_laws_run_metadata_latest.json"
103
+ if not metadata_path.exists():
104
+ return {}
105
+ try:
106
+ return json.loads(metadata_path.read_text(encoding="utf-8"))
107
+ except Exception:
108
+ return {}
109
+
110
+
111
+ def _write_dataset_card(
112
+ out_dir: Path, title: str, repo_id: str, configs: list[str], body: str
113
+ ) -> None:
114
+ config_yaml = "\n".join(
115
+ [
116
+ f"- config_name: {config}\n data_files:\n - split: train\n path: parquet/{config}/*.parquet"
117
+ for config in configs
118
+ ]
119
+ )
120
+ readme = f"""---
121
+ pretty_name: {title}
122
+ language:
123
+ - nl
124
+ tags:
125
+ - ipfs
126
+ - cid
127
+ - legal
128
+ license: other
129
+ configs:
130
+ {config_yaml}
131
+ ---
132
+
133
+ # {title}
134
+
135
+ Hugging Face target: `{repo_id}`.
136
+
137
+ {body}
138
+ """
139
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
140
+
141
+
142
+ def _write_gitattributes(out_dir: Path) -> None:
143
+ (out_dir / ".gitattributes").write_text(
144
+ "parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text\n"
145
+ "artifacts/* filter=lfs diff=lfs merge=lfs -text\n"
146
+ "data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text\n"
147
+ "data/**/*.jsonld filter=lfs diff=lfs merge=lfs -text\n",
148
+ encoding="utf-8",
149
+ )
150
+
151
+
152
+ def _catalog_summary_text(run_metadata: dict[str, Any]) -> str:
153
+ if not run_metadata.get("catalog_backed_run"):
154
+ return ""
155
+ counts = run_metadata.get("catalog_coverage_counts") or {}
156
+ return (
157
+ f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). "
158
+ f"Catalog coverage after this run: {counts.get('complete', 'unknown')} complete of "
159
+ f"{counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) "
160
+ f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: "
161
+ f"{counts.get('remaining', 'unknown')}. Integrity validation ok: "
162
+ f"{run_metadata.get('catalog_integrity_ok', 'unknown')}. "
163
+ "This is not full Dutch corpus coverage until every discovered identifier is parsed, intentionally skipped, "
164
+ "or permanently failed with explanation. "
165
+ )
166
+
167
+
168
+ def _write_manifest(
169
+ out_dir: Path,
170
+ dataset_name: str,
171
+ repo_id: str,
172
+ record_counts: dict[str, int],
173
+ source_dataset: str = DEFAULT_HF_REPO_IDS["base"],
174
+ extra: dict[str, Any] | None = None,
175
+ ) -> dict[str, Any]:
176
+ manifest: dict[str, Any] = {
177
+ "dataset_name": dataset_name,
178
+ "source_dataset": source_dataset,
179
+ "repo_target": repo_id,
180
+ "upload_target": repo_id,
181
+ "records": record_counts,
182
+ "files": {},
183
+ }
184
+ if extra:
185
+ manifest["index_metadata"] = extra
186
+ for path in sorted(
187
+ p for p in out_dir.rglob("*") if p.is_file() and p.name != "dataset_manifest.json"
188
+ ):
189
+ rel = path.relative_to(out_dir).as_posix()
190
+ records = None
191
+ for key, count in record_counts.items():
192
+ if (
193
+ f"/{key}/" in f"/{rel}/"
194
+ or rel.startswith(f"parquet/{key}/")
195
+ or rel.startswith(f"data/{key}/")
196
+ ):
197
+ records = count
198
+ break
199
+ manifest["files"][rel] = file_manifest_entry(path, records)
200
+ write_json(out_dir / "dataset_manifest.json", manifest)
201
+ return manifest
202
+
203
+
204
+ def build_vector_index(
205
+ corpus: list[dict[str, Any]] | None = None,
206
+ source_dir: Path | None = None,
207
+ out_dir: Path | None = None,
208
+ repo_id: str = DEFAULT_HF_REPO_IDS["vector"],
209
+ ) -> Path:
210
+ import faiss
211
+ from sklearn.decomposition import TruncatedSVD
212
+ from sklearn.feature_extraction.text import TfidfVectorizer
213
+ from sklearn.preprocessing import normalize
214
+
215
+ corpus = corpus or load_source_rows(source_dir)
216
+ run_metadata = load_source_run_metadata(source_dir)
217
+ out_dir = out_dir or DEFAULT_VECTOR_OUT_DIR
218
+ docs: list[dict[str, Any]] = []
219
+ texts: list[str] = []
220
+ for row in corpus:
221
+ search_text = f"{row.get('title') or ''}\n{row.get('citation') or ''}\n{row.get('text') or ''}".strip()
222
+ docs.append({**row, "search_text": search_text})
223
+ texts.append(search_text)
224
+
225
+ vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1, max_features=8192)
226
+ tfidf = vectorizer.fit_transform(texts)
227
+ max_components = min(256, max(2, tfidf.shape[0] - 1), max(2, tfidf.shape[1] - 1))
228
+ svd = TruncatedSVD(n_components=max_components, random_state=42)
229
+ dense = normalize(svd.fit_transform(tfidf), norm="l2").astype("float32")
230
+
231
+ index = faiss.IndexFlatIP(dense.shape[1])
232
+ index.add(dense)
233
+
234
+ mapping_rows: list[dict[str, Any]] = []
235
+ for idx, row in enumerate(docs):
236
+ payload = {
237
+ "cid": row["source_cid"],
238
+ "source_cid": row["source_cid"],
239
+ "law_cid": row.get("law_cid"),
240
+ "record_type": row["record_type"],
241
+ "law_identifier": row.get("law_identifier"),
242
+ "article_identifier": row.get("article_identifier"),
243
+ "title": row.get("title"),
244
+ "citation": row.get("citation"),
245
+ "content_address": row.get("content_address"),
246
+ "law_status": row.get("law_status"),
247
+ "is_current": row.get("is_current"),
248
+ "valid_from": row.get("valid_from"),
249
+ "valid_to": row.get("valid_to"),
250
+ "effective_date": row.get("effective_date"),
251
+ "retrieved_at": row.get("retrieved_at"),
252
+ "status_source": row.get("status_source"),
253
+ "status_confidence": row.get("status_confidence"),
254
+ "status_note": row.get("status_note"),
255
+ "embedding": dense[idx].tolist(),
256
+ "embedding_dim": int(dense.shape[1]),
257
+ "search_text_preview": row["search_text"][:500],
258
+ }
259
+ payload["index_row_cid"] = cid_for_obj(payload)
260
+ mapping_rows.append(payload)
261
+
262
+ write_parquet(out_dir / "parquet/mapping/train-00000-of-00001.parquet", mapping_rows)
263
+ write_jsonl(out_dir / "data/mapping/ipfs_netherlands_laws_vector_mapping.jsonl", mapping_rows)
264
+ (out_dir / "artifacts").mkdir(parents=True, exist_ok=True)
265
+ (out_dir / "artifacts/faiss.index").write_bytes(faiss.serialize_index(index).tobytes())
266
+ (out_dir / "artifacts/vectorizer.pkl").write_bytes(pickle.dumps(vectorizer))
267
+ (out_dir / "artifacts/svd.pkl").write_bytes(pickle.dumps(svd))
268
+ metadata = {
269
+ "dataset_name": VECTOR_INDEX_DATASET_NAME,
270
+ "source_dataset": DEFAULT_HF_REPO_IDS["base"],
271
+ "records": len(mapping_rows),
272
+ "embedding_method": "tfidf_plus_truncated_svd",
273
+ "embedding_dim": int(dense.shape[1]),
274
+ "faiss_metric": "inner_product_on_l2_normalized_vectors",
275
+ "index_key": "source_cid",
276
+ }
277
+ write_json(out_dir / "artifacts/metadata.json", metadata)
278
+ scrape_date = str(run_metadata.get("scraped_at") or "unknown")
279
+ full_bwb = run_metadata.get("full_bwb_discovery") or {}
280
+ catalog_summary = _catalog_summary_text(run_metadata)
281
+ _write_dataset_card(
282
+ out_dir,
283
+ "IPFS Netherlands Laws Vector Index",
284
+ repo_id,
285
+ ["mapping"],
286
+ (
287
+ "Dense vector mapping keyed by source CID, with FAISS and TF-IDF/SVD artifacts.\n\n"
288
+ f"This index covers {len(mapping_rows)} rows from the paired CID dataset. "
289
+ f"Source scrape date: {scrape_date}. "
290
+ f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers "
291
+ f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). "
292
+ f"{catalog_summary}"
293
+ "The current source dataset may be capped; do not describe it as the full Dutch corpus unless "
294
+ "the paired base dataset manifest/run metadata proves full discovery coverage. "
295
+ "The paired base dataset includes article extraction diagnostics and parser coverage improvements "
296
+ "for older/French heading styles. The paired source package was quality-audited after parser-noise "
297
+ "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean "
298
+ "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with "
299
+ "`law_status`, `is_current`, validity dates, status source, confidence, and notes; these fields "
300
+ "are also present in the vector mapping rows for filtering. This index is not legal advice."
301
+ ),
302
+ )
303
+ _write_gitattributes(out_dir)
304
+ _write_manifest(
305
+ out_dir, VECTOR_INDEX_DATASET_NAME, repo_id, {"mapping": len(mapping_rows)}, extra=metadata
306
+ )
307
+ return out_dir
308
+
309
+
310
+ def build_bm25_index(
311
+ corpus: list[dict[str, Any]] | None = None,
312
+ source_dir: Path | None = None,
313
+ out_dir: Path | None = None,
314
+ repo_id: str = DEFAULT_HF_REPO_IDS["bm25"],
315
+ ) -> Path:
316
+ corpus = corpus or load_source_rows(source_dir)
317
+ run_metadata = load_source_run_metadata(source_dir)
318
+ out_dir = out_dir or DEFAULT_BM25_OUT_DIR
319
+ doc_lengths: dict[str, int] = {}
320
+ tf_by_doc: dict[str, Counter[str]] = {}
321
+ postings_by_term: dict[str, list[tuple[str, int]]] = defaultdict(list)
322
+ doc_rows: list[dict[str, Any]] = []
323
+ row_by_cid: dict[str, dict[str, Any]] = {}
324
+
325
+ for row in corpus:
326
+ text = (
327
+ f"{row.get('title') or ''} {row.get('citation') or ''} {row.get('text') or ''}".strip()
328
+ )
329
+ source_cid = row["source_cid"]
330
+ tokens = tokenise(text)
331
+ term_counts = Counter(tokens)
332
+ doc_lengths[source_cid] = len(tokens)
333
+ tf_by_doc[source_cid] = term_counts
334
+ for term, tf in term_counts.items():
335
+ postings_by_term[term].append((source_cid, tf))
336
+ payload = {
337
+ "cid": source_cid,
338
+ "source_cid": source_cid,
339
+ "law_cid": row.get("law_cid"),
340
+ "record_type": row["record_type"],
341
+ "law_identifier": row.get("law_identifier"),
342
+ "article_identifier": row.get("article_identifier"),
343
+ "title": row.get("title"),
344
+ "citation": row.get("citation"),
345
+ "content_address": row.get("content_address"),
346
+ "law_status": row.get("law_status"),
347
+ "is_current": row.get("is_current"),
348
+ "valid_from": row.get("valid_from"),
349
+ "valid_to": row.get("valid_to"),
350
+ "effective_date": row.get("effective_date"),
351
+ "retrieved_at": row.get("retrieved_at"),
352
+ "status_source": row.get("status_source"),
353
+ "status_confidence": row.get("status_confidence"),
354
+ "status_note": row.get("status_note"),
355
+ "doc_length": len(tokens),
356
+ "token_count_unique": len(tf_by_doc[source_cid]),
357
+ "text_preview": text[:500],
358
+ }
359
+ payload["doc_row_cid"] = cid_for_obj(payload)
360
+ doc_rows.append(payload)
361
+ row_by_cid[source_cid] = payload
362
+
363
+ n_docs = len(doc_lengths)
364
+ avgdl = sum(doc_lengths.values()) / max(1, n_docs)
365
+ doc_freq: Counter[str] = Counter()
366
+ for tf_counter in tf_by_doc.values():
367
+ doc_freq.update(tf_counter.keys())
368
+
369
+ k1 = 1.5
370
+ b = 0.75
371
+ term_rows: list[dict[str, Any]] = []
372
+ for term in sorted(doc_freq):
373
+ df = doc_freq[term]
374
+ idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
375
+ postings = []
376
+ for source_cid, tf in postings_by_term.get(term, []):
377
+ dl = doc_lengths[source_cid]
378
+ score = idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (dl / avgdl))))
379
+ postings.append(
380
+ {
381
+ "source_cid": source_cid,
382
+ "law_cid": row_by_cid[source_cid]["law_cid"],
383
+ "tf": tf,
384
+ "doc_length": dl,
385
+ "bm25_term_score": score,
386
+ }
387
+ )
388
+ row = {
389
+ "term": term,
390
+ "doc_freq": df,
391
+ "idf": idf,
392
+ "postings_count": len(postings),
393
+ "postings": postings,
394
+ }
395
+ row["term_row_cid"] = cid_for_obj(row)
396
+ term_rows.append(row)
397
+
398
+ write_parquet(out_dir / "parquet/documents/train-00000-of-00001.parquet", doc_rows)
399
+ write_parquet(out_dir / "parquet/terms/train-00000-of-00001.parquet", term_rows)
400
+ write_jsonl(out_dir / "data/documents/ipfs_netherlands_laws_bm25_documents.jsonl", doc_rows)
401
+ write_jsonl(out_dir / "data/terms/ipfs_netherlands_laws_bm25_terms.jsonl", term_rows)
402
+ metadata = {
403
+ "dataset_name": BM25_INDEX_DATASET_NAME,
404
+ "source_dataset": DEFAULT_HF_REPO_IDS["base"],
405
+ "records": {"documents": len(doc_rows), "terms": len(term_rows)},
406
+ "bm25": {"k1": k1, "b": b, "avgdl": avgdl},
407
+ "index_key": "source_cid",
408
+ }
409
+ write_json(out_dir / "artifacts/metadata.json", metadata)
410
+ scrape_date = str(run_metadata.get("scraped_at") or "unknown")
411
+ full_bwb = run_metadata.get("full_bwb_discovery") or {}
412
+ catalog_summary = _catalog_summary_text(run_metadata)
413
+ _write_dataset_card(
414
+ out_dir,
415
+ "IPFS Netherlands Laws BM25 Index",
416
+ repo_id,
417
+ ["documents", "terms"],
418
+ (
419
+ "Sparse BM25 document and postings tables keyed by source CID.\n\n"
420
+ f"This index covers {len(doc_rows)} documents and {len(term_rows)} terms from the paired CID dataset. "
421
+ f"Source scrape date: {scrape_date}. "
422
+ f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers "
423
+ f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). "
424
+ f"{catalog_summary}"
425
+ "The current source dataset may be capped; do not describe it as the full Dutch corpus unless "
426
+ "the paired base dataset manifest/run metadata proves full discovery coverage. "
427
+ "The paired base dataset includes article extraction diagnostics and parser coverage improvements "
428
+ "for older/French heading styles. The paired source package was quality-audited after parser-noise "
429
+ "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean "
430
+ "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with "
431
+ "`law_status`, `is_current`, validity dates, status source, confidence, and notes; these fields "
432
+ "are also present in BM25 document rows for filtering. This index is not legal advice."
433
+ ),
434
+ )
435
+ _write_gitattributes(out_dir)
436
+ _write_manifest(
437
+ out_dir,
438
+ BM25_INDEX_DATASET_NAME,
439
+ repo_id,
440
+ {"documents": len(doc_rows), "terms": len(term_rows)},
441
+ extra=metadata,
442
+ )
443
+ return out_dir
444
+
445
+
446
+ def build_knowledge_graph(
447
+ corpus: list[dict[str, Any]] | None = None,
448
+ source_dir: Path | None = None,
449
+ out_dir: Path | None = None,
450
+ repo_id: str = DEFAULT_HF_REPO_IDS["knowledge-graph"],
451
+ ) -> Path:
452
+ corpus = corpus or load_source_rows(source_dir)
453
+ run_metadata = load_source_run_metadata(source_dir)
454
+ out_dir = out_dir or DEFAULT_KG_OUT_DIR
455
+ laws = [row for row in corpus if row["record_type"] == "law"]
456
+ articles = [row for row in corpus if row["record_type"] == "article"]
457
+ graph_nodes: list[dict[str, Any]] = []
458
+ graph_edges: list[dict[str, Any]] = []
459
+ jsonld_graph: list[dict[str, Any]] = []
460
+
461
+ context = {
462
+ "@vocab": "https://schema.org/",
463
+ "source_cid": "https://schema.org/identifier",
464
+ "law_cid": "https://schema.org/isPartOf",
465
+ "article_identifier": "https://schema.org/identifier",
466
+ "law_identifier": "https://schema.org/identifier",
467
+ "content_address": "https://schema.org/url",
468
+ "law_status": "https://schema.org/legislationLegalForce",
469
+ "valid_from": "https://schema.org/validFrom",
470
+ "valid_to": "https://schema.org/validThrough",
471
+ "hasPart": {"@id": "https://schema.org/hasPart", "@type": "@id"},
472
+ "isPartOf": {"@id": "https://schema.org/isPartOf", "@type": "@id"},
473
+ }
474
+
475
+ for law in laws:
476
+ node = {
477
+ "@id": law["content_address"],
478
+ "@type": "Legislation",
479
+ "source_cid": law["source_cid"],
480
+ "law_identifier": law["law_identifier"],
481
+ "name": law["title"],
482
+ "law_status": law.get("law_status") or "unknown",
483
+ "is_current": law.get("is_current"),
484
+ "valid_from": law.get("valid_from"),
485
+ "valid_to": law.get("valid_to"),
486
+ "effective_date": law.get("effective_date"),
487
+ "retrieved_at": law.get("retrieved_at"),
488
+ "status_source": law.get("status_source"),
489
+ "status_confidence": law.get("status_confidence"),
490
+ "status_note": law.get("status_note"),
491
+ }
492
+ jsonld_graph.append(node)
493
+ graph_nodes.append(
494
+ {
495
+ "cid": law["source_cid"],
496
+ "node_cid": cid_for_obj(node),
497
+ "source_cid": law["source_cid"],
498
+ "record_type": "law",
499
+ "label": law["title"],
500
+ "jsonld_id": law["content_address"],
501
+ "law_identifier": law["law_identifier"],
502
+ "article_identifier": None,
503
+ "law_status": law.get("law_status"),
504
+ "is_current": law.get("is_current"),
505
+ "valid_from": law.get("valid_from"),
506
+ "valid_to": law.get("valid_to"),
507
+ "effective_date": law.get("effective_date"),
508
+ "retrieved_at": law.get("retrieved_at"),
509
+ "status_source": law.get("status_source"),
510
+ "status_confidence": law.get("status_confidence"),
511
+ }
512
+ )
513
+
514
+ law_map = {law["law_identifier"]: law for law in laws}
515
+ for article in articles:
516
+ law = law_map.get(article["law_identifier"])
517
+ node = {
518
+ "@id": article["content_address"],
519
+ "@type": "LegislationObject",
520
+ "source_cid": article["source_cid"],
521
+ "article_identifier": article["article_identifier"],
522
+ "law_identifier": article["law_identifier"],
523
+ "name": article["title"],
524
+ "law_status": article.get("law_status") or "unknown",
525
+ "is_current": article.get("is_current"),
526
+ "valid_from": article.get("valid_from"),
527
+ "valid_to": article.get("valid_to"),
528
+ "effective_date": article.get("effective_date"),
529
+ "retrieved_at": article.get("retrieved_at"),
530
+ "status_source": article.get("status_source"),
531
+ "status_confidence": article.get("status_confidence"),
532
+ "status_note": article.get("status_note"),
533
+ }
534
+ if law:
535
+ node["isPartOf"] = {"@id": law["content_address"]}
536
+ jsonld_graph.append(node)
537
+ graph_nodes.append(
538
+ {
539
+ "cid": article["source_cid"],
540
+ "node_cid": cid_for_obj(node),
541
+ "source_cid": article["source_cid"],
542
+ "record_type": "article",
543
+ "label": article["title"],
544
+ "jsonld_id": article["content_address"],
545
+ "law_identifier": article["law_identifier"],
546
+ "article_identifier": article["article_identifier"],
547
+ "law_status": article.get("law_status"),
548
+ "is_current": article.get("is_current"),
549
+ "valid_from": article.get("valid_from"),
550
+ "valid_to": article.get("valid_to"),
551
+ "effective_date": article.get("effective_date"),
552
+ "retrieved_at": article.get("retrieved_at"),
553
+ "status_source": article.get("status_source"),
554
+ "status_confidence": article.get("status_confidence"),
555
+ }
556
+ )
557
+ if law:
558
+ edge = {
559
+ "cid": article["source_cid"],
560
+ "edge_type": "isPartOf",
561
+ "source_cid": article["source_cid"],
562
+ "target_cid": law["source_cid"],
563
+ "source_id": article["content_address"],
564
+ "target_id": law["content_address"],
565
+ "law_identifier": article["law_identifier"],
566
+ "article_identifier": article["article_identifier"],
567
+ }
568
+ edge["edge_cid"] = cid_for_obj(edge)
569
+ graph_edges.append(edge)
570
+
571
+ for law in laws:
572
+ children = [
573
+ {"@id": article["content_address"]}
574
+ for article in articles
575
+ if article["law_identifier"] == law["law_identifier"]
576
+ ]
577
+ if children:
578
+ for obj in jsonld_graph:
579
+ if obj["@id"] == law["content_address"]:
580
+ obj["hasPart"] = children
581
+ break
582
+
583
+ jsonld_doc = {"@context": context, "@graph": jsonld_graph}
584
+ write_jsonl(out_dir / "data/nodes/ipfs_netherlands_laws_kg_nodes.jsonl", graph_nodes)
585
+ write_jsonl(out_dir / "data/edges/ipfs_netherlands_laws_kg_edges.jsonl", graph_edges)
586
+ (out_dir / "data/graph").mkdir(parents=True, exist_ok=True)
587
+ (out_dir / "data/graph/ipfs_netherlands_laws_kg.jsonld").write_text(
588
+ json.dumps(jsonld_doc, ensure_ascii=False, indent=2), encoding="utf-8"
589
+ )
590
+ write_parquet(out_dir / "parquet/nodes/train-00000-of-00001.parquet", graph_nodes)
591
+ write_parquet(out_dir / "parquet/edges/train-00000-of-00001.parquet", graph_edges)
592
+ metadata = {
593
+ "dataset_name": KNOWLEDGE_GRAPH_DATASET_NAME,
594
+ "source_dataset": DEFAULT_HF_REPO_IDS["base"],
595
+ "records": {"nodes": len(graph_nodes), "edges": len(graph_edges)},
596
+ "graph_root_cid": cid_for_obj(jsonld_doc),
597
+ "index_key": "source_cid",
598
+ }
599
+ write_json(out_dir / "artifacts/metadata.json", metadata)
600
+ scrape_date = str(run_metadata.get("scraped_at") or "unknown")
601
+ full_bwb = run_metadata.get("full_bwb_discovery") or {}
602
+ catalog_summary = _catalog_summary_text(run_metadata)
603
+ _write_dataset_card(
604
+ out_dir,
605
+ "IPFS Netherlands Laws Knowledge Graph",
606
+ repo_id,
607
+ ["nodes", "edges"],
608
+ (
609
+ "JSON-LD graph and node/edge tables whose identities are IPFS content addresses.\n\n"
610
+ f"This graph currently has {len(graph_nodes)} nodes and {len(graph_edges)} edges from the paired CID dataset. "
611
+ f"Source scrape date: {scrape_date}. "
612
+ f"Full BWB discovery inventory found {full_bwb.get('unique_laws_discovered', 'unknown')} unique BWBR identifiers "
613
+ f"from {full_bwb.get('number_of_records_reported', 'unknown')} official SRU record(s). "
614
+ f"{catalog_summary}"
615
+ "The current source dataset may be capped; do not describe it as the full Dutch corpus unless "
616
+ "the paired base dataset manifest/run metadata proves full discovery coverage. "
617
+ "The paired base dataset includes article extraction diagnostics and parser coverage improvements "
618
+ "for older/French heading styles. The paired source package was quality-audited after parser-noise "
619
+ "cleanup for official website UI chrome, duplicate article identifier disambiguation, clean "
620
+ "hierarchy/citation validation, and sampled CID/vector/BM25/KG retrieval checks. Historical/former laws are preserved and labeled with "
621
+ "`law_status`, `is_current`, validity dates, status source, confidence, and notes in graph nodes "
622
+ "and JSON-LD objects. This graph is not legal advice."
623
+ ),
624
+ )
625
+ _write_gitattributes(out_dir)
626
+ _write_manifest(
627
+ out_dir,
628
+ KNOWLEDGE_GRAPH_DATASET_NAME,
629
+ repo_id,
630
+ {"nodes": len(graph_nodes), "edges": len(graph_edges)},
631
+ extra=metadata,
632
+ )
633
+ return out_dir
634
+
635
+
636
+ def build_vector_package(*args: Any, **kwargs: Any) -> Path:
637
+ return build_vector_index(*args, **kwargs)
638
+
639
+
640
+ def build_bm25_package(*args: Any, **kwargs: Any) -> Path:
641
+ return build_bm25_index(*args, **kwargs)
642
+
643
+
644
+ def build_knowledge_graph_package(*args: Any, **kwargs: Any) -> Path:
645
+ return build_knowledge_graph(*args, **kwargs)
646
+
647
+
648
+ def build_all_indexes(source_dir: Path | None = None) -> list[Path]:
649
+ corpus = load_source_rows(source_dir)
650
+ return [
651
+ build_vector_index(corpus=corpus, source_dir=source_dir),
652
+ build_bm25_index(corpus=corpus, source_dir=source_dir),
653
+ build_knowledge_graph(corpus=corpus, source_dir=source_dir),
654
+ ]
655
+
656
+
657
+ def main() -> None:
658
+ built = build_all_indexes()
659
+ print(json.dumps([str(path) for path in built], indent=2))
660
+
661
+
662
+ if __name__ == "__main__":
663
+ main()
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/ipfs_package.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the CID-addressed Hugging Face package for Netherlands laws."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from ipfs_datasets_py.utils.cid_utils import cid_for_obj
10
+
11
+ from .common import (
12
+ clean_legal_text,
13
+ disambiguate_duplicate_article_identifiers,
14
+ file_manifest_entry,
15
+ read_jsonl,
16
+ stable_row_key,
17
+ write_json,
18
+ write_jsonl,
19
+ write_parquet,
20
+ )
21
+ from ..paths import (
22
+ DEFAULT_HF_REPO_IDS,
23
+ HF_DATA_DIR,
24
+ IPFS_DATASET_NAME,
25
+ PACKAGE_RAW_OUTPUT_DIR,
26
+ )
27
+
28
+
29
+ DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["base"]
30
+ DEFAULT_RAW_DIR = PACKAGE_RAW_OUTPUT_DIR
31
+ DEFAULT_OUT_DIR = HF_DATA_DIR / IPFS_DATASET_NAME
32
+
33
+
34
+ def coverage_note(run_metadata: dict[str, Any], record_counts: dict[str, int]) -> str:
35
+ max_documents = run_metadata.get("max_documents")
36
+ parsed = (
37
+ run_metadata.get("output_records_count")
38
+ or run_metadata.get("documents_parsed")
39
+ or record_counts.get("laws", 0)
40
+ )
41
+ discovered = (
42
+ run_metadata.get("total_unique_laws_discovered")
43
+ or run_metadata.get("unique_laws_discovered")
44
+ or "unknown"
45
+ )
46
+ failed = run_metadata.get("documents_failed", "unknown")
47
+ if max_documents:
48
+ return (
49
+ f"This is a capped Netherlands scrape, not the full Dutch corpus. "
50
+ f"The scrape used max_documents={max_documents}, parsed {parsed} law record(s), "
51
+ f"and discovered {discovered} unique official BWBR law document(s) before applying the cap. "
52
+ f"Documents failed: {failed}."
53
+ )
54
+ return (
55
+ "This is an uncapped discovered-corpus Netherlands scrape from the configured official discovery sources, "
56
+ "but it should not be described as the full Dutch corpus unless the run metadata confirms discovery covered "
57
+ f"the complete intended BWBR population. Parsed law records: {parsed}; discovered: {discovered}; "
58
+ f"documents failed: {failed}."
59
+ )
60
+
61
+
62
+ def law_payload(row: dict[str, Any]) -> dict[str, Any]:
63
+ keep = [
64
+ "record_type",
65
+ "jurisdiction",
66
+ "jurisdiction_name",
67
+ "country",
68
+ "language",
69
+ "identifier",
70
+ "law_identifier",
71
+ "official_identifier",
72
+ "law_version_identifier",
73
+ "version_specific_identifier",
74
+ "title",
75
+ "canonical_title",
76
+ "aliases",
77
+ "text",
78
+ "source_url",
79
+ "canonical_law_url",
80
+ "canonical_document_url",
81
+ "versioned_law_url",
82
+ "information_url",
83
+ "document_type",
84
+ "citation",
85
+ "official_metadata",
86
+ "law_status",
87
+ "is_current",
88
+ "valid_from",
89
+ "valid_to",
90
+ "effective_date",
91
+ "retrieved_at",
92
+ "status_source",
93
+ "status_confidence",
94
+ "status_note",
95
+ "version_start_date",
96
+ "version_end_date",
97
+ "publication_date",
98
+ "last_modified_date",
99
+ "historical_versions",
100
+ "article_count",
101
+ "article_rows_count",
102
+ "article_extraction_status",
103
+ "article_extraction_note",
104
+ "article_extraction_diagnostics",
105
+ "chapter_count",
106
+ "scraped_at",
107
+ "metadata",
108
+ ]
109
+ payload = {key: row.get(key) for key in keep}
110
+ payload["text"] = clean_legal_text(payload.get("text"))
111
+ return payload
112
+
113
+
114
+ def article_payload(row: dict[str, Any]) -> dict[str, Any]:
115
+ keep = [
116
+ "record_type",
117
+ "law_identifier",
118
+ "law_version_identifier",
119
+ "version_specific_identifier",
120
+ "document_identifier",
121
+ "document_version_identifier",
122
+ "article_identifier",
123
+ "article_number",
124
+ "article_heading",
125
+ "citation",
126
+ "document_citation",
127
+ "hierarchy_path",
128
+ "hierarchy_path_text",
129
+ "hierarchy_labels",
130
+ "book_label",
131
+ "title_label",
132
+ "chapter_label",
133
+ "division_label",
134
+ "paragraph_label",
135
+ "article_label",
136
+ "book_number",
137
+ "title_number",
138
+ "chapter_number",
139
+ "division_number",
140
+ "paragraph_number",
141
+ "text",
142
+ "law_status",
143
+ "is_current",
144
+ "valid_from",
145
+ "valid_to",
146
+ "effective_date",
147
+ "retrieved_at",
148
+ "status_source",
149
+ "status_confidence",
150
+ "status_note",
151
+ "version_start_date",
152
+ "version_end_date",
153
+ "scraped_at",
154
+ ]
155
+ payload = {key: row.get(key) for key in keep}
156
+ payload["text"] = clean_legal_text(payload.get("text"))
157
+ return payload
158
+
159
+
160
+ def build_rows(
161
+ raw_dir: Path | None = None,
162
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
163
+ raw_dir = raw_dir or DEFAULT_RAW_DIR
164
+ raw_laws = read_jsonl(raw_dir / "netherlands_laws_index_latest.jsonl")
165
+ raw_articles = read_jsonl(raw_dir / "netherlands_laws_articles_index_latest.jsonl")
166
+
167
+ laws: list[dict[str, Any]] = []
168
+ law_cid_by_id: dict[str, str] = {}
169
+ cid_index: list[dict[str, Any]] = []
170
+ for raw_row in raw_laws:
171
+ payload = law_payload(raw_row)
172
+ cid = cid_for_obj(payload)
173
+ payload["cid"] = cid
174
+ payload["content_address"] = f"ipfs://{cid}"
175
+ laws.append(payload)
176
+ law_id = str(payload.get("law_identifier") or payload.get("identifier") or "")
177
+ law_cid_by_id[law_id] = cid
178
+ cid_index.append(
179
+ {
180
+ "record_type": "law",
181
+ "law_identifier": law_id,
182
+ "article_identifier": None,
183
+ "cid": cid,
184
+ "content_address": f"ipfs://{cid}",
185
+ "source_url": payload.get("source_url"),
186
+ "title": payload.get("title"),
187
+ "law_status": payload.get("law_status"),
188
+ "is_current": payload.get("is_current"),
189
+ "valid_from": payload.get("valid_from"),
190
+ "valid_to": payload.get("valid_to"),
191
+ "effective_date": payload.get("effective_date"),
192
+ "retrieved_at": payload.get("retrieved_at"),
193
+ "status_source": payload.get("status_source"),
194
+ "status_confidence": payload.get("status_confidence"),
195
+ }
196
+ )
197
+
198
+ article_payloads = [article_payload(raw_row) for raw_row in raw_articles]
199
+ disambiguate_duplicate_article_identifiers(article_payloads)
200
+
201
+ articles: list[dict[str, Any]] = []
202
+ seen_article_payloads: set[str] = set()
203
+ for payload in article_payloads:
204
+ payload["law_cid"] = law_cid_by_id.get(str(payload.get("law_identifier") or ""), "")
205
+ dedupe_key = stable_row_key(payload)
206
+ if dedupe_key in seen_article_payloads:
207
+ continue
208
+ seen_article_payloads.add(dedupe_key)
209
+ cid = cid_for_obj(payload)
210
+ payload["cid"] = cid
211
+ payload["content_address"] = f"ipfs://{cid}"
212
+ articles.append(payload)
213
+ cid_index.append(
214
+ {
215
+ "record_type": "article",
216
+ "law_identifier": payload.get("law_identifier"),
217
+ "article_identifier": payload.get("article_identifier"),
218
+ "cid": cid,
219
+ "content_address": f"ipfs://{cid}",
220
+ "source_url": None,
221
+ "title": payload.get("citation"),
222
+ "law_status": payload.get("law_status"),
223
+ "is_current": payload.get("is_current"),
224
+ "valid_from": payload.get("valid_from"),
225
+ "valid_to": payload.get("valid_to"),
226
+ "effective_date": payload.get("effective_date"),
227
+ "retrieved_at": payload.get("retrieved_at"),
228
+ "status_source": payload.get("status_source"),
229
+ "status_confidence": payload.get("status_confidence"),
230
+ }
231
+ )
232
+ return laws, articles, cid_index
233
+
234
+
235
+ def write_readme(
236
+ out_dir: Path,
237
+ repo_id: str = DEFAULT_REPO_ID,
238
+ *,
239
+ run_metadata: dict[str, Any] | None = None,
240
+ record_counts: dict[str, int] | None = None,
241
+ ) -> None:
242
+ run_metadata = run_metadata or {}
243
+ record_counts = record_counts or {}
244
+ scrape_command = run_metadata.get("scrape_command") or (
245
+ "python -m ipfs_datasets_py.processors.legal_scrapers.netherlands_laws scrape "
246
+ "--use_default_seeds true --max_seed_pages <pages> --crawl_depth 1 "
247
+ "--max_documents <cap> --rate_limit_delay <delay> --resume"
248
+ )
249
+ coverage = coverage_note(run_metadata, record_counts)
250
+ scrape_date = str(run_metadata.get("scraped_at") or "unknown")
251
+ scope_note = str(run_metadata.get("corpus_scope_note") or "")
252
+ full_bwb = run_metadata.get("full_bwb_discovery") or {}
253
+ catalog_counts = run_metadata.get("catalog_coverage_counts") or {}
254
+ catalog_note = ""
255
+ if run_metadata.get("catalog_backed_run"):
256
+ catalog_note = (
257
+ f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). "
258
+ f"Catalog coverage after this run: {catalog_counts.get('complete', 'unknown')} complete of "
259
+ f"{catalog_counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) "
260
+ f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: "
261
+ f"{catalog_counts.get('remaining', 'unknown')}. Integrity validation ok: "
262
+ f"{run_metadata.get('catalog_integrity_ok', 'unknown')}."
263
+ )
264
+ readme = f"""---
265
+ pretty_name: IPFS Netherlands Laws
266
+ language:
267
+ - nl
268
+ task_categories:
269
+ - text-retrieval
270
+ - question-answering
271
+ - text-classification
272
+ tags:
273
+ - law
274
+ - legal
275
+ - legislation
276
+ - netherlands
277
+ - dutch
278
+ - ipfs
279
+ - cid
280
+ license: other
281
+ configs:
282
+ - config_name: laws
283
+ data_files:
284
+ - split: train
285
+ path: parquet/laws/*.parquet
286
+ - config_name: articles
287
+ data_files:
288
+ - split: train
289
+ path: parquet/articles/*.parquet
290
+ - config_name: cid_index
291
+ data_files:
292
+ - split: train
293
+ path: parquet/cid_index/*.parquet
294
+ ---
295
+
296
+ # IPFS Netherlands Laws
297
+
298
+ Hugging Face target: `{repo_id}`.
299
+
300
+ This dataset packages Netherlands law records with deterministic IPFS Content IDs. Each row includes a `cid` and `content_address`; article rows also include the parent `law_cid`.
301
+
302
+ {coverage}
303
+
304
+ Scrape date: {scrape_date}
305
+
306
+ Exact corpus size in this package: {record_counts.get("laws", 0)} law records, {record_counts.get("articles", 0)} article records, and {record_counts.get("cid_index", 0)} CID index rows.
307
+
308
+ Full BWB discovery inventory: {full_bwb.get("unique_laws_discovered", "unknown")} unique BWBR identifiers from {full_bwb.get("number_of_records_reported", "unknown")} official SRU record(s), with {full_bwb.get("failed_pages_count", "unknown")} failed discovery page(s).
309
+
310
+ {catalog_note}
311
+
312
+ {scope_note}
313
+
314
+ This refresh includes parser coverage improvements for older/French heading styles such as `Article I.er`,
315
+ plus run metadata diagnostics that distinguish article-producing laws, parser-missing article cases,
316
+ and genuinely unnumbered/non-article documents.
317
+
318
+ Quality audit note: this snapshot was rebuilt after parser-noise cleanup for official website UI chrome
319
+ such as relation, permanent-link, print, save, and wetstechnical-information controls. Duplicate article
320
+ identifiers caused by repeated article numbers in different hierarchy branches are disambiguated with
321
+ deterministic hierarchy/text-derived suffixes. The quality audit reports duplicate IDs/CIDs as zero,
322
+ clean status inheritance, clean hierarchy/citation reconstruction, and passing sampled CID/vector/BM25/KG
323
+ retrieval validation.
324
+
325
+ Historical/former laws are preserved. Consumers should use `law_status`, `is_current`, `valid_from`,
326
+ `valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note`
327
+ to distinguish current law from historical, repealed, superseded, or unknown-status records. These fields
328
+ are part of the content-addressed payload, so CIDs change when official status/version metadata changes.
329
+ This dataset is not legal advice and does not validate legal force beyond the official metadata parsed.
330
+
331
+ Scrape command:
332
+
333
+ ```bash
334
+ {scrape_command}
335
+ ```
336
+
337
+ Current package counts:
338
+
339
+ - Laws: {record_counts.get("laws", 0)}
340
+ - Articles: {record_counts.get("articles", 0)}
341
+ - CID index rows: {record_counts.get("cid_index", 0)}
342
+ - Unique laws discovered before any document cap: {run_metadata.get("unique_laws_discovered", "unknown")}
343
+ - Documents failed: {run_metadata.get("documents_failed", "unknown")}
344
+ - Article-producing laws: {run_metadata.get("article_producing_laws_count", "unknown")}
345
+ - Non-article-producing laws: {run_metadata.get("non_article_producing_laws_count", "unknown")}
346
+ - Current laws: {run_metadata.get("current_laws_count", "unknown")}
347
+ - Historical/repealed/superseded laws: {run_metadata.get("historical_repealed_superseded_laws_count", "unknown")}
348
+ - Unknown-status laws: {run_metadata.get("unknown_status_laws_count", "unknown")}
349
+ - Ambiguous-status laws: {run_metadata.get("ambiguous_status_laws_count", "unknown")}
350
+
351
+ Remaining limitations: this package should only be described as the full Dutch corpus when the run metadata shows uncapped official discovery and every discovered official BWBR document was parsed or explicitly logged as failed/skipped. Otherwise it is a verified shard or discovered-corpus subset.
352
+ """
353
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
354
+
355
+
356
+ def write_gitattributes(out_dir: Path) -> None:
357
+ (out_dir / ".gitattributes").write_text(
358
+ "data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text\n"
359
+ "data/**/*.json filter=lfs diff=lfs merge=lfs -text\n"
360
+ "parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text\n",
361
+ encoding="utf-8",
362
+ )
363
+
364
+
365
+ def build_manifest(
366
+ laws: list[dict[str, Any]],
367
+ articles: list[dict[str, Any]],
368
+ cid_index: list[dict[str, Any]],
369
+ out_dir: Path,
370
+ repo_id: str = DEFAULT_REPO_ID,
371
+ ) -> dict[str, Any]:
372
+ manifest: dict[str, Any] = {
373
+ "dataset_name": IPFS_DATASET_NAME,
374
+ "snapshot_date": "2026-04-11",
375
+ "repo_target": repo_id,
376
+ "upload_target": repo_id,
377
+ "jurisdiction": "Netherlands",
378
+ "language": "nl",
379
+ "cid_format": {"version": 1, "codec": "raw", "multihash": "sha2-256", "base": "base32"},
380
+ "records": {"laws": len(laws), "articles": len(articles), "cid_index": len(cid_index)},
381
+ "files": {},
382
+ }
383
+ files: list[tuple[str, int | None]] = [
384
+ ("data/laws/ipfs_netherlands_laws.jsonl", len(laws)),
385
+ ("data/articles/ipfs_netherlands_laws_articles.jsonl", len(articles)),
386
+ ("data/cid_index/ipfs_netherlands_laws_cid_index.jsonl", len(cid_index)),
387
+ ("data/metadata/netherlands_laws_run_metadata_latest.json", None),
388
+ ("parquet/laws/train-00000-of-00001.parquet", len(laws)),
389
+ ("parquet/articles/train-00000-of-00001.parquet", len(articles)),
390
+ ("parquet/cid_index/train-00000-of-00001.parquet", len(cid_index)),
391
+ ]
392
+ for rel, records in files:
393
+ manifest["files"][rel] = file_manifest_entry(out_dir / rel, records)
394
+ write_json(out_dir / "dataset_manifest.json", manifest)
395
+ return manifest
396
+
397
+
398
+ def build_ipfs_cid_package(
399
+ raw_dir: Path | None = None,
400
+ out_dir: Path | None = None,
401
+ repo_id: str = DEFAULT_REPO_ID,
402
+ ) -> Path:
403
+ raw_dir = raw_dir or DEFAULT_RAW_DIR
404
+ out_dir = out_dir or DEFAULT_OUT_DIR
405
+ laws, articles, cid_index = build_rows(raw_dir)
406
+ run_metadata = json.loads(
407
+ (raw_dir / "netherlands_laws_run_metadata_latest.json").read_text(encoding="utf-8")
408
+ )
409
+
410
+ for rel in [
411
+ "data/laws",
412
+ "data/articles",
413
+ "data/cid_index",
414
+ "data/metadata",
415
+ "parquet/laws",
416
+ "parquet/articles",
417
+ "parquet/cid_index",
418
+ ]:
419
+ (out_dir / rel).mkdir(parents=True, exist_ok=True)
420
+
421
+ write_jsonl(out_dir / "data/laws/ipfs_netherlands_laws.jsonl", laws)
422
+ write_jsonl(out_dir / "data/articles/ipfs_netherlands_laws_articles.jsonl", articles)
423
+ write_jsonl(out_dir / "data/cid_index/ipfs_netherlands_laws_cid_index.jsonl", cid_index)
424
+ write_json(out_dir / "data/metadata/netherlands_laws_run_metadata_latest.json", run_metadata)
425
+ write_parquet(out_dir / "parquet/laws/train-00000-of-00001.parquet", laws)
426
+ write_parquet(out_dir / "parquet/articles/train-00000-of-00001.parquet", articles)
427
+ write_parquet(out_dir / "parquet/cid_index/train-00000-of-00001.parquet", cid_index)
428
+
429
+ write_readme(
430
+ out_dir,
431
+ repo_id,
432
+ run_metadata=run_metadata,
433
+ record_counts={"laws": len(laws), "articles": len(articles), "cid_index": len(cid_index)},
434
+ )
435
+ write_gitattributes(out_dir)
436
+ build_manifest(laws, articles, cid_index, out_dir, repo_id)
437
+ return out_dir
438
+
439
+
440
+ def main() -> None:
441
+ out_dir = build_ipfs_cid_package()
442
+ manifest = json.loads((out_dir / "dataset_manifest.json").read_text(encoding="utf-8"))
443
+ print(json.dumps({"out_dir": str(out_dir), "records": manifest["records"]}, indent=2))
444
+
445
+
446
+ if __name__ == "__main__":
447
+ main()
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/normalized_package.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build a normalized Hugging Face package for Netherlands laws."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import Counter
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .common import (
11
+ clean_legal_text,
12
+ count_jsonl,
13
+ disambiguate_duplicate_article_identifiers,
14
+ file_manifest_entry,
15
+ read_jsonl,
16
+ stable_row_key,
17
+ write_json,
18
+ write_jsonl,
19
+ write_parquet,
20
+ )
21
+ from ..paths import (
22
+ DEFAULT_HF_REPO_IDS,
23
+ HF_DATA_DIR,
24
+ NORMALIZED_DATASET_NAME,
25
+ PACKAGE_RAW_OUTPUT_DIR,
26
+ )
27
+
28
+
29
+ DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["normalized"]
30
+ DEFAULT_RAW_DIR = PACKAGE_RAW_OUTPUT_DIR
31
+ DEFAULT_OUT_DIR = HF_DATA_DIR / NORMALIZED_DATASET_NAME
32
+
33
+
34
+ def coverage_note(run_metadata: dict[str, Any], record_counts: dict[str, int]) -> str:
35
+ max_documents = run_metadata.get("max_documents")
36
+ parsed = (
37
+ run_metadata.get("output_records_count")
38
+ or run_metadata.get("documents_parsed")
39
+ or record_counts.get("laws", 0)
40
+ )
41
+ discovered = (
42
+ run_metadata.get("total_unique_laws_discovered")
43
+ or run_metadata.get("unique_laws_discovered")
44
+ or "unknown"
45
+ )
46
+ failed = run_metadata.get("documents_failed", "unknown")
47
+ if max_documents:
48
+ return (
49
+ f"This is a capped Netherlands scrape, not the full Dutch corpus. "
50
+ f"The scrape used max_documents={max_documents}, parsed {parsed} law record(s), "
51
+ f"and discovered {discovered} unique official BWBR law document(s) before applying the cap. "
52
+ f"Documents failed: {failed}."
53
+ )
54
+ return (
55
+ "This is an uncapped discovered-corpus Netherlands scrape from the configured official discovery sources, "
56
+ "but it should not be described as the full Dutch corpus unless the run metadata confirms discovery covered "
57
+ f"the complete intended BWBR population. Parsed law records: {parsed}; discovered: {discovered}; "
58
+ f"documents failed: {failed}."
59
+ )
60
+
61
+
62
+ def measured_size(value: Any) -> int:
63
+ return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")))
64
+
65
+
66
+ def top_field_report(rows: list[dict[str, Any]], limit: int = 15) -> list[dict[str, Any]]:
67
+ field_sizes: Counter[str] = Counter()
68
+ nonnull: Counter[str] = Counter()
69
+ for row in rows:
70
+ for key, value in row.items():
71
+ if value not in (None, "", [], {}):
72
+ field_sizes[key] += measured_size(value)
73
+ nonnull[key] += 1
74
+ total = sum(field_sizes.values())
75
+ report: list[dict[str, Any]] = []
76
+ for key, size in sorted(field_sizes.items(), key=lambda kv: kv[1], reverse=True)[:limit]:
77
+ report.append(
78
+ {
79
+ "field": key,
80
+ "total_bytes": size,
81
+ "pct_of_measured_fields": round((100 * size / total), 2) if total else 0.0,
82
+ "nonnull_rows": nonnull[key],
83
+ "avg_bytes_when_present": round(size / nonnull[key], 1) if nonnull[key] else 0.0,
84
+ }
85
+ )
86
+ return report
87
+
88
+
89
+ def normalize_laws(raw_laws: list[dict[str, Any]]) -> list[dict[str, Any]]:
90
+ keep = [
91
+ "record_type",
92
+ "jurisdiction",
93
+ "jurisdiction_name",
94
+ "country",
95
+ "language",
96
+ "identifier",
97
+ "law_identifier",
98
+ "official_identifier",
99
+ "law_version_identifier",
100
+ "version_specific_identifier",
101
+ "title",
102
+ "canonical_title",
103
+ "aliases",
104
+ "text",
105
+ "source_url",
106
+ "canonical_law_url",
107
+ "canonical_document_url",
108
+ "versioned_law_url",
109
+ "information_url",
110
+ "document_type",
111
+ "citation",
112
+ "official_metadata",
113
+ "law_status",
114
+ "is_current",
115
+ "valid_from",
116
+ "valid_to",
117
+ "effective_date",
118
+ "retrieved_at",
119
+ "status_source",
120
+ "status_confidence",
121
+ "status_note",
122
+ "version_start_date",
123
+ "version_end_date",
124
+ "publication_date",
125
+ "last_modified_date",
126
+ "historical_versions",
127
+ "article_count",
128
+ "article_rows_count",
129
+ "article_extraction_status",
130
+ "article_extraction_note",
131
+ "article_extraction_diagnostics",
132
+ "chapter_count",
133
+ "scraped_at",
134
+ "metadata",
135
+ ]
136
+ rows = [{key: row.get(key) for key in keep} for row in raw_laws]
137
+ for row in rows:
138
+ row["text"] = clean_legal_text(row.get("text"))
139
+ return rows
140
+
141
+
142
+ def normalize_articles(raw_articles: list[dict[str, Any]]) -> list[dict[str, Any]]:
143
+ keep = [
144
+ "record_type",
145
+ "law_identifier",
146
+ "law_version_identifier",
147
+ "version_specific_identifier",
148
+ "document_identifier",
149
+ "document_version_identifier",
150
+ "article_identifier",
151
+ "article_number",
152
+ "article_heading",
153
+ "citation",
154
+ "document_citation",
155
+ "hierarchy_path",
156
+ "hierarchy_path_text",
157
+ "hierarchy_labels",
158
+ "book_label",
159
+ "title_label",
160
+ "chapter_label",
161
+ "division_label",
162
+ "paragraph_label",
163
+ "article_label",
164
+ "book_number",
165
+ "title_number",
166
+ "chapter_number",
167
+ "division_number",
168
+ "paragraph_number",
169
+ "text",
170
+ "law_status",
171
+ "is_current",
172
+ "valid_from",
173
+ "valid_to",
174
+ "effective_date",
175
+ "retrieved_at",
176
+ "status_source",
177
+ "status_confidence",
178
+ "status_note",
179
+ "version_start_date",
180
+ "version_end_date",
181
+ "scraped_at",
182
+ ]
183
+ rows: list[dict[str, Any]] = []
184
+ for row in raw_articles:
185
+ out = {key: row.get(key) for key in keep}
186
+ out["text"] = clean_legal_text(out.get("text"))
187
+ out["law_row_id"] = row.get("law_identifier")
188
+ rows.append(out)
189
+ disambiguate_duplicate_article_identifiers(rows)
190
+ deduplicated: list[dict[str, Any]] = []
191
+ seen: set[str] = set()
192
+ for row in rows:
193
+ key = stable_row_key(row)
194
+ if key in seen:
195
+ continue
196
+ seen.add(key)
197
+ deduplicated.append(row)
198
+ return deduplicated
199
+
200
+
201
+ def write_dataset_card(
202
+ out_dir: Path,
203
+ repo_id: str = DEFAULT_REPO_ID,
204
+ *,
205
+ run_metadata: dict[str, Any] | None = None,
206
+ record_counts: dict[str, int] | None = None,
207
+ ) -> None:
208
+ run_metadata = run_metadata or {}
209
+ record_counts = record_counts or {}
210
+ coverage = coverage_note(run_metadata, record_counts)
211
+ scrape_command = run_metadata.get("scrape_command") or (
212
+ "python -m ipfs_datasets_py.processors.legal_scrapers.netherlands_laws scrape "
213
+ "--use_default_seeds true --max_seed_pages <pages> --crawl_depth 1 "
214
+ "--max_documents <cap> --rate_limit_delay <delay> --resume"
215
+ )
216
+ scrape_date = str(run_metadata.get("scraped_at") or "unknown")
217
+ scope_note = str(run_metadata.get("corpus_scope_note") or "")
218
+ full_bwb = run_metadata.get("full_bwb_discovery") or {}
219
+ catalog_counts = run_metadata.get("catalog_coverage_counts") or {}
220
+ catalog_note = ""
221
+ if run_metadata.get("catalog_backed_run"):
222
+ catalog_note = (
223
+ f"Catalog-backed production batch: {run_metadata.get('catalog_batch_size', 'unknown')} queued BWBR identifier(s). "
224
+ f"Catalog coverage after this run: {catalog_counts.get('complete', 'unknown')} complete of "
225
+ f"{catalog_counts.get('total_discovered_identifiers', 'unknown')} discovered identifier(s) "
226
+ f"({run_metadata.get('catalog_percent_complete', 'unknown')}%). Remaining: "
227
+ f"{catalog_counts.get('remaining', 'unknown')}. Integrity validation ok: "
228
+ f"{run_metadata.get('catalog_integrity_ok', 'unknown')}."
229
+ )
230
+ readme = f"""---
231
+ pretty_name: Netherlands Laws (Dutch, Normalized)
232
+ language:
233
+ - nl
234
+ task_categories:
235
+ - text-retrieval
236
+ - question-answering
237
+ - text-classification
238
+ tags:
239
+ - law
240
+ - legal
241
+ - legislation
242
+ - netherlands
243
+ - dutch
244
+ license: other
245
+ configs:
246
+ - config_name: laws
247
+ data_files:
248
+ - split: train
249
+ path: parquet/laws/*.parquet
250
+ - config_name: articles
251
+ data_files:
252
+ - split: train
253
+ path: parquet/articles/*.parquet
254
+ ---
255
+
256
+ # Netherlands Laws (Dutch, Normalized)
257
+
258
+ Hugging Face target: `{repo_id}`.
259
+
260
+ This package is a normalized version of the Netherlands laws scrape output.
261
+
262
+ {coverage}
263
+
264
+ Scrape date: {scrape_date}
265
+
266
+ Exact corpus size in this package: {record_counts.get("laws", 0)} law records and {record_counts.get("articles", 0)} article records.
267
+
268
+ Full BWB discovery inventory: {full_bwb.get("unique_laws_discovered", "unknown")} unique BWBR identifiers from {full_bwb.get("number_of_records_reported", "unknown")} official SRU record(s), with {full_bwb.get("failed_pages_count", "unknown")} failed discovery page(s).
269
+
270
+ {catalog_note}
271
+
272
+ {scope_note}
273
+
274
+ This refresh includes parser coverage improvements for older/French heading styles such as `Article I.er`,
275
+ plus run metadata diagnostics that distinguish article-producing laws, parser-missing article cases,
276
+ and genuinely unnumbered/non-article documents.
277
+
278
+ Historical/former laws are preserved. Consumers should use `law_status`, `is_current`, `valid_from`,
279
+ `valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note`
280
+ to distinguish current law from historical, repealed, superseded, or unknown-status records. These fields
281
+ are parsed only from official Dutch government metadata/pages; `unknown` means the scraper did not find
282
+ enough official metadata to classify the status.
283
+
284
+ This dataset is not legal advice and does not validate legal force beyond the official metadata parsed.
285
+
286
+ Scrape command:
287
+
288
+ ```bash
289
+ {scrape_command}
290
+ ```
291
+
292
+ Current package counts:
293
+
294
+ - Laws: {record_counts.get("laws", 0)}
295
+ - Articles: {record_counts.get("articles", 0)}
296
+ - Search records in raw run: {run_metadata.get("search_records_count", "unknown")}
297
+ - Unique laws discovered before any document cap: {run_metadata.get("unique_laws_discovered", "unknown")}
298
+ - Documents failed: {run_metadata.get("documents_failed", "unknown")}
299
+ - Article-producing laws: {run_metadata.get("article_producing_laws_count", "unknown")}
300
+ - Non-article-producing laws: {run_metadata.get("non_article_producing_laws_count", "unknown")}
301
+ - Current laws: {run_metadata.get("current_laws_count", "unknown")}
302
+ - Historical/repealed/superseded laws: {run_metadata.get("historical_repealed_superseded_laws_count", "unknown")}
303
+ - Unknown-status laws: {run_metadata.get("unknown_status_laws_count", "unknown")}
304
+ - Ambiguous-status laws: {run_metadata.get("ambiguous_status_laws_count", "unknown")}
305
+
306
+ Remaining limitations: this package should only be described as the full Dutch corpus when the run metadata shows uncapped official discovery and every discovered official BWBR document was parsed or explicitly logged as failed/skipped. Otherwise it is a verified shard or discovered-corpus subset.
307
+ """
308
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
309
+
310
+
311
+ def write_gitattributes(out_dir: Path) -> None:
312
+ text = """data/**/*.jsonl filter=lfs diff=lfs merge=lfs -text
313
+ data/**/*.json filter=lfs diff=lfs merge=lfs -text
314
+ parquet/**/*.parquet filter=lfs diff=lfs merge=lfs -text
315
+ analysis/**/*.json filter=lfs diff=lfs merge=lfs -text
316
+ """
317
+ (out_dir / ".gitattributes").write_text(text, encoding="utf-8")
318
+
319
+
320
+ def write_upload_script(out_dir: Path) -> None:
321
+ text = """#!/usr/bin/env bash
322
+ set -euo pipefail
323
+
324
+ if [[ $# -lt 1 ]]; then
325
+ echo "Usage: $0 <namespace/dataset-name>"
326
+ exit 1
327
+ fi
328
+
329
+ REPO_ID="$1"
330
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
331
+
332
+ cat <<EOF
333
+ cd "$SCRIPT_DIR"
334
+ git init
335
+ git lfs install
336
+ git remote add origin "https://huggingface.co/datasets/$REPO_ID"
337
+ git add .
338
+ git commit -m "Add normalized Netherlands laws dataset"
339
+ git branch -M main
340
+ git push origin main
341
+ EOF
342
+ """
343
+ path = out_dir / "upload_to_hf.sh"
344
+ path.write_text(text, encoding="utf-8")
345
+ path.chmod(0o755)
346
+
347
+
348
+ def build_normalized_package(
349
+ raw_dir: Path | None = None,
350
+ out_dir: Path | None = None,
351
+ repo_id: str = DEFAULT_REPO_ID,
352
+ ) -> Path:
353
+ raw_dir = raw_dir or DEFAULT_RAW_DIR
354
+ out_dir = out_dir or DEFAULT_OUT_DIR
355
+ raw_laws = read_jsonl(raw_dir / "netherlands_laws_index_latest.jsonl")
356
+ raw_articles = read_jsonl(raw_dir / "netherlands_laws_articles_index_latest.jsonl")
357
+ raw_search_rows = count_jsonl(raw_dir / "netherlands_laws_search_index_latest.jsonl")
358
+ run_metadata = json.loads(
359
+ (raw_dir / "netherlands_laws_run_metadata_latest.json").read_text(encoding="utf-8")
360
+ )
361
+
362
+ laws = normalize_laws(raw_laws)
363
+ articles = normalize_articles(raw_articles)
364
+
365
+ (out_dir / "data" / "laws").mkdir(parents=True, exist_ok=True)
366
+ (out_dir / "data" / "articles").mkdir(parents=True, exist_ok=True)
367
+ (out_dir / "data" / "metadata").mkdir(parents=True, exist_ok=True)
368
+ (out_dir / "analysis").mkdir(parents=True, exist_ok=True)
369
+ (out_dir / "parquet" / "laws").mkdir(parents=True, exist_ok=True)
370
+ (out_dir / "parquet" / "articles").mkdir(parents=True, exist_ok=True)
371
+
372
+ laws_jsonl = out_dir / "data" / "laws" / "netherlands_laws_normalized.jsonl"
373
+ articles_jsonl = out_dir / "data" / "articles" / "netherlands_laws_articles_normalized.jsonl"
374
+
375
+ write_jsonl(laws_jsonl, laws)
376
+ write_jsonl(articles_jsonl, articles)
377
+ write_parquet(out_dir / "parquet" / "laws" / "train-00000-of-00001.parquet", laws)
378
+ write_parquet(out_dir / "parquet" / "articles" / "train-00000-of-00001.parquet", articles)
379
+
380
+ raw_article_bytes = (raw_dir / "netherlands_laws_articles_index_latest.jsonl").stat().st_size
381
+ normalized_article_bytes = articles_jsonl.stat().st_size
382
+ report = {
383
+ "raw": {
384
+ "laws_rows": len(raw_laws),
385
+ "articles_rows": len(raw_articles),
386
+ "search_rows": raw_search_rows,
387
+ "article_jsonl_bytes": raw_article_bytes,
388
+ "article_top_fields": top_field_report(raw_articles),
389
+ },
390
+ "normalized": {
391
+ "laws_rows": len(laws),
392
+ "articles_rows": len(articles),
393
+ "article_jsonl_bytes": normalized_article_bytes,
394
+ "article_reduction_bytes": raw_article_bytes - normalized_article_bytes,
395
+ "article_reduction_pct": round(
396
+ 100 * (raw_article_bytes - normalized_article_bytes) / raw_article_bytes, 2
397
+ )
398
+ if raw_article_bytes
399
+ else 0.0,
400
+ },
401
+ "scrape_trace": {
402
+ "max_documents": run_metadata.get("max_documents"),
403
+ "seed_url_count": run_metadata.get("seed_url_count"),
404
+ "seed_pages_visited": run_metadata.get("seed_pages_visited"),
405
+ "explicit_document_urls": run_metadata.get("explicit_document_urls"),
406
+ "official_law_documents_accepted": run_metadata.get("official_law_documents_accepted"),
407
+ "documents_parsed": run_metadata.get("documents_parsed"),
408
+ "records_count": run_metadata.get("records_count"),
409
+ "article_records_count": run_metadata.get("article_records_count"),
410
+ "search_records_count": run_metadata.get("search_records_count"),
411
+ "law_status_counts": run_metadata.get("law_status_counts"),
412
+ "current_laws_count": run_metadata.get("current_laws_count"),
413
+ "historical_repealed_superseded_laws_count": run_metadata.get(
414
+ "historical_repealed_superseded_laws_count"
415
+ ),
416
+ "unknown_status_laws_count": run_metadata.get("unknown_status_laws_count"),
417
+ "ambiguous_status_laws_count": run_metadata.get("ambiguous_status_laws_count"),
418
+ },
419
+ }
420
+
421
+ write_json(out_dir / "analysis" / "size_inflation_report.json", report)
422
+ write_json(
423
+ out_dir / "data" / "metadata" / "netherlands_laws_run_metadata_latest.json", run_metadata
424
+ )
425
+
426
+ manifest = {
427
+ "dataset_name": NORMALIZED_DATASET_NAME,
428
+ "snapshot_date": "2026-04-11",
429
+ "package_variant": "normalized",
430
+ "source_directory": str(raw_dir),
431
+ "source_url": "https://wetten.overheid.nl/",
432
+ "repo_target": repo_id,
433
+ "upload_target": repo_id,
434
+ "language": "nl",
435
+ "jurisdiction": "Netherlands",
436
+ "join_key": {"articles": "law_identifier", "laws": "law_identifier"},
437
+ "records": {"laws": len(laws), "articles": len(articles)},
438
+ "notes": [
439
+ "Law-level metadata is stored in the laws table.",
440
+ "Repeated law-level fields were removed from article rows.",
441
+ "Historical/former laws are preserved and labeled; they are not filtered out.",
442
+ "This dataset is not legal advice and does not validate legal force beyond parsed official metadata.",
443
+ ],
444
+ "files": {},
445
+ }
446
+ for rel in [
447
+ "data/laws/netherlands_laws_normalized.jsonl",
448
+ "data/articles/netherlands_laws_articles_normalized.jsonl",
449
+ "data/metadata/netherlands_laws_run_metadata_latest.json",
450
+ "analysis/size_inflation_report.json",
451
+ "parquet/laws/train-00000-of-00001.parquet",
452
+ "parquet/articles/train-00000-of-00001.parquet",
453
+ ]:
454
+ path = out_dir / rel
455
+ records: int | None = None
456
+ if rel.startswith("data/laws") or rel.startswith("parquet/laws"):
457
+ records = len(laws)
458
+ elif rel.startswith("data/articles") or rel.startswith("parquet/articles"):
459
+ records = len(articles)
460
+ manifest["files"][rel] = file_manifest_entry(path, records)
461
+ write_json(out_dir / "dataset_manifest.json", manifest)
462
+
463
+ write_dataset_card(
464
+ out_dir,
465
+ repo_id,
466
+ run_metadata=run_metadata,
467
+ record_counts={"laws": len(laws), "articles": len(articles)},
468
+ )
469
+ write_gitattributes(out_dir)
470
+ write_upload_script(out_dir)
471
+ return out_dir
472
+
473
+
474
+ def main() -> None:
475
+ out_dir = build_normalized_package()
476
+ report = json.loads(
477
+ (out_dir / "analysis" / "size_inflation_report.json").read_text(encoding="utf-8")
478
+ )
479
+ print(json.dumps(report, indent=2, ensure_ascii=False))
480
+
481
+
482
+ if __name__ == "__main__":
483
+ main()
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/netherlands_laws/builders/unified_package.py ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the unified WetWijzer Netherlands legal corpus bundle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shutil
8
+ import tempfile
9
+ from collections import defaultdict
10
+ from datetime import UTC, datetime
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import pyarrow.parquet as pq
15
+
16
+ from ipfs_datasets_py.utils.cid_utils import cid_for_obj
17
+
18
+ from .common import file_manifest_entry, write_json, write_jsonl, write_parquet
19
+ from ..paths import (
20
+ BM25_INDEX_DATASET_NAME,
21
+ DEFAULT_HF_REPO_IDS,
22
+ DATASETS_DIR,
23
+ HF_DATA_DIR,
24
+ IPFS_DATASET_NAME,
25
+ KNOWLEDGE_GRAPH_DATASET_NAME,
26
+ OPERATIONS_DATA_DIR,
27
+ UNIFIED_WETWIJZER_DATASET_NAME,
28
+ VECTOR_INDEX_DATASET_NAME,
29
+ )
30
+
31
+
32
+ DEFAULT_REPO_ID = DEFAULT_HF_REPO_IDS["unified"]
33
+ DEFAULT_BASE_DIR = HF_DATA_DIR / IPFS_DATASET_NAME
34
+ DEFAULT_VECTOR_DIR = HF_DATA_DIR / VECTOR_INDEX_DATASET_NAME
35
+ DEFAULT_BM25_DIR = HF_DATA_DIR / BM25_INDEX_DATASET_NAME
36
+ DEFAULT_KG_DIR = HF_DATA_DIR / KNOWLEDGE_GRAPH_DATASET_NAME
37
+ DEFAULT_REPORTS_DIR = OPERATIONS_DATA_DIR
38
+ DEFAULT_OUT_DIR = HF_DATA_DIR / UNIFIED_WETWIJZER_DATASET_NAME
39
+ DATASET_VIEWER_ROW_GROUP_SIZE = 10_000
40
+
41
+ ARTICLE_REFERENCE_RE = re.compile(r"\b(?:Artikel|Article)\s+([0-9]+[a-zA-Z]?)\b")
42
+
43
+
44
+ def build_unified_wetwijzer_package(
45
+ *,
46
+ base_dir: Path | None = None,
47
+ vector_dir: Path | None = None,
48
+ bm25_dir: Path | None = None,
49
+ kg_dir: Path | None = None,
50
+ reports_dir: Path | None = None,
51
+ out_dir: Path | None = None,
52
+ repo_id: str = DEFAULT_REPO_ID,
53
+ include_relationship_summaries: bool = True,
54
+ ) -> Path:
55
+ """Create a single HF-ready bundle from the existing quality-audited outputs."""
56
+
57
+ base_dir = base_dir or DEFAULT_BASE_DIR
58
+ vector_dir = vector_dir or DEFAULT_VECTOR_DIR
59
+ bm25_dir = bm25_dir or DEFAULT_BM25_DIR
60
+ kg_dir = kg_dir or DEFAULT_KG_DIR
61
+ reports_dir = reports_dir or DEFAULT_REPORTS_DIR
62
+ out_dir = out_dir or DEFAULT_OUT_DIR
63
+
64
+ _reset_output_dir(out_dir)
65
+
66
+ copied = _copy_package_layers(
67
+ out_dir=out_dir,
68
+ base_dir=base_dir,
69
+ vector_dir=vector_dir,
70
+ bm25_dir=bm25_dir,
71
+ kg_dir=kg_dir,
72
+ reports_dir=reports_dir,
73
+ )
74
+ if include_relationship_summaries:
75
+ _write_logic_relationship_summaries(out_dir)
76
+
77
+ _write_source_manifests(out_dir, base_dir, vector_dir, bm25_dir, kg_dir)
78
+ manifest = _write_unified_manifest(out_dir, repo_id, copied)
79
+ _write_readme(out_dir, repo_id, manifest)
80
+ _write_gitattributes(out_dir)
81
+ return out_dir
82
+
83
+
84
+ def _reset_output_dir(out_dir: Path) -> None:
85
+ _ensure_safe_output_dir(out_dir)
86
+ if out_dir.exists():
87
+ shutil.rmtree(out_dir)
88
+ out_dir.mkdir(parents=True, exist_ok=True)
89
+
90
+
91
+ def _ensure_safe_output_dir(out_dir: Path) -> None:
92
+ resolved = out_dir.resolve()
93
+ safe_roots = [DATASETS_DIR.resolve(), Path(tempfile.gettempdir()).resolve()]
94
+ if resolved in safe_roots or not any(resolved.is_relative_to(root) for root in safe_roots):
95
+ roots = ", ".join(str(root) for root in safe_roots)
96
+ raise ValueError(
97
+ f"Refusing to reset unsafe unified package output directory: {resolved}. "
98
+ f"Use a child directory under one of: {roots}"
99
+ )
100
+
101
+
102
+ def _copy_package_layers(
103
+ *,
104
+ out_dir: Path,
105
+ base_dir: Path,
106
+ vector_dir: Path,
107
+ bm25_dir: Path,
108
+ kg_dir: Path,
109
+ reports_dir: Path,
110
+ ) -> dict[str, str]:
111
+ copies = {
112
+ "data/laws.parquet": base_dir / "parquet/laws/train-00000-of-00001.parquet",
113
+ "data/articles.parquet": base_dir / "parquet/articles/train-00000-of-00001.parquet",
114
+ "data/cid_index.parquet": base_dir / "parquet/cid_index/train-00000-of-00001.parquet",
115
+ "indexes/vector/vector_mapping.parquet": vector_dir
116
+ / "parquet/mapping/train-00000-of-00001.parquet",
117
+ "indexes/vector/faiss.index": vector_dir / "artifacts/faiss.index",
118
+ "indexes/vector/vectorizer.pkl": vector_dir / "artifacts/vectorizer.pkl",
119
+ "indexes/vector/svd.pkl": vector_dir / "artifacts/svd.pkl",
120
+ "indexes/vector/metadata.json": vector_dir / "artifacts/metadata.json",
121
+ "indexes/bm25/bm25_documents.parquet": bm25_dir
122
+ / "parquet/documents/train-00000-of-00001.parquet",
123
+ "indexes/bm25/bm25_terms.parquet": bm25_dir / "parquet/terms/train-00000-of-00001.parquet",
124
+ "indexes/bm25/metadata.json": bm25_dir / "artifacts/metadata.json",
125
+ "graph/kg_nodes.parquet": kg_dir / "parquet/nodes/train-00000-of-00001.parquet",
126
+ "graph/kg_edges.parquet": kg_dir / "parquet/edges/train-00000-of-00001.parquet",
127
+ "graph/graph.jsonld": kg_dir / "data/graph/ipfs_netherlands_laws_kg.jsonld",
128
+ "graph/metadata.json": kg_dir / "artifacts/metadata.json",
129
+ "reports/run_metadata.json": base_dir
130
+ / "data/metadata/netherlands_laws_run_metadata_latest.json",
131
+ }
132
+
133
+ report_paths = _select_reports(reports_dir)
134
+ copies.update(report_paths)
135
+
136
+ copied: dict[str, str] = {}
137
+ for rel, source in copies.items():
138
+ if not source.exists():
139
+ raise FileNotFoundError(
140
+ f"Cannot build unified package; missing source file for {rel}: {source}"
141
+ )
142
+ destination = out_dir / rel
143
+ destination.parent.mkdir(parents=True, exist_ok=True)
144
+ shutil.copy2(source, destination)
145
+ copied[rel] = str(source)
146
+ _rewrite_viewer_friendly_parquet(out_dir / "indexes/bm25/bm25_terms.parquet")
147
+ return copied
148
+
149
+
150
+ def _rewrite_viewer_friendly_parquet(path: Path) -> None:
151
+ """Rewrite large copied parquet files with row groups small enough for Dataset Viewer."""
152
+
153
+ table = pq.read_table(path)
154
+ pq.write_table(
155
+ table,
156
+ path,
157
+ compression="zstd",
158
+ row_group_size=DATASET_VIEWER_ROW_GROUP_SIZE,
159
+ write_page_index=True,
160
+ )
161
+
162
+
163
+ def _select_reports(reports_dir: Path) -> dict[str, Path]:
164
+ quality_dir = reports_dir / "quality_audit"
165
+ return {
166
+ "reports/coverage_report.json": _first_existing_or_latest(
167
+ reports_dir,
168
+ [
169
+ "coverage_report_quality_audit_after_verify_*.json",
170
+ "coverage_report_catalog_batch_5000_after_verify_*.json",
171
+ "coverage_report_latest.json",
172
+ "coverage_report*.json",
173
+ ],
174
+ ),
175
+ "reports/integrity_report.json": _first_existing_or_latest(
176
+ reports_dir,
177
+ [
178
+ "integrity_report_quality_audit_final_*.json",
179
+ "integrity_report_catalog_batch_5000_after_verify_*.json",
180
+ "integrity_report*.json",
181
+ ],
182
+ ),
183
+ "reports/quality_report.json": quality_dir / "quality_report.json",
184
+ "reports/duplicate_report.json": quality_dir / "duplicate_report.json",
185
+ "reports/parser_noise_report.json": quality_dir / "parser_noise_report.json",
186
+ "reports/hierarchy_report.json": quality_dir / "hierarchy_report.json",
187
+ "reports/retrieval_validation_report.json": quality_dir
188
+ / "retrieval_validation_report.json",
189
+ }
190
+
191
+
192
+ def _first_existing_or_latest(directory: Path, patterns: list[str]) -> Path:
193
+ for pattern in patterns:
194
+ matches = sorted(
195
+ directory.glob(pattern), key=lambda path: path.stat().st_mtime, reverse=True
196
+ )
197
+ if matches:
198
+ return matches[0]
199
+ raise FileNotFoundError(f"No report matched any of {patterns} in {directory}")
200
+
201
+
202
+ def _write_source_manifests(
203
+ out_dir: Path, base_dir: Path, vector_dir: Path, bm25_dir: Path, kg_dir: Path
204
+ ) -> None:
205
+ sources = {
206
+ "ipfs_netherlands_laws_manifest.json": base_dir / "dataset_manifest.json",
207
+ "ipfs_netherlands_laws_vector_index_manifest.json": vector_dir / "dataset_manifest.json",
208
+ "ipfs_netherlands_laws_bm25_index_manifest.json": bm25_dir / "dataset_manifest.json",
209
+ "ipfs_netherlands_laws_knowledge_graph_manifest.json": kg_dir / "dataset_manifest.json",
210
+ }
211
+ for filename, source in sources.items():
212
+ if not source.exists():
213
+ raise FileNotFoundError(f"Missing source manifest: {source}")
214
+ destination = out_dir / "manifests" / filename
215
+ destination.parent.mkdir(parents=True, exist_ok=True)
216
+ shutil.copy2(source, destination)
217
+
218
+
219
+ def _write_logic_relationship_summaries(out_dir: Path) -> list[dict[str, Any]]:
220
+ articles_path = out_dir / "data/articles.parquet"
221
+ laws_path = out_dir / "data/laws.parquet"
222
+
223
+ law_rows = _read_parquet_rows(
224
+ laws_path,
225
+ ["cid", "law_identifier", "title", "citation", "source_url", "law_status", "is_current"],
226
+ )
227
+ law_by_id = {str(row.get("law_identifier") or ""): row for row in law_rows}
228
+
229
+ article_rows = _read_parquet_rows(
230
+ articles_path,
231
+ [
232
+ "cid",
233
+ "law_cid",
234
+ "law_identifier",
235
+ "article_identifier",
236
+ "article_number",
237
+ "citation",
238
+ "document_citation",
239
+ "text",
240
+ "law_status",
241
+ "is_current",
242
+ "valid_from",
243
+ "valid_to",
244
+ "source_url",
245
+ ],
246
+ )
247
+
248
+ by_law: dict[str, list[dict[str, Any]]] = defaultdict(list)
249
+ article_by_number: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
250
+ for row in article_rows:
251
+ law_identifier = str(row.get("law_identifier") or "")
252
+ by_law[law_identifier].append(row)
253
+ article_number = _normalize_article_number(row.get("article_number"))
254
+ if article_number and article_number not in article_by_number[law_identifier]:
255
+ article_by_number[law_identifier][article_number] = row
256
+
257
+ relationships: list[dict[str, Any]] = []
258
+ seen: set[tuple[str, str, str]] = set()
259
+
260
+ for law_identifier, articles in by_law.items():
261
+ law = law_by_id.get(law_identifier) or {}
262
+ law_cid = str(law.get("cid") or articles[0].get("law_cid") or "")
263
+ for index, article in enumerate(articles):
264
+ _append_relationship(
265
+ relationships,
266
+ seen,
267
+ relationship_type="parent_law",
268
+ source=article,
269
+ target_cid=law_cid,
270
+ target_record_type="law",
271
+ target_label=str(law.get("title") or law.get("citation") or law_identifier),
272
+ target_identifier=law_identifier,
273
+ note="Parent law relationship derived from article law_cid.",
274
+ )
275
+ if index > 0:
276
+ previous = articles[index - 1]
277
+ _append_relationship(
278
+ relationships,
279
+ seen,
280
+ relationship_type="previous_article",
281
+ source=article,
282
+ target_cid=str(previous.get("cid") or ""),
283
+ target_record_type="article",
284
+ target_label=str(
285
+ previous.get("citation") or previous.get("article_identifier") or ""
286
+ ),
287
+ target_identifier=str(previous.get("article_identifier") or ""),
288
+ note="Previous article relationship derived from source article ordering within the same law.",
289
+ )
290
+ if index + 1 < len(articles):
291
+ following = articles[index + 1]
292
+ _append_relationship(
293
+ relationships,
294
+ seen,
295
+ relationship_type="next_article",
296
+ source=article,
297
+ target_cid=str(following.get("cid") or ""),
298
+ target_record_type="article",
299
+ target_label=str(
300
+ following.get("citation") or following.get("article_identifier") or ""
301
+ ),
302
+ target_identifier=str(following.get("article_identifier") or ""),
303
+ note="Next article relationship derived from source article ordering within the same law.",
304
+ )
305
+
306
+ for target in _referenced_article_targets(article, article_by_number[law_identifier]):
307
+ _append_relationship(
308
+ relationships,
309
+ seen,
310
+ relationship_type="referenced_article_candidate",
311
+ source=article,
312
+ target_cid=str(target.get("cid") or ""),
313
+ target_record_type="article",
314
+ target_label=str(
315
+ target.get("citation") or target.get("article_identifier") or ""
316
+ ),
317
+ target_identifier=str(target.get("article_identifier") or ""),
318
+ confidence="low",
319
+ note="Candidate same-law article reference derived from article text mention.",
320
+ )
321
+
322
+ write_parquet(out_dir / "logic/logic_relationships.parquet", relationships)
323
+ write_jsonl(out_dir / "logic/logic_relationships.jsonl", relationships)
324
+ return relationships
325
+
326
+
327
+ def _read_parquet_rows(path: Path, columns: list[str]) -> list[dict[str, Any]]:
328
+ parquet = pq.ParquetFile(path)
329
+ available = [column for column in columns if column in parquet.schema_arrow.names]
330
+ if not available:
331
+ return []
332
+ return parquet.read(columns=available).to_pylist()
333
+
334
+
335
+ def _normalize_article_number(value: Any) -> str:
336
+ return str(value or "").strip().lower().rstrip(".")
337
+
338
+
339
+ def _referenced_article_targets(
340
+ source: dict[str, Any],
341
+ article_by_number: dict[str, dict[str, Any]],
342
+ *,
343
+ limit: int = 20,
344
+ ) -> list[dict[str, Any]]:
345
+ text = str(source.get("text") or "")
346
+ if not text:
347
+ return []
348
+ source_cid = str(source.get("cid") or "")
349
+ targets: list[dict[str, Any]] = []
350
+ seen: set[str] = set()
351
+ for match in ARTICLE_REFERENCE_RE.finditer(text):
352
+ target = article_by_number.get(_normalize_article_number(match.group(1)))
353
+ target_cid = str((target or {}).get("cid") or "")
354
+ if not target or not target_cid or target_cid == source_cid or target_cid in seen:
355
+ continue
356
+ seen.add(target_cid)
357
+ targets.append(target)
358
+ if len(targets) >= limit:
359
+ break
360
+ return targets
361
+
362
+
363
+ def _append_relationship(
364
+ rows: list[dict[str, Any]],
365
+ seen: set[tuple[str, str, str]],
366
+ *,
367
+ relationship_type: str,
368
+ source: dict[str, Any],
369
+ target_cid: str,
370
+ target_record_type: str,
371
+ target_label: str,
372
+ target_identifier: str,
373
+ confidence: str = "high",
374
+ note: str,
375
+ ) -> None:
376
+ source_cid = str(source.get("cid") or "")
377
+ target_cid = str(target_cid or "")
378
+ if not source_cid or not target_cid:
379
+ return
380
+ key = (relationship_type, source_cid, target_cid)
381
+ if key in seen:
382
+ return
383
+ seen.add(key)
384
+ row = {
385
+ "relationship_type": relationship_type,
386
+ "source_cid": source_cid,
387
+ "target_cid": target_cid,
388
+ "source_record_type": "article",
389
+ "target_record_type": target_record_type,
390
+ "law_cid": source.get("law_cid"),
391
+ "law_identifier": source.get("law_identifier"),
392
+ "source_identifier": source.get("article_identifier"),
393
+ "target_identifier": target_identifier,
394
+ "source_label": source.get("citation") or source.get("article_identifier"),
395
+ "target_label": target_label,
396
+ "source_law_status": source.get("law_status"),
397
+ "source_is_current": source.get("is_current"),
398
+ "source_valid_from": source.get("valid_from"),
399
+ "source_valid_to": source.get("valid_to"),
400
+ "source_url": source.get("source_url"),
401
+ "status": "derived",
402
+ "confidence": confidence,
403
+ "derivation_note": note,
404
+ }
405
+ row["relationship_cid"] = cid_for_obj(row)
406
+ rows.append(row)
407
+
408
+
409
+ def _write_unified_manifest(
410
+ out_dir: Path, repo_id: str, copied_sources: dict[str, str]
411
+ ) -> dict[str, Any]:
412
+ records = _record_counts(out_dir)
413
+ source_manifests = _load_source_manifests(out_dir)
414
+ coverage = _read_json(out_dir / "reports/coverage_report.json")
415
+ quality = _read_json(out_dir / "reports/quality_report.json")
416
+ integrity = _read_json(out_dir / "reports/integrity_report.json")
417
+ run_metadata = _read_json(out_dir / "reports/run_metadata.json")
418
+
419
+ manifest: dict[str, Any] = {
420
+ "dataset_name": UNIFIED_WETWIJZER_DATASET_NAME,
421
+ "repo_target": repo_id,
422
+ "upload_target": repo_id,
423
+ "jurisdiction": "Netherlands",
424
+ "language": "nl",
425
+ "build_date": datetime.now(UTC).isoformat(),
426
+ "source_repos": {
427
+ "base": DEFAULT_HF_REPO_IDS["base"],
428
+ "vector": DEFAULT_HF_REPO_IDS["vector"],
429
+ "bm25": DEFAULT_HF_REPO_IDS["bm25"],
430
+ "knowledge_graph": DEFAULT_HF_REPO_IDS["knowledge-graph"],
431
+ },
432
+ "records": records,
433
+ "coverage": {
434
+ "counts": coverage.get("counts"),
435
+ "percent_complete": coverage.get("percent_complete"),
436
+ "completion_semantics": coverage.get("completion_semantics"),
437
+ "law_status_counts": coverage.get("law_status_counts")
438
+ or run_metadata.get("law_status_counts"),
439
+ "article_extraction_status_counts": coverage.get("article_extraction_status_counts"),
440
+ },
441
+ "quality_audit": {
442
+ "generated_at": quality.get("generated_at"),
443
+ "records": quality.get("records"),
444
+ "issue_summary": quality.get("issue_summary"),
445
+ "current_gate_pass": (quality.get("quality_gate_recommendation") or {}).get(
446
+ "current_gate_pass"
447
+ ),
448
+ },
449
+ "integrity": {
450
+ "generated_at": integrity.get("generated_at"),
451
+ "ok": integrity.get("ok"),
452
+ "issue_counts": integrity.get("issue_counts"),
453
+ },
454
+ "not_full_corpus_warning": (
455
+ "This is a quality-audited partial Dutch corpus package. Do not claim full Dutch corpus coverage "
456
+ "until every discovered BWBR identifier is parsed, intentionally skipped, or permanently failed "
457
+ "with explanation."
458
+ ),
459
+ "source_local_files": copied_sources,
460
+ "source_manifest_records": {
461
+ name: manifest_data.get("records", {})
462
+ for name, manifest_data in source_manifests.items()
463
+ },
464
+ "sample_cids": _sample_cids(out_dir),
465
+ "files": {},
466
+ }
467
+
468
+ for path in sorted(
469
+ p for p in out_dir.rglob("*") if p.is_file() and p.name != "dataset_manifest.json"
470
+ ):
471
+ rel = path.relative_to(out_dir).as_posix()
472
+ manifest["files"][rel] = file_manifest_entry(path, _records_for_file(rel, records))
473
+
474
+ write_json(out_dir / "dataset_manifest.json", manifest)
475
+ return manifest
476
+
477
+
478
+ def _record_counts(out_dir: Path) -> dict[str, int]:
479
+ counts = {
480
+ "laws": _parquet_count(out_dir / "data/laws.parquet"),
481
+ "articles": _parquet_count(out_dir / "data/articles.parquet"),
482
+ "cid_index": _parquet_count(out_dir / "data/cid_index.parquet"),
483
+ "vector_index": _parquet_count(out_dir / "indexes/vector/vector_mapping.parquet"),
484
+ "bm25_documents": _parquet_count(out_dir / "indexes/bm25/bm25_documents.parquet"),
485
+ "bm25_terms": _parquet_count(out_dir / "indexes/bm25/bm25_terms.parquet"),
486
+ "knowledge_graph_nodes": _parquet_count(out_dir / "graph/kg_nodes.parquet"),
487
+ "knowledge_graph_edges": _parquet_count(out_dir / "graph/kg_edges.parquet"),
488
+ }
489
+ logic_path = out_dir / "logic/logic_relationships.parquet"
490
+ if logic_path.exists():
491
+ counts["logic_relationships"] = _parquet_count(logic_path)
492
+ return counts
493
+
494
+
495
+ def _parquet_count(path: Path) -> int:
496
+ return int(pq.ParquetFile(path).metadata.num_rows)
497
+
498
+
499
+ def _records_for_file(rel: str, records: dict[str, int]) -> int | None:
500
+ mapping = {
501
+ "data/laws.parquet": "laws",
502
+ "data/articles.parquet": "articles",
503
+ "data/cid_index.parquet": "cid_index",
504
+ "indexes/vector/vector_mapping.parquet": "vector_index",
505
+ "indexes/bm25/bm25_documents.parquet": "bm25_documents",
506
+ "indexes/bm25/bm25_terms.parquet": "bm25_terms",
507
+ "graph/kg_nodes.parquet": "knowledge_graph_nodes",
508
+ "graph/kg_edges.parquet": "knowledge_graph_edges",
509
+ "logic/logic_relationships.parquet": "logic_relationships",
510
+ "logic/logic_relationships.jsonl": "logic_relationships",
511
+ }
512
+ key = mapping.get(rel)
513
+ return records.get(key) if key else None
514
+
515
+
516
+ def _load_source_manifests(out_dir: Path) -> dict[str, dict[str, Any]]:
517
+ manifests: dict[str, dict[str, Any]] = {}
518
+ for path in sorted((out_dir / "manifests").glob("*.json")):
519
+ manifests[path.stem] = _read_json(path)
520
+ return manifests
521
+
522
+
523
+ def _read_json(path: Path) -> dict[str, Any]:
524
+ return json.loads(path.read_text(encoding="utf-8"))
525
+
526
+
527
+ def _sample_cids(out_dir: Path) -> dict[str, str | None]:
528
+ samples: dict[str, str | None] = {}
529
+ for name, path, column in [
530
+ ("law", out_dir / "data/laws.parquet", "cid"),
531
+ ("article", out_dir / "data/articles.parquet", "cid"),
532
+ ("cid_index", out_dir / "data/cid_index.parquet", "cid"),
533
+ ("vector", out_dir / "indexes/vector/vector_mapping.parquet", "source_cid"),
534
+ ("bm25_document", out_dir / "indexes/bm25/bm25_documents.parquet", "source_cid"),
535
+ ("knowledge_graph_node", out_dir / "graph/kg_nodes.parquet", "cid"),
536
+ ("knowledge_graph_edge_source", out_dir / "graph/kg_edges.parquet", "source_cid"),
537
+ ("logic_relationship_source", out_dir / "logic/logic_relationships.parquet", "source_cid"),
538
+ ]:
539
+ if not path.exists():
540
+ samples[name] = None
541
+ continue
542
+ parquet = pq.ParquetFile(path)
543
+ if parquet.metadata.num_rows == 0 or column not in parquet.schema_arrow.names:
544
+ samples[name] = None
545
+ continue
546
+ samples[name] = str(parquet.read_row_group(0, columns=[column]).column(0)[0].as_py() or "")
547
+ return samples
548
+
549
+
550
+ def _write_readme(out_dir: Path, repo_id: str, manifest: dict[str, Any]) -> None:
551
+ records = manifest["records"]
552
+ coverage_counts = (manifest.get("coverage") or {}).get("counts") or {}
553
+ integrity = manifest.get("integrity") or {}
554
+ quality = manifest.get("quality_audit") or {}
555
+ readme = f"""---
556
+ pretty_name: WetWijzer Netherlands Legal Corpus
557
+ language:
558
+ - nl
559
+ task_categories:
560
+ - text-retrieval
561
+ - question-answering
562
+ - text-classification
563
+ tags:
564
+ - law
565
+ - legal
566
+ - legislation
567
+ - netherlands
568
+ - dutch
569
+ - ipfs
570
+ - cid
571
+ - bm25
572
+ - vector-search
573
+ - knowledge-graph
574
+ license: other
575
+ configs:
576
+ - config_name: laws
577
+ data_files:
578
+ - split: train
579
+ path: data/laws.parquet
580
+ - config_name: articles
581
+ data_files:
582
+ - split: train
583
+ path: data/articles.parquet
584
+ - config_name: cid_index
585
+ data_files:
586
+ - split: train
587
+ path: data/cid_index.parquet
588
+ - config_name: vector_index
589
+ data_files:
590
+ - split: train
591
+ path: indexes/vector/vector_mapping.parquet
592
+ - config_name: bm25_documents
593
+ data_files:
594
+ - split: train
595
+ path: indexes/bm25/bm25_documents.parquet
596
+ - config_name: bm25_terms
597
+ data_files:
598
+ - split: train
599
+ path: indexes/bm25/bm25_terms.parquet
600
+ - config_name: knowledge_graph_nodes
601
+ data_files:
602
+ - split: train
603
+ path: graph/kg_nodes.parquet
604
+ - config_name: knowledge_graph_edges
605
+ data_files:
606
+ - split: train
607
+ path: graph/kg_edges.parquet
608
+ - config_name: logic_relationships
609
+ data_files:
610
+ - split: train
611
+ path: logic/logic_relationships.parquet
612
+ ---
613
+
614
+ # WetWijzer Netherlands Legal Corpus
615
+
616
+ Hugging Face target: `{repo_id}`.
617
+
618
+ This unified dataset bundles the quality-audited WetWijzer Netherlands legal corpus stack in one repository for frontend retrieval. It preserves the existing compatibility repositories and does not replace or delete them.
619
+
620
+ ## Contents
621
+
622
+ - Laws: {records.get("laws", 0):,}
623
+ - Articles: {records.get("articles", 0):,}
624
+ - CID index rows: {records.get("cid_index", 0):,}
625
+ - Vector mapping rows: {records.get("vector_index", 0):,}
626
+ - BM25 document rows: {records.get("bm25_documents", 0):,}
627
+ - BM25 term rows: {records.get("bm25_terms", 0):,}
628
+ - Knowledge graph nodes: {records.get("knowledge_graph_nodes", 0):,}
629
+ - Knowledge graph edges: {records.get("knowledge_graph_edges", 0):,}
630
+ - Logic/relationship summary rows: {records.get("logic_relationships", 0):,}
631
+
632
+ ## Layout
633
+
634
+ - `data/laws.parquet`
635
+ - `data/articles.parquet`
636
+ - `data/cid_index.parquet`
637
+ - `indexes/vector/vector_mapping.parquet`
638
+ - `indexes/vector/faiss.index`
639
+ - `indexes/bm25/bm25_documents.parquet`
640
+ - `indexes/bm25/bm25_terms.parquet`
641
+ - `graph/kg_nodes.parquet`
642
+ - `graph/kg_edges.parquet`
643
+ - `graph/graph.jsonld`
644
+ - `logic/logic_relationships.parquet`
645
+ - `reports/*.json`
646
+ - `manifests/*.json`
647
+ - `dataset_manifest.json`
648
+
649
+ Every retrieval layer is joinable by CID. Law rows have `cid`; article rows have `cid` and `law_cid`; vector and BM25 rows use `source_cid`; graph nodes use `cid`; graph edges and relationship summaries use `source_cid`, `target_cid`, and a relationship type.
650
+
651
+ ## Source Repositories
652
+
653
+ - `{DEFAULT_HF_REPO_IDS["base"]}`
654
+ - `{DEFAULT_HF_REPO_IDS["vector"]}`
655
+ - `{DEFAULT_HF_REPO_IDS["bm25"]}`
656
+ - `{DEFAULT_HF_REPO_IDS["knowledge-graph"]}`
657
+
658
+ ## Coverage And Quality
659
+
660
+ This is a quality-audited partial Dutch corpus package, not a full Dutch corpus claim.
661
+
662
+ Completed catalog coverage: {coverage_counts.get("complete", "unknown")} of {coverage_counts.get("total_discovered_identifiers", "unknown")} discovered BWBR identifiers ({(manifest.get("coverage") or {}).get("percent_complete", "unknown")}%). Remaining identifiers: {coverage_counts.get("remaining", "unknown")}.
663
+
664
+ Integrity validation ok: {integrity.get("ok", "unknown")}. Quality gate passed: {quality.get("current_gate_pass", "unknown")}.
665
+
666
+ Historical and inactive laws are preserved. Use `law_status`, `is_current`, `valid_from`, `valid_to`, `effective_date`, `retrieved_at`, `status_source`, `status_confidence`, and `status_note` to distinguish current, historical, repealed, superseded, and unknown-status records.
667
+
668
+ This dataset is not legal advice. Users should verify official text and legal effect on `wetten.overheid.nl`.
669
+ """
670
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
671
+
672
+
673
+ def _write_gitattributes(out_dir: Path) -> None:
674
+ (out_dir / ".gitattributes").write_text(
675
+ "*.parquet filter=lfs diff=lfs merge=lfs -text\n"
676
+ "*.index filter=lfs diff=lfs merge=lfs -text\n"
677
+ "*.pkl filter=lfs diff=lfs merge=lfs -text\n"
678
+ "*.jsonld filter=lfs diff=lfs merge=lfs -text\n"
679
+ "logic/*.jsonl filter=lfs diff=lfs merge=lfs -text\n",
680
+ encoding="utf-8",
681
+ )
682
+
683
+
684
+ def load_parquet_head(
685
+ path: Path, *, columns: list[str] | None = None, limit: int = 5
686
+ ) -> list[dict[str, Any]]:
687
+ """Small verification helper for local/remote downloaded Parquet files."""
688
+
689
+ parquet = pq.ParquetFile(path)
690
+ read_columns = columns or parquet.schema_arrow.names
691
+ if parquet.metadata.num_rows == 0:
692
+ return []
693
+ table = parquet.read_row_group(
694
+ 0, columns=[column for column in read_columns if column in parquet.schema_arrow.names]
695
+ )
696
+ return table.slice(0, limit).to_pylist()
697
+
698
+
699
+ def validate_unified_package(out_dir: Path | None = None) -> dict[str, Any]:
700
+ """Validate local unified bundle joins without downloading or scraping anything."""
701
+
702
+ out_dir = out_dir or DEFAULT_OUT_DIR
703
+ required = [
704
+ "dataset_manifest.json",
705
+ "data/laws.parquet",
706
+ "data/articles.parquet",
707
+ "data/cid_index.parquet",
708
+ "indexes/vector/vector_mapping.parquet",
709
+ "indexes/bm25/bm25_documents.parquet",
710
+ "indexes/bm25/bm25_terms.parquet",
711
+ "graph/kg_nodes.parquet",
712
+ "graph/kg_edges.parquet",
713
+ "logic/logic_relationships.parquet",
714
+ ]
715
+ missing = [rel for rel in required if not (out_dir / rel).exists()]
716
+ sample = _sample_cids(out_dir)
717
+ messages = [f"Missing required file: {rel}" for rel in missing]
718
+ if "logic/logic_relationships.parquet" in missing:
719
+ messages.append(
720
+ "Relationship summaries are required for unified package validation; "
721
+ "rebuild with include_relationship_summaries=True before upload."
722
+ )
723
+
724
+ manifest = (
725
+ _read_json(out_dir / "dataset_manifest.json")
726
+ if "dataset_manifest.json" not in missing
727
+ else {}
728
+ )
729
+ article_rows = (
730
+ []
731
+ if "data/articles.parquet" in missing
732
+ else load_parquet_head(
733
+ out_dir / "data/articles.parquet",
734
+ columns=["cid", "law_cid"],
735
+ limit=1,
736
+ )
737
+ )
738
+ if not article_rows and "data/articles.parquet" not in missing:
739
+ messages.append("Required parquet has no article rows: data/articles.parquet")
740
+
741
+ article = article_rows[0] if article_rows else {}
742
+ article_cid = article.get("cid")
743
+ law_cid = article.get("law_cid")
744
+ if article_rows and (not article_cid or not law_cid):
745
+ messages.append("Sample article row must include cid and law_cid.")
746
+
747
+ vector_match = _parquet_contains_if_present(
748
+ out_dir,
749
+ missing,
750
+ "indexes/vector/vector_mapping.parquet",
751
+ "source_cid",
752
+ article_cid,
753
+ )
754
+ bm25_match = _parquet_contains_if_present(
755
+ out_dir,
756
+ missing,
757
+ "indexes/bm25/bm25_documents.parquet",
758
+ "source_cid",
759
+ article_cid,
760
+ )
761
+ node_match = _parquet_contains_if_present(
762
+ out_dir, missing, "graph/kg_nodes.parquet", "cid", article_cid
763
+ )
764
+ edge_match = _parquet_contains_if_present(
765
+ out_dir, missing, "graph/kg_edges.parquet", "source_cid", article_cid
766
+ )
767
+ relationship_match = _parquet_contains_if_present(
768
+ out_dir,
769
+ missing,
770
+ "logic/logic_relationships.parquet",
771
+ "source_cid",
772
+ article_cid,
773
+ )
774
+ parent_match = _parquet_contains_if_present(
775
+ out_dir, missing, "data/laws.parquet", "cid", law_cid
776
+ )
777
+
778
+ checks = {
779
+ "missing_required_files": missing,
780
+ "sample_article_cid": article_cid,
781
+ "sample_parent_law_cid": law_cid,
782
+ "parent_law_found": parent_match,
783
+ "vector_row_found": vector_match,
784
+ "bm25_row_found": bm25_match,
785
+ "graph_node_found": node_match,
786
+ "graph_edge_found": edge_match,
787
+ "logic_relationship_found": relationship_match,
788
+ }
789
+ ok = not messages and all(value for key, value in checks.items() if key.endswith("_found"))
790
+ return {
791
+ "ok": ok,
792
+ "records": manifest.get("records", {}),
793
+ "sample_cids": sample,
794
+ "checks": checks,
795
+ "messages": messages,
796
+ }
797
+
798
+
799
+ def _parquet_contains_if_present(
800
+ out_dir: Path, missing: list[str], rel: str, column: str, value: Any
801
+ ) -> bool:
802
+ if value is None or rel in missing:
803
+ return False
804
+ return _parquet_contains(out_dir / rel, column, value)
805
+
806
+
807
+ def _parquet_contains(path: Path, column: str, value: Any) -> bool:
808
+ parquet = pq.ParquetFile(path)
809
+ if column not in parquet.schema_arrow.names:
810
+ return False
811
+ for batch in parquet.iter_batches(columns=[column], batch_size=8192):
812
+ values = batch.column(0).to_pylist()
813
+ if value in values:
814
+ return True
815
+ return False
816
+
817
+
818
+ def main() -> None:
819
+ out_dir = build_unified_wetwijzer_package()
820
+ print(json.dumps({"out_dir": str(out_dir), **validate_unified_package(out_dir)}, indent=2))
821
+
822
+
823
+ if __name__ == "__main__":
824
+ main()
scrapers_and_normalizers/scripts/scrapers/legal/README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Legal Data Scrapers
2
+
3
+ This directory contains specialized scrapers for legal and regulatory data sources.
4
+
5
+ ## Available Scrapers
6
+
7
+ ### us_code_scraper.py
8
+ Scraper for the United States Code.
9
+
10
+ **Features:**
11
+ - Scrapes USC titles and sections
12
+ - Structured XML/HTML parsing
13
+ - Incremental updates
14
+
15
+ **Usage:**
16
+ ```bash
17
+ python scripts/scrapers/legal/us_code_scraper.py [options]
18
+ ```
19
+
20
+ ### state_laws_scraper.py
21
+ Scraper for state legislation and laws.
22
+
23
+ **Features:**
24
+ - Multi-state support
25
+ - Bill tracking
26
+ - Legislative session data
27
+
28
+ **Usage:**
29
+ ```bash
30
+ python scripts/scrapers/legal/state_laws_scraper.py [state] [options]
31
+ ```
32
+
33
+ ### municipal_laws_scraper.py
34
+ Scraper for municipal codes and ordinances.
35
+
36
+ **Features:**
37
+ - City and county codes
38
+ - Ordinance tracking
39
+ - Historical versions
40
+
41
+ **Usage:**
42
+ ```bash
43
+ python scripts/scrapers/legal/municipal_laws_scraper.py [municipality] [options]
44
+ ```
45
+
46
+ ### recap_archive_scraper.py
47
+ Scraper for the RECAP archive (court documents).
48
+
49
+ **Features:**
50
+ - Federal court dockets
51
+ - Case documents
52
+ - Metadata extraction
53
+
54
+ **Usage:**
55
+ ```bash
56
+ python scripts/scrapers/legal/recap_archive_scraper.py [options]
57
+ ```
58
+
59
+ ### federal_register_scraper.py
60
+ Scraper for the Federal Register.
61
+
62
+ **Features:**
63
+ - Daily register entries
64
+ - Agency documents
65
+ - Rules and notices
66
+
67
+ **Usage:**
68
+ ```bash
69
+ python scripts/scrapers/legal/federal_register_scraper.py [options]
70
+ ```
71
+
72
+ ### netherlands_laws_scraper.py
73
+ Scraper for Netherlands laws from official Dutch government law pages.
74
+
75
+ **Features:**
76
+ - Crawls official `wetten.overheid.nl` discovery/search pages
77
+ - Supports explicit BWBR law-document URLs
78
+ - Downloads per-law `/informatie` metadata pages
79
+ - Writes document, article, search, and JSON-LD outputs
80
+ - Persists scrape-run metadata with discovery/fetch/parse counters
81
+
82
+ **Usage:**
83
+ ```bash
84
+ ipfs-datasets legal scrape-netherlands-laws \
85
+ --seed_urls '["https://wetten.overheid.nl/zoeken/zoekresultaat/titel/verloten/titelf/0/tekstf/1/d/10-5-2025/dx/0/page/1/count/100/s/2"]' \
86
+ --output_dir ~/.ipfs_datasets/netherlands_laws \
87
+ --max_seed_pages 10 \
88
+ --crawl_depth 1 \
89
+ --max_documents 50 \
90
+ --rate_limit_delay 0.5 \
91
+ --skip_existing true
92
+ ```
93
+
94
+ **Outputs:**
95
+ - `netherlands_laws_index_latest.jsonl`: document-level normalized law records
96
+ - `netherlands_laws_articles_index_latest.jsonl`: article-level records
97
+ - `netherlands_laws_search_index_latest.jsonl`: combined document/article search rows
98
+ - `netherlands_laws_jsonld/NETHERLANDS-LAWS.jsonld`: JSON-LD export
99
+ - `netherlands_laws_run_metadata_latest.json`: run counters and error log
100
+
101
+ **How To Tell It Is Working:**
102
+ - `seed_pages_visited` should increase above 0 when discovery pages are reachable
103
+ - `candidate_links_found` and `official_law_documents_accepted` should grow as BWBR links are discovered
104
+ - `documents_fetched` and `documents_parsed` should track successful law retrieval/parsing
105
+ - `documents_skipped` should increase on reruns when `--skip_existing true` is used
106
+ - `errors` in the run metadata should stay small and inspectable rather than silently ignored
107
+
108
+ ## Integration
109
+
110
+ These scrapers can be used with the Legal Dataset Tools in the MCP server:
111
+
112
+ ```bash
113
+ # Via MCP tools
114
+ ipfs-datasets tools run legal_dataset_tools scrape_jurisdiction --jurisdiction "us_federal"
115
+
116
+ # Direct execution
117
+ python scripts/scrapers/legal/us_code_scraper.py
118
+ ```
119
+
120
+ ## Requirements
121
+
122
+ Most scrapers require additional dependencies:
123
+ - `beautifulsoup4` - HTML parsing
124
+ - `lxml` - XML parsing
125
+ - `requests` - HTTP requests
126
+ - `playwright` - Browser automation (for some scrapers)
127
+
128
+ Install with:
129
+ ```bash
130
+ pip install beautifulsoup4 lxml requests playwright
131
+ ```
132
+
133
+ ## Data Storage
134
+
135
+ Scraped data is typically stored in:
136
+ - IPFS (via ipfs_kit_py)
137
+ - Local cache directories
138
+ - Dataset formats (Parquet, JSON, etc.)
139
+
140
+ ## Notes
141
+
142
+ - Some scrapers may require API keys or credentials
143
+ - Respect rate limits and robots.txt
144
+ - See individual scraper files for detailed documentation
scrapers_and_normalizers/scripts/scrapers/legal/courtlistener_docket_ingest.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Ingest a CourtListener docket into the docket dataset pipeline."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import importlib.util
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ PROJECT_ROOT = Path(__file__).resolve().parents[3]
11
+ if str(PROJECT_ROOT) not in sys.path:
12
+ sys.path.insert(0, str(PROJECT_ROOT))
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ cli_path = PROJECT_ROOT / "ipfs_datasets_py" / "cli" / "docket_cli.py"
17
+ spec = importlib.util.spec_from_file_location("courtlistener_docket_cli", cli_path)
18
+ if spec is None or spec.loader is None:
19
+ raise RuntimeError(f"Unable to load docket CLI from {cli_path}")
20
+ module = importlib.util.module_from_spec(spec)
21
+ spec.loader.exec_module(module)
22
+
23
+ args = list(argv if argv is not None else sys.argv[1:])
24
+ if "--input-type" not in args:
25
+ args = ["--input-type", "courtlistener", *args]
26
+ return int(module.main(args))
27
+
28
+
29
+ if __name__ == "__main__":
30
+ raise SystemExit(main())
scrapers_and_normalizers/scripts/scrapers/legal/federal_register_scraper.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports.
2
+
3
+ The legal scraper implementations live under
4
+ `ipfs_datasets_py.legal_scrapers`.
5
+ """
6
+
7
+ from ipfs_datasets_py.processors.legal_scrapers.federal_register_scraper import * # noqa: F401,F403
scrapers_and_normalizers/scripts/scrapers/legal/municipal_laws_scraper.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports.
2
+
3
+ The legal scraper implementations live under
4
+ `ipfs_datasets_py.legal_scrapers`.
5
+ """
6
+
7
+ from ipfs_datasets_py.processors.legal_scrapers.municipal_laws_scraper import * # noqa: F401,F403
scrapers_and_normalizers/scripts/scrapers/legal/netherlands_laws_scraper.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Compatibility wrapper for the Netherlands laws scraper."""
2
+
3
+ from ipfs_datasets_py.processors.legal_scrapers.netherlands_laws_scraper import * # noqa: F401,F403
scrapers_and_normalizers/scripts/scrapers/legal/recap_archive_scraper.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports.
2
+
3
+ The legal scraper implementations live under
4
+ `ipfs_datasets_py.legal_scrapers`.
5
+ """
6
+
7
+ from ipfs_datasets_py.processors.legal_scrapers.recap_archive_scraper import * # noqa: F401,F403
scrapers_and_normalizers/scripts/scrapers/legal/state_laws_scraper.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports.
2
+
3
+ The legal scraper implementations live under
4
+ `ipfs_datasets_py.legal_scrapers`.
5
+ """
6
+
7
+ from ipfs_datasets_py.processors.legal_scrapers.state_laws_scraper import * # noqa: F401,F403
scrapers_and_normalizers/scripts/scrapers/legal/us_code_scraper.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports.
2
+
3
+ The legal scraper implementations live under
4
+ `ipfs_datasets_py.legal_scrapers`.
5
+ """
6
+
7
+ from ipfs_datasets_py.processors.legal_scrapers.us_code_scraper import * # noqa: F401,F403