endomorphosis commited on
Commit
7dc8b62
·
verified ·
1 Parent(s): 80f8c63

mu_b1: AGO consolidated Acts diff-limited append (+526 laws / +16,881 articles -> 723 laws / 22,815 articles); scrapers/mu_b1 bundle

Browse files
MANIFEST.md CHANGED
@@ -24,3 +24,17 @@ catalog_expected: None
24
  catalog_gap:
25
  gaps: Official Mauritius (cc=mu) Acts/Bills/SI/Gazette/Constitution PDFs from attorneygeneral.govmu.org, nationalassembly.govmu.org, mauritiusassembly.govmu.org, supremecourt.govmu.org and govmu.org only. Live-first; Wayback/CDX of official *.govmu.org / *.gov.mu URLs on fail. NOT AfricanLII / MauritiusLII. No WAF bypass. Distinct from Seychelles (sc), Comoros (km), Madagascar (mg). Not legal advice.
26
  uploaded: false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  catalog_gap:
25
  gaps: Official Mauritius (cc=mu) Acts/Bills/SI/Gazette/Constitution PDFs from attorneygeneral.govmu.org, nationalassembly.govmu.org, mauritiusassembly.govmu.org, supremecourt.govmu.org and govmu.org only. Live-first; Wayback/CDX of official *.govmu.org / *.gov.mu URLs on fail. NOT AfricanLII / MauritiusLII. No WAF bypass. Distinct from Seychelles (sc), Comoros (km), Madagascar (mg). Not legal advice.
26
  uploaded: false
27
+
28
+ ## batch mu_b1 (diff-limited append)
29
+
30
+ - parent: 80f8c63175886c85a94669f825086cee6c322009
31
+ - laws_rows: 723 (tip 197, new 526)
32
+ - articles_rows: 22815 (tip 5934, new 16881)
33
+ - laws_sha256: 4045d9a063c367d264f20cdf0035e443787ddd82a20710cd6eed371f28ca9a1e
34
+ - articles_sha256: e99b82992ad3cc6faac0e702fab5b44f75f58c1843f5d91fe4b2692f6de4e664
35
+ - compression: zstd; row groups 1 (copied from the tip)
36
+ - collector: scrapers/mu_b1/collect_mu.py (pipeline scrapers/mu_b1/pipeline_mu.sh)
37
+ - drops: {"empty_text": 36, "duplicate_act_in_batch": 49, "duplicate_of_tip": 10}
38
+ - heading-only rows dropped 1036; repeal placeholders kept 455; schedules 379; whole-text fallback 36
39
+ - MANIFEST.json / provenance/changes.json: not present on the parent commit (not created by this batch)
40
+ - checksums: SHA256SUMS
README.md CHANGED
@@ -40,8 +40,8 @@ Research snapshot of official national legislation from **Attorney General's Off
40
  | Coverage | catalog-backed incomplete (attorneygeneral.govmu.org + nationalassembly/mauritiusassembly.govmu.org + supremecourt.govmu.org + govmu.org live+CDX; PDFs >12MB skipped) |
41
  | Source | Attorney General's Office (attorneygeneral.govmu.org) + National Assembly (nationalassembly.govmu.org / mauritiusassembly.govmu.org) + Supreme Court (supremecourt.govmu.org) + govmu.org |
42
  | Collector | `scrapers/collect_mu.py` |
43
- | Laws / instruments | 197 |
44
- | Articles | 5,934 |
45
  | Language | en |
46
  | Jurisdiction | Mauritius |
47
  | License | `mu-ago-assembly-supremecourt-official-texts` |
@@ -76,3 +76,32 @@ Additive update on top of `endomorphosis/ipfs_mauritius_laws`@94566e522d28: laws
76
  - Article rows are an exact partition of the law text at numbered article/section markers; laws with no clean markers have no article rows.
77
  - Per-row provenance (source URL, crawl, dropped candidates and reasons, title/language repairs, audit fixes) is in `provenance/changes.json`; file hashes in `MANIFEST.json`.
78
  - Research compilation of public legal texts. The official gazette / authentic text prevails. Not legal advice.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  | Coverage | catalog-backed incomplete (attorneygeneral.govmu.org + nationalassembly/mauritiusassembly.govmu.org + supremecourt.govmu.org + govmu.org live+CDX; PDFs >12MB skipped) |
41
  | Source | Attorney General's Office (attorneygeneral.govmu.org) + National Assembly (nationalassembly.govmu.org / mauritiusassembly.govmu.org) + Supreme Court (supremecourt.govmu.org) + govmu.org |
42
  | Collector | `scrapers/collect_mu.py` |
43
+ | Laws / instruments | 723 |
44
+ | Articles | 22,815 |
45
  | Language | en |
46
  | Jurisdiction | Mauritius |
47
  | License | `mu-ago-assembly-supremecourt-official-texts` |
 
76
  - Article rows are an exact partition of the law text at numbered article/section markers; laws with no clean markers have no article rows.
77
  - Per-row provenance (source URL, crawl, dropped candidates and reasons, title/language repairs, audit fixes) is in `provenance/changes.json`; file hashes in `MANIFEST.json`.
78
  - Research compilation of public legal texts. The official gazette / authentic text prevails. Not legal advice.
79
+
80
+ ## Batch mu_b1 update (AGO consolidated Acts A-Z)
81
+
82
+ Diff-limited append on top of `endomorphosis/ipfs_mauritius_laws`@80f8c6317588: laws/articles 197/5,934 -> 723/22,815 (new instruments 526, new article rows 16,881). Every row already in the dataset is kept unchanged; new rows follow them.
83
+
84
+ - Source: the Attorney General's Office 'Acts A-Z' pages (attorneygeneral.govmu.org, Laws of Mauritius), one consolidated PDF per Act (Revised Laws of Mauritius layout). Live official pages only; robots.txt checked on every hop; no archives, logins or forms.
85
+ - New rows carry `source_type` = `mauritius_ago_revised_laws_acts_az` and `metadata_json.batch` = `mu_b1` (listing page, file name, PDF sha256, Last-Modified, bounds, printed Act number line).
86
+ - Duplicates dropped: identical PDFs, the same Act listed twice under two file names (newest copy kept) and Acts already in this dataset (normalised title + year); see `manifests/mu_b1_drops.jsonl`.
87
+ - Every new article `text` is a verbatim slice `laws.text[char_start:char_end]` (offsets in the article's `metadata_json`, ascending). Arrangement-of-sections lines with no body are not articles (listed in `manifests/known_gaps.json`); repealed/spent sections printed as 'Repealed by ...' or 'N. —' are kept with `metadata_json.body_status` = `repealed_placeholder`; Schedules are separate `-sch` articles.
88
+ - The Act number and year in the listing/file name are checked against the printed title block; mismatches are listed in `manifests/known_gaps.json` (the printed value is used).
89
+ - Free-webmail addresses are redacted as `[redacted-webmail]` (`manifests/webmail_redactions.json`, offsets only).
90
+ - `scrapers/mu_b1/`: complete code for this batch with a how-to-run README; pinned versions in `scrapers/requirements.txt`; file hashes in `manifests/mu_b1_code.json`; `SHA256SUMS` covers every file of the pack.
91
+
92
+ ### License / reuse (batch mu_b1)
93
+
94
+ Consolidated Acts of Mauritius as published by the Attorney General's Office (attorneygeneral.govmu.org). Described, not quoted: the site's Term of Use lets people make personal copies and printouts of the legislation under the Copyright Act, but publishing, disseminating or incorporating it for commercial use needs the prior approval of the Solicitor General; the site also says that only the LexisNexis 2016 Revised Laws of Mauritius (with their supplements) are the authoritative text, so these copies are for information only. Terms: https://attorneygeneral.govmu.org/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx . Not legal advice.
95
+
96
+ ### OCR and text quality (batch mu_b1)
97
+
98
+ - Text source: the PDFs' own text layer (pdftotext -layout) for 502 instruments; tesseract OCR (eng, system tessdata) for 24.
99
+ - DEGRADED means: OCR mean word confidence below 80, or more than 8 % of a text layer's characters outside printable Latin text.
100
+ - Whole-text fallback (no usable numbered sections, or one section dominating): 36 instruments (listed in `manifests/known_gaps.json`).
101
+
102
+ DEGRADED items: none.
103
+
104
+ ### Known gaps (batch mu_b1)
105
+
106
+ - The A-Z pages are the AGO's consolidated set; Acts passed after the last consolidation on the site may be missing or not yet consolidated.
107
+ - Drops by reason: duplicate_act_in_batch 49, duplicate_of_tip 10, empty_text 36.
SHA256SUMS ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 74580987e2ef0f3df46e8834880cbe5c6f591e884b9231c84e43fee41b034624 MANIFEST.md
2
+ 8a56053306aa49e6632cb0bc8be3eeb9520182e99cd2369a4ef7ded6fd26be00 README.md
3
+ e99b82992ad3cc6faac0e702fab5b44f75f58c1843f5d91fe4b2692f6de4e664 data/articles.parquet
4
+ 4045d9a063c367d264f20cdf0035e443787ddd82a20710cd6eed371f28ca9a1e data/laws.parquet
5
+ e492b8793ef2d2e9591ebff13dfbee0785871c82e4fd13c6fd76ef3390ad804e manifests/changed_ids.json
6
+ 3f9e49f0fa110da07ab7da296812b78b89e790e31ef2d9990e39637a2158f25b manifests/known_gaps.json
7
+ 10381964d9ca2a0d4bdc039a5e2982b78e3105d4a19e3177c8f4b90f1fd0e3f4 manifests/mu_b1_code.json
8
+ 32c20f64f37682234c2e176a863e7d9e7b09f872bd9a10c31472dd5012a52dd5 manifests/mu_b1_drops.jsonl
9
+ 4d9f846e8839b0e9cba30165b400621c35964a293aaa45fb66bcb38301e8c334 manifests/mu_b1_pii_scan.json
10
+ ebf3f8d01754d7c1797dcd3113b6df279ed75d75703c1f8db31125de8638ed7a manifests/mu_b1_summary.json
11
+ 22e6ecc6b9b988d6e646fdc1b1ce0fcc575c218ef6b6fc900027f6ffb5c7ccf7 manifests/pii_scan_notes.md
12
+ 091a771025f44f34582d605b0b4dcc75df52bac1310bfefc5ee7f6de7f3c6836 manifests/webmail_redactions.json
13
+ e5b59be89063d70973109e5c0d1e40292aca55d33faf8e22cbf9eb4871255b60 scrapers/mu_b1/README.md
14
+ 3666a01e0aacada4f37fd727cfbb0dd4401c1c7611788ed7ddfa87eb51afee40 scrapers/mu_b1/articles_mu.py
15
+ d0b5bb288e11db24ff4b9ba10f9044bed52b2a836e6a33af30ca335cc5240779 scrapers/mu_b1/br_waiting.sh
16
+ d1a2050ece0e8030fa06d1595ef149b17fccc290d998116c9368f33d8e67efe0 scrapers/mu_b1/challenge_detector_v2.py
17
+ 2ef0a6427fb829855d4167d9ac10a1fa8676ddc72a834049bc0d9a929f165dfe scrapers/mu_b1/classify_mu.py
18
+ ece509d861a2d71600ebda5af0ee19ab830aa8f8e0ebe2ce0ae3e7d942c68d39 scrapers/mu_b1/collect_mu.py
19
+ 3cb0c44612fe290f13cc8154555c2afe065c3b8a36a091dee63b4d20104e8bb0 scrapers/mu_b1/extract_mu.py
20
+ 763513542d94c7cd4259b8b4120e692319305cbf6ed174176de112e433ee7e06 scrapers/mu_b1/finalize_mu.py
21
+ d855c2da5a06029077ec55c76bdf5930c62e1e2fc48a5d7911bb006cdf8c08f8 scrapers/mu_b1/mu_net.py
22
+ c6f4cad70e5d8a031f0fba2b3c610eb407084307f09e2727636cc4e8abd404a8 scrapers/mu_b1/ocr_mu.py
23
+ 588e5f4888c0b3c7b8b16dbeb61ae6443d3983bb737fa0d857c2c14ab7d78667 scrapers/mu_b1/pii_scan_mu.py
24
+ ba67bfb6b737afb71e7e252fee2acd561082f21e32095f7f0c52b18497a4ed0d scrapers/mu_b1/pipeline_mu.sh
25
+ 99c7d5d6e37ede272bba826b066854de93ea0615f6e09248b64fb85eb2f1ed92 scrapers/mu_b1/readme_mu.py
26
+ 3b19512cd5e12799cf68d05e9f4a331b585399b7269a4c766308c21907da2c4c scrapers/mu_b1/requirements.txt
27
+ ae493dcc040f22127c8c9064679583fe8f49f620f1a1206968e230b36a1f9139 scrapers/mu_b1/robots_guard.py
28
+ e6f32ad254a8f2528536cedcc9f5603687f7bd3d756c777ebf1bf94540c7ee2c scrapers/mu_b1/split_mu.py
29
+ 154c41c53bd815b626a0019e68e020effa150395344cfe6928901f4498c7a1c8 scrapers/mu_b1/stage_mu.py
30
+ 96bfc34ee5b6fff94c089f19218d86d277f7ef63c86f7d841381d9c63306fe80 scrapers/mu_b1/validate_split_mu.py
31
+ 9bbbc728b75be42503eb079bc3cedf48b75af46a582a56637e8336760b462058 scrapers/mu_b1/verify_mu.py
32
+ e6ecae506421274a004c99793bb214b76928e014f416cd6a71a3f583a866f1cc scrapers/mu_b1/webmail_mu.py
33
+ 3b19512cd5e12799cf68d05e9f4a331b585399b7269a4c766308c21907da2c4c scrapers/requirements.txt
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:891500bb92ff65ab32be1db82481332dc1ca728052865b8eb29c8aa0637e48a2
3
- size 1833206
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e99b82992ad3cc6faac0e702fab5b44f75f58c1843f5d91fe4b2692f6de4e664
3
+ size 8215798
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:60271dcf6d4967d6ed1eab8108107f479e69627668dfa214c875f3ae076c198d
3
- size 1673306
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4045d9a063c367d264f20cdf0035e443787ddd82a20710cd6eed371f28ca9a1e
3
+ size 7596440
manifests/changed_ids.json ADDED
The diff for this file is too large to render. See raw diff
 
manifests/known_gaps.json ADDED
The diff for this file is too large to render. See raw diff
 
manifests/mu_b1_code.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bundle": "scrapers/mu_b1",
3
+ "files": {
4
+ "README.md": "e5b59be89063d70973109e5c0d1e40292aca55d33faf8e22cbf9eb4871255b60",
5
+ "articles_mu.py": "3666a01e0aacada4f37fd727cfbb0dd4401c1c7611788ed7ddfa87eb51afee40",
6
+ "br_waiting.sh": "d0b5bb288e11db24ff4b9ba10f9044bed52b2a836e6a33af30ca335cc5240779",
7
+ "challenge_detector_v2.py": "d1a2050ece0e8030fa06d1595ef149b17fccc290d998116c9368f33d8e67efe0",
8
+ "classify_mu.py": "2ef0a6427fb829855d4167d9ac10a1fa8676ddc72a834049bc0d9a929f165dfe",
9
+ "collect_mu.py": "ece509d861a2d71600ebda5af0ee19ab830aa8f8e0ebe2ce0ae3e7d942c68d39",
10
+ "extract_mu.py": "3cb0c44612fe290f13cc8154555c2afe065c3b8a36a091dee63b4d20104e8bb0",
11
+ "finalize_mu.py": "763513542d94c7cd4259b8b4120e692319305cbf6ed174176de112e433ee7e06",
12
+ "mu_net.py": "d855c2da5a06029077ec55c76bdf5930c62e1e2fc48a5d7911bb006cdf8c08f8",
13
+ "ocr_mu.py": "c6f4cad70e5d8a031f0fba2b3c610eb407084307f09e2727636cc4e8abd404a8",
14
+ "pii_scan_mu.py": "588e5f4888c0b3c7b8b16dbeb61ae6443d3983bb737fa0d857c2c14ab7d78667",
15
+ "pipeline_mu.sh": "ba67bfb6b737afb71e7e252fee2acd561082f21e32095f7f0c52b18497a4ed0d",
16
+ "readme_mu.py": "99c7d5d6e37ede272bba826b066854de93ea0615f6e09248b64fb85eb2f1ed92",
17
+ "requirements.txt": "3b19512cd5e12799cf68d05e9f4a331b585399b7269a4c766308c21907da2c4c",
18
+ "robots_guard.py": "ae493dcc040f22127c8c9064679583fe8f49f620f1a1206968e230b36a1f9139",
19
+ "split_mu.py": "e6f32ad254a8f2528536cedcc9f5603687f7bd3d756c777ebf1bf94540c7ee2c",
20
+ "stage_mu.py": "154c41c53bd815b626a0019e68e020effa150395344cfe6928901f4498c7a1c8",
21
+ "validate_split_mu.py": "96bfc34ee5b6fff94c089f19218d86d277f7ef63c86f7d841381d9c63306fe80",
22
+ "verify_mu.py": "9bbbc728b75be42503eb079bc3cedf48b75af46a582a56637e8336760b462058",
23
+ "webmail_mu.py": "e6ecae506421274a004c99793bb214b76928e014f416cd6a71a3f583a866f1cc"
24
+ },
25
+ "requirements": {
26
+ "scrapers/requirements.txt": "3b19512cd5e12799cf68d05e9f4a331b585399b7269a4c766308c21907da2c4c"
27
+ },
28
+ "robots_guard": {
29
+ "upstream_sha256": "fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542",
30
+ "bundled_sha256": "ae493dcc040f22127c8c9064679583fe8f49f620f1a1206968e230b36a1f9139",
31
+ "change": "cache root default changed from an absolute fleet path to the relative 'legal-corpora' (LEGAL_CORPORA_ROOT overrides); no logic change"
32
+ }
33
+ }
manifests/mu_b1_drops.jsonl ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"key": "7ba0ffcf4493224f", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/AFRICAN%20CULTURAL%20CENTRE%20TRUST%20FUND%20ACT.pdf", "title": "AFRICAN CULTURAL CENTRE TRUST FUND ACT", "reason": "empty_text"}
2
+ {"key": "4e343704d62c7607", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/AGRICULTURAL%20DIVERSIFICATION%20CORPORATION%20ACT,%20No%2012%20of%201983.pdf", "title": "AGRICULTURAL DIVERSIFICATION CORPORATION ACT", "reason": "empty_text"}
3
+ {"key": "f298a134a8f5cdc9", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/APPRENTICESHIPACT.pdf", "title": "APPRENTICESHIP ACT", "reason": "empty_text"}
4
+ {"key": "4b0842c0424620fd", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/Ar/ARBITRATION(FOREIGNAWARDS)ACT.pdf", "title": "ARBITRATION (FOREIGN AWARDS) ACT", "reason": "empty_text"}
5
+ {"key": "3fc9457766c00710", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/Ar/ARBITRATIONCLAUSES(PROTOCOL)ACT.pdf", "title": "ARBITRATION CLAUSES (PROTOCOL) ACT", "reason": "empty_text"}
6
+ {"key": "6e01f49a2abfff0b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CAISSE%20CENTRALE%20DE%20COOP%c3%89RATION%20ECONOMIQUE%20%28IMMUNITIES%20AND%20PRIVILEGES%29%20ACT%2c%20No%2048%20of%201975.pdf", "title": "CAISSE CENTRALE DE COOPéRATION ECONOMIQUE (IMMUNITIES AND PRIVILEGES) ACT", "reason": "empty_text"}
7
+ {"key": "ee6e986635912251", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CARGO%20HANDLING%20CORPORATION%20ACT%2c%20No%2020%20of%201983.pdf", "title": "CARGO HANDLING CORPORATION ACT", "reason": "empty_text"}
8
+ {"key": "821ddce71c3a683b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CENTRAL%20TENDER%20BOARD%20ACT,%20No%2032%20of%202000.pdf", "title": "CENTRAL TENDER BOARD ACT", "reason": "empty_text"}
9
+ {"key": "c5b01f8fa912659d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CIVIL%20AVIATION%20%28FEES%20AND%20CHARGES%29%20ACT%2c%20No%2021%20of%201977.pdf", "title": "CIVIL AVIATION (FEES AND CHARGES) ACT", "reason": "empty_text"}
10
+ {"key": "284c629a28f6fb30", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CIVIL%20AVIATION%20%28TRANSFER%20OF%20UNDERTAKING%29%20ACT%2c%20No%2041%20of%201993.pdf", "title": "CIVIL AVIATION (TRANSFER OF UNDERTAKING) ACT", "reason": "empty_text"}
11
+ {"key": "bbb933dcd686b141", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/COMMERCIAL%20AND%20INDUSTRIAL%20INVESTMENT%20TRUST%20OF%20MAURITIUS%20ACT%2c%20No%2034%20of%201976.pdf", "title": "COMMERCIAL AND INDUSTRIAL INVESTMENT TRUST OF MAURITIUS ACT", "reason": "empty_text"}
12
+ {"key": "2174df15b3a7e76e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/D/DISTRIBUTION%20OF%20FODDER%20(CONTROL)%20ACT,%20No%2010%20of%201961.pdf", "title": "DISTRIBUTION OF FODDER (CONTROL) ACT", "reason": "empty_text"}
13
+ {"key": "a03ae02367ef8a71", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/D/DISTRICT%20COURTS%20EXECUTION%20ACT,%20No%2017%20of%201947.pdf", "title": "DISTRICT COURTS EXECUTION ACT", "reason": "empty_text"}
14
+ {"key": "9655cdc4a5ee06a1", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/F/Fi/FINANCE%20AND%20AUDIT%20(TEMPORARY%20PROVISIONS)%20ACT,%20No%203%20of%202006.pdf", "title": "FINANCE AND AUDIT (TEMPORARY PROVISIONS) ACT", "reason": "empty_text"}
15
+ {"key": "03a1ecef7cc6513a", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/F/FREEPORT%20(TRANSFER%20OF%20UNDERTAKING)%20ACT,%20No%2018%20of%202001.pdf", "title": "FREEPORT (TRANSFER OF UNDERTAKING) ACT", "reason": "empty_text"}
16
+ {"key": "fff726f4434e17db", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/G/GAMING%20ACT,18%20of%201973.pdf", "title": "GAMING ACT", "reason": "empty_text"}
17
+ {"key": "182181a39d77e729", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/G/GRANARY%20ACT,%20Cap%2064.pdf", "title": "GRANARY ACT", "reason": "empty_text"}
18
+ {"key": "d8d7600b20a20cdc", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/H/HORSE%20RACING%20BOARD%20ACT,%20No%2023%20of%202003.pdf", "title": "HORSE RACING BOARD ACT", "reason": "empty_text"}
19
+ {"key": "b9626e5523b1978d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/I/IMPRISONMENT%20FOR%20CIVIL%20DEBT%20(ABOLITION)%20ACT,%20No%2027%20of%202006.pdf", "title": "IMPRISONMENT FOR CIVIL DEBT (ABOLITION) ACT", "reason": "empty_text"}
20
+ {"key": "ee65f35c1942e26d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/M/MCCB%20LIMITED%20(LIQUIDATION)%20ACT,%20No%208%20of%201996.pdf", "title": "MCCB LIMITED (LIQUIDATION) ACT", "reason": "empty_text"}
21
+ {"key": "40fd62e97c3de316", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/N/Na/NATIONAL%20INDUSTRIES%20(REGISTRATION%20AND%20LICENSING)%20ACT,%20No%2057%20of%201968.pdf", "title": "NATIONAL INDUSTRIES (REGISTRATION AND LICENSING) ACT", "reason": "empty_text"}
22
+ {"key": "405319e445b13f42", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/N/Na/NATIONAL%20UNIVERSITY%20OF%20MAURITIUS%20(PROVISIONAL%20COUNCIL)%20ACT,%20No%2023%20of%201982.pdf", "title": "NATIONAL UNIVERSITY OF MAURITIUS (PROVISIONAL COUNCIL) ACT", "reason": "empty_text"}
23
+ {"key": "729dbc1d07cbf0c5", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PRESIDENTIAL%20COMMISSION%20ACT%2c%20No%202%20of%201997.pdf", "title": "PRESIDENTIAL COMMISSION ACT", "reason": "empty_text"}
24
+ {"key": "a22dbdd99c124733", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PREVENTION%20OF%20MALARIA%20ACT%2c%20No%2028%20of%201946.pdf", "title": "PREVENTION OF MALARIA ACT", "reason": "empty_text"}
25
+ {"key": "c29abf65d6b64f5e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PRIVATISATION%20FUND%20%28REVENUE%20AND%20EXPENDITURE%29%20ACT%2c%20No%2019%20of%201999.pdf", "title": "PRIVATISATION FUND (REVENUE AND EXPENDITURE) ACT (2)", "reason": "empty_text"}
26
+ {"key": "40413e3675321f1e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PRIVATISATION%20FUND%20%28REVENUE%20AND%20EXPENDITURE%29%20ACT%2c%20No%2015%20of%201997.pdf", "title": "PRIVATISATION FUND (REVENUE AND EXPENDITURE) ACT", "reason": "empty_text"}
27
+ {"key": "f7dc171ee2b2f3bc", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PRIZE%20COMPETITIONS%20ACT%2c%20No.%2036%20of%201975.pdf", "title": "PRIZE COMPETITIONS ACT", "reason": "empty_text"}
28
+ {"key": "6c664823836b3bce", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pu/PUBLIC%20SECURITY%20ACT%2c%20No.%201%20of%202000.pdf", "title": "PUBLIC SECURITY ACT", "reason": "empty_text"}
29
+ {"key": "086c38e8b815bac3", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pu/PUBLIC%20TRUSTEE%20ACT%2c%20No.%2027%20of%201989.pdf", "title": "PUBLIC TRUSTEE ACT", "reason": "empty_text"}
30
+ {"key": "a667e747d86f61b3", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/REPLENISHMENT%20OF%20THE%20CONTINGENCIES%20FUND%20%282005-2006%29%20ACT%2c%20No%207%20of%202006.pdf", "title": "REPLENISHMENT OF THE CONTINGENCIES FUND (2005-2006) ACT", "reason": "empty_text"}
31
+ {"key": "6654614ffd916608", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Si/SILVERCURRENCYPROTECTIONACTCap139.pdf", "title": "SILVER CURRENCY PROTECTION ACT", "reason": "empty_text"}
32
+ {"key": "40e6d081c3f5c2b4", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Su/SUGARINDUSTRYDEVELOPMENTFUNDSREPEALACTNo18of1994.pdf", "title": "SUGAR INDUSTRY DEVELOPMENT FUNDS (REPEAL) ACT", "reason": "empty_text"}
33
+ {"key": "3eafb4a58beb4ecf", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/T/Te/TELECOMMUNICATIONTRANSFERACTNo11of1988.pdf", "title": "TELECOMMUNICATION (TRANSFER) ACT", "reason": "empty_text"}
34
+ {"key": "af1cffbe99defa83", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/U/Un/UNIONCATHOLIQUEDELILEMAURICEACTCap384.pdf", "title": "UNION CATHOLIQUE DE L’ILE MAURICE ACT", "reason": "empty_text"}
35
+ {"key": "6560512b9d97e042", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/W/WAGESANDSALARIESAGGREGATIONOFCOSTOFLIVINGALLOWANCEACT24of1976.pdf", "title": "WAGES AND SALARIES (AGGREGATION OF COST OF LIVING ALLOWANCE) ACT", "reason": "empty_text"}
36
+ {"key": "8c9740ba1e7abfc7", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/W/WIDOWSANDORPHANSPENSIONFUNDACTCap342.pdf", "title": "WIDOWS AND ORPHANS PENSION FUND ACT", "reason": "empty_text"}
37
+ {"key": "0f98364c355d283b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/ADVERTISEMENTS%20REGULATION%20ACT.pdf", "title": "ADVERTISEMENTS REGULATION ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/Advertisements%20Regulation%20Act%2c%20Cap.%20281.pdf"}
38
+ {"key": "d243f4407ce4e5bc", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/B/BIOLOGICAL%20AND%20TOXIN%20WEAPONS%20CONVENTION%20ACT%2c%20No%202%20of%202004.pdf", "title": "BIOLOGICAL AND TOXIN WEAPONS CONVENTION ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/B/Biological%20and%20Toxin%20Weapons%20Convention%20Act%2c%20No.%202%20of%202004.pdf"}
39
+ {"key": "c2fd0be65616335f", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/B/BUS%20INDUSTRY%20EMPLOYEES%20WELFARE%20FUND%20ACT%2c%20No%2036%20of%202002.pdf", "title": "BUS INDUSTRY EMPLOYEES WELFARE FUND ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/B/Bus%20Industry%20Employees%20Welfare%20Fund%20Act%2c%20No.%2036%20of%202002.pdf"}
40
+ {"key": "4218e4497f9cca50", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CADASTRAL%20SURVEY%20ACT%2c%20No%2022%20of%202011.pdf", "title": "CADASTRAL SURVEY ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Cadastral%20Survey%20Act%2c%20No.%2022%20of%202011.pdf"}
41
+ {"key": "bda62140942ea081", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CHEMICAL%20WEAPONS%20CONVENTION%20ACT%2c%20No%203%20of%202003.pdf", "title": "CHEMICAL WEAPONS CONVENTION ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Chemical%20Weapons%20Convention%20Act%2c%20No.%203%20of%202003.pdf"}
42
+ {"key": "9e033e1401bd8d7f", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CIVIL%20SERVICE%20FAMILY%20PROTECTION%20SCHEME%20ACT%2c%20No%2016%20of%201969.pdf", "title": "CIVIL SERVICE FAMILY PROTECTION SCHEME ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Civil%20Service%20Family%20Protection%20Scheme%20Act%2c%20No.%2016%20of%201969.pdf"}
43
+ {"key": "791518a01e082ecc", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CIVIL%20STATUS%20ACT%2c%20No%2023%20of%201981.pdf", "title": "CIVIL STATUS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Civil%20Status%20Act%2c%20No.%2023%20of%201981.pdf"}
44
+ {"key": "30d95c51bc31e6bf", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/CLINICAL%20TRIALS%20ACT%2c%20No%208%20of%202011.pdf", "title": "CLINICAL TRIALS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Clinical%20Trials%20Act%2c%20No.%208%20of%202011.pdf"}
45
+ {"key": "b4974e4c1c9d3bb7", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/COMMUNITY%20SERVICE%20ORDER%20ACT%2c%20No%2017%20of%202002.pdf", "title": "COMMUNITY SERVICE ORDER ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Community%20Service%20Order%20Act%2c%20No.%2017%20of%202002.pdf"}
46
+ {"key": "5c18ef673bb22abd", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/CompaniesActNo.15of2001.pdf", "title": "COMPANIES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Companies%20Act%2c%20No.%2015%20of%202001.pdf"}
47
+ {"key": "1aeda15202b55ca4", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/ContructionIndustryDevelopmentBoardActNo35of2008.pdf", "title": "CONSTRUCTION INDUSTRY DEVELOPMENT BOARD ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Construction%20Industry%20Development%20Board%20Act%2c%20No.%2035%20of%202008.pdf"}
48
+ {"key": "6f5af47050fd9f1d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/CONSUMER%20PROTECTION%20%28PRICE%20AND%20SUPPLIES%20CONTROL%29%20ACT%2c%20No%2012%20of%201998.pdf", "title": "CONSUMER PROTECTION (PRICE AND SUPPLIES CONTROL) ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Consumer%20Protection%20%28Price%20and%20Supplies%20Control%29%20Act%2c%20No.%2012%20of%201998.pdf"}
49
+ {"key": "6025945353a7fac1", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/CONVENTION%20FOR%20THE%20SUPPRESSION%20OF%20THE%20FINANCING%20OF%20TERRORISM%20ACT%2c%20No%2037%20of%202003.pdf", "title": "CONVENTION FOR THE SUPPRESSION OF THE FINANCING OF TERRORISM ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Convention%20for%20the%20Suppression%20of%20the%20Financing%20of%20Terrorism%20Act%2c%20No.%2037%20of%202003.pdf"}
50
+ {"key": "9ba6c48db8ee1b7a", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/Co-operatives%20Act-Issue9.pdf", "title": "CO-OPERATIVES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co-operatives%20Act%2c%20No.%2022%20of%202016.pdf"}
51
+ {"key": "a82ea8d0ce8d77e2", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/PATENTS%2c%20INDUSTRIAL%20DESIGNS%20AND%20TRADEMARKS%20ACT%2c%20NO%2025%20of%202002.pdf", "title": "PATENTS, INDUSTRIAL DESIGNS AND TRADEMARKS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Patents%2c%20Industrial%20Designs%20and%20Trademarks%20Act%2c%20No.%2025%20of%202002.pdf"}
52
+ {"key": "0a7cedeed50c9254", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/PENSIONS%20ACT%2c%20No%2090%20of%201951%2c%2019%20of%201954%2c%205%20of%201976.pdf", "title": "PENSIONS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pensions%20Act%2c%20No.%2090%20of%201951%2c%2019%20of%201954%2c%205%20of%201976.pdf"}
53
+ {"key": "733db42598b29b8e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/PHARMACY%20ACT.pdf", "title": "PHARMACY ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pharmacy%20Act%2c%20No.%2060%20of%201983.pdf"}
54
+ {"key": "a215ad6b308eee2a", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Planning%20and%20Development%20Act-I9.pdf", "title": "PLANNING AND DEVELOPMENT ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Planning%20and%20Development%20Act%2c%20No.%2032%20of%202004.pdf"}
55
+ {"key": "f7d57066aca4967f", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/PORTS%20ACT%2c%20No%203%20of%201998.pdf", "title": "PORTS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Ports%20Act%2c%20No.%203%20of%201998.pdf"}
56
+ {"key": "708d7730af93ee1e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/POUCE%20STREAM%20%28AUTHORISED%20CONSTRUCTION%29%20ACT%2c%20No%2032%20of%201992.pdf", "title": "POUCE STREAM (AUTHORISED CONSTRUCTION) ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pouce%20Stream%20%28Authorised%20Construction%29%20Act%2c%20No.%2032%20of%201992.pdf"}
57
+ {"key": "e1714f184160f78d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PREVENTION%20OF%20CORRUPTION%20ACT%2c%20NO%205%20of%202002.pdf", "title": "PREVENTION OF CORRUPTION ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Prevention%20of%20Corruption%20Act%2c%20No.%205%20of%202002.pdf"}
58
+ {"key": "9425fff219a5e71d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PreventionofTerrorismAct-I9.pdf", "title": "PREVENTION OF TERRORISM ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Prevention%20of%20Terrorism%20Act%2c%20No.%202%20of%202002.pdf"}
59
+ {"key": "c92b1fcf3cc89d2d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PRIVATE%20PENSION%20SCHEMES%20ACT%2c%2015%20of%202012.pdf", "title": "PRIVATE PENSION SCHEMES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Private%20Pension%20Schemes%20Act%2c%20No.%2015%20of%202012.pdf"}
60
+ {"key": "9e519ca8c84537ef", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/ProfessionalLandSurveyorsCouncilAct-I9.pdf", "title": "PROFESSIONAL LAND SURVEYORS’ COUNCIL ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Professional%20Land%20Surveyors%e2%80%99%20Council%20Act%2c%20No.%204%20of%202014.pdf"}
61
+ {"key": "c43ab1f0dffc9253", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PROTECTED%20CELL%20COMPANIES%20ACT%2c%20No.%2037%20of%201999.pdf", "title": "PROTECTED CELL COMPANIES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Protected%20Cell%20Companies%20Act%2c%20No.%2037%20of%201999.pdf"}
62
+ {"key": "8156f1c219ad7640", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pr/PROTECTION%20OF%20HUMAN%20RIGHTS%20ACT%2c%20No.%2019%20of%201998.pdf", "title": "PROTECTION OF HUMAN RIGHTS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Protection%20of%20Human%20Rights%20Act%2c%20No.%2019%20of%201998.pdf"}
63
+ {"key": "2e39e544a90600e6", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pu/PubicDebtManagementAct-I9.pdf", "title": "PUBLIC DEBT MANAGEMENT ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Public%20Debt%20Management%20Act%2c%20No.%205%20of%202008.pdf"}
64
+ {"key": "b96c6bdf654e643b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pu/PublicProcurementAct-I9.pdf", "title": "PUBLIC PROCUREMENT ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Public%20Procurement%20Act%2c%20No.%2033%20of%202006.pdf"}
65
+ {"key": "97bd552d14a55b15", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/RECOVERY%20OF%20STATE%20DEBTS%20ACT%2c%20Cap%20137.pdf", "title": "RECOVERY OF STATE DEBTS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/Recovery%20of%20State%20Debts%20Act%2c%20Cap.%20137.pdf"}
66
+ {"key": "f1146d62c347e574", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/REGISTRAR-GENERAL%20ACT%2c%20Cap%20340.pdf", "title": "REGISTRAR-GENERAL ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/Registrar-General%20Act%2c%20Cap.%20340.pdf"}
67
+ {"key": "e3a43edd98e38bdb", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/Registration%20of%20Associations%20Act-I9.pdf", "title": "REGISTRATION OF ASSOCIATIONS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/R/Re/Registration%20of%20Associations%20Act%2c%20No.%2035%20of%201978.pdf"}
68
+ {"key": "04245d19f87d727d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Sa/SaleofImmovablePropertyActCap202.pdf", "title": "SALE OF IMMOVABLE PROPERTY ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Sa/Sale%20of%20Immovable%20Property%20Act%2c%20Cap.%20202.pdf"}
69
+ {"key": "4f14b761caf74621", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/SECURITIESCENTRALDEPOSITORYCLEARINGANDSETTLEMENTACTNo30of1996.pdf", "title": "SECURITIES (CENTRAL DEPOSITORY, CLEARING AND SETTLEMENT) ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/Securities%20%28Central%20Depository%2c%20Clearing%20and%20Settlement%29%20Act%2c%20No.%2030%20of%201996.pdf"}
70
+ {"key": "fbd029c7796f7670", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/Securities%20ActNo22of2005.pdf", "title": "SECURITIES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/Securities%20Act%2c%20No.%2022%20of%202005.pdf"}
71
+ {"key": "c8749ee20c117cc1", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/SEEDSACTNo10of2013.pdf", "title": "SEEDS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Se/Seeds%20Act%2c%20No.%2010%20of%202013.pdf"}
72
+ {"key": "415d171cfbe0fb54", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/So/SocialAidActI9.pdf", "title": "SOCIAL AID ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/So/Social%20Aid%20Act%2c%20No.%202%20of%201983.pdf"}
73
+ {"key": "8b344b86a568c3b8", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/SportsActI9.pdf", "title": "SPORTS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Sports%20Act%2c%20No.%2035%20of%202016.pdf"}
74
+ {"key": "c680a70c690e1ffe", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/STAMPDUTYACTNo37of1990.pdf", "title": "STAMP DUTY ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/Stamp%20Duty%20Act%2c%20No.%2037%20of%201990.pdf"}
75
+ {"key": "7bbbeb4490e0223e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/StateLandsActI9.pdf", "title": "STATE LANDS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/State%20Lands%20Act%2c%20Cap.%20224.pdf"}
76
+ {"key": "1b4ffe08c7aa1232", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/StateTradingCorporationActI9.pdf", "title": "STATE TRADING CORPORATION ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/State%20Trading%20Corporation%20Act%2c%20No.%2024%20of%201982.pdf"}
77
+ {"key": "d7410ba50c1ddf6c", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/STATISTICSACTNo38of2000.pdf", "title": "STATISTICS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/Statistics%20Act%2c%20No.%2038%20of%202000.pdf"}
78
+ {"key": "1e15f5acab1be0e1", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/StatutoryBodiesAccountsandAuditActI9.pdf", "title": "STATUTORY BODIES (ACCOUNTS AND AUDIT) ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/St/Statutory%20Bodies%20%28Accounts%20and%20Audit%29%20Act%2c%20No.%202%20of%201972.pdf"}
79
+ {"key": "bdab20ac1e44d8d5", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Su/SugarIndustryEfficiencyActI9.pdf", "title": "SUGAR INDUSTRY EFFICIENCY ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Su/Sugar%20Industry%20Efficiency%20Act%2c%20No.%2020%20of%202001.pdf"}
80
+ {"key": "f7299c8a87288e13", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Su/SugarInsuranceFundActI9.pdf", "title": "SUGAR INSURANCE FUND ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/S/Su/Sugar%20Insurance%20Fund%20Act%2c%20No.%204%20of%201974.pdf"}
81
+ {"key": "9520bccb1e5dd83c", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/T/TOWNANDCOUNTRYPLANNINGACTNo6of1954.pdf", "title": "TOWN AND COUNTRY PLANNING ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/T/Town%20and%20Country%20Planning%20Act%2c%20No.%206%20of%201954.pdf"}
82
+ {"key": "0c420dab59539e0b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/T/Tr/TranscriptionandMortgageActI9.pdf", "title": "TRANSCRIPTION AND MORTGAGE ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/T/Transcription%20and%20Mortgage%20Act%2c%20Cap.%20417.pdf"}
83
+ {"key": "b0a30ac1be59035d", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/U/Un/UNIVERSIT%c3%89DESMASCAREIGNESACTNo4of2012.pdf", "title": "UNIVERSITÉ DES MASCAREIGNES ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/U/Universite%20Des%20Mascareignes%20Act%2c%20No.%204%20of%202012.pdf"}
84
+ {"key": "5e0dff6a7e206d4b", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/U/Un/UNIVERSITYOFTECHNOLOGYMAURITIUSACTNo2of2000.pdf", "title": "UNIVERSITY OF TECHNOLOGY, MAURITIUS ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/U/University%20of%20Technology%2c%20Mauritius%20Act%2c%20No.%202%20of%202000.pdf"}
85
+ {"key": "c58d8dbe0b8b9ae0", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/V/ValueAddedTaxActI9.pdf", "title": "VALUE ADDED TAX ACT", "reason": "duplicate_act_in_batch", "kept_url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/V/Value%20Added%20Tax%20Act%2c%20No.%202%20of%201998.pdf"}
86
+ {"key": "f28b6f88f200be90", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/Acquisitive%20Prescription%20Act%2c%20No.%2013%20of%202018.pdf", "title": "ACQUISITIVE PRESCRIPTION ACT, NO. 13 of 2018", "reason": "duplicate_of_tip", "tip_id": "mu-cc-f1cdbab51145f4"}
87
+ {"key": "b4083d401aab3291", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/A/APPROPRIATIONACT.pdf", "title": "APPROPRIATION ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-2c2bee3bfe9bf2"}
88
+ {"key": "b7d149af2256fa4e", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Chemical%20Weapons%20Convention%20Act%2c%20No.%203%20of%202003.pdf", "title": "CHEMICAL WEAPONS CONVENTION ACT, NO 3 OF 2003", "reason": "duplicate_of_tip", "tip_id": "mu-cc-1e9016b31876e1"}
89
+ {"key": "894fd81935047ab8", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/C/Co/COMBATING%20OF%20TRAFFICKING%20IN%20PERSONS%20ACT.pdf", "title": "COMBATING OF TRAFFICKING IN PERSONS ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-7e3f590586f3e9"}
90
+ {"key": "1f9e0d95b59228b9", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/I/Immigration%20Act-I9.pdf", "title": "IMMIGRATION ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-7ab575069176d2"}
91
+ {"key": "8803edf731ddb37f", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/M/MUTUAL%20ASSISTANCE%20IN%20CRIMINAL%20AND%20RELATED%20MATTERS%20ACT,%20No%2035%20of%202003.pdf", "title": "MUTUAL ASSISTANCE IN CRIMINAL AND RELATED MATTERS ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-fb48478a44a181"}
92
+ {"key": "b19330567869eab3", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/O/OFFICIAL%20SECRETS%20ACT,%20No%2013%20of%201972.pdf", "title": "OFFICIAL SECRETS ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-e451de3316f33c"}
93
+ {"key": "88ad8c36b0d31567", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Public%20Debt%20Management%20Act%2c%20No.%205%20of%202008.pdf", "title": "PUBLIC DEBT MANAGEMENT ACT, NO 5 OF 2008", "reason": "duplicate_of_tip", "tip_id": "mu-cc-2b68bfa6dd3db2"}
94
+ {"key": "1feff0839a16f7bf", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Pu/PublicOfficersProtectionAct-I9.pdf", "title": "PUBLIC OFFICERS’ PROTECTION ACT", "reason": "duplicate_of_tip", "tip_id": "mu-cc-d0c62feb8faaa7"}
95
+ {"key": "cbbd7cff752a0b89", "url": "https://attorneygeneral.govmu.org/Documents/Laws%20of%20Mauritius/A-Z%20Acts/P/Public%20Procurement%20Act%2c%20No.%2033%20of%202006.pdf", "title": "PUBLIC PROCUREMENT ACT, NO 33 OF 2006", "reason": "duplicate_of_tip", "tip_id": "mu-cc-699b9cfdc66abf"}
manifests/mu_b1_pii_scan.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "new_fail": 0,
3
+ "new_hits": []
4
+ }
manifests/mu_b1_summary.json ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "batch": "mu_b1",
3
+ "repo": "endomorphosis/ipfs_mauritius_laws",
4
+ "mode": "append",
5
+ "parent": "80f8c63175886c85a94669f825086cee6c322009",
6
+ "tip_files": [
7
+ ".gitattributes",
8
+ "MANIFEST.md",
9
+ "README.md",
10
+ "data/articles.parquet",
11
+ "data/laws.parquet",
12
+ "scrapers/archive_fallbacks.py",
13
+ "scrapers/collect_mu.py",
14
+ "scrapers/common.py",
15
+ "scrapers/pdf_extract_lib.py",
16
+ "scrapers/world_lib.py"
17
+ ],
18
+ "tip_laws": 197,
19
+ "tip_articles": 5934,
20
+ "new_laws": 526,
21
+ "new_articles": 16881,
22
+ "laws_rows": 723,
23
+ "articles_rows": 22815,
24
+ "languages": {
25
+ "en": 519,
26
+ "fr": 7
27
+ },
28
+ "drops": {
29
+ "empty_text": 36,
30
+ "duplicate_act_in_batch": 49,
31
+ "duplicate_of_tip": 10
32
+ },
33
+ "whole_text_fallback": 36,
34
+ "degraded": [],
35
+ "ocr_used": [
36
+ {
37
+ "id": "mu-ago-act-31-1995-abolition-of-death-penalty-act",
38
+ "title": "ABOLITION OF DEATH PENALTY ACT",
39
+ "text_source": "ocr",
40
+ "garble": 0.0,
41
+ "mean_conf": 94.15,
42
+ "sections": 3,
43
+ "whole": false,
44
+ "status": "ok"
45
+ },
46
+ {
47
+ "id": "mu-ago-act-7-1981-bonds-act",
48
+ "title": "BONDS ACT",
49
+ "text_source": "ocr",
50
+ "garble": 0.0,
51
+ "mean_conf": 95.48,
52
+ "sections": 3,
53
+ "whole": false,
54
+ "status": "ok"
55
+ },
56
+ {
57
+ "id": "mu-ago-act-26-1981-convention-on-social-security-act",
58
+ "title": "CONVENTION ON SOCIAL SECURITY ACT",
59
+ "text_source": "ocr",
60
+ "garble": 0.0,
61
+ "mean_conf": 93.59,
62
+ "sections": 4,
63
+ "whole": false,
64
+ "status": "ok"
65
+ },
66
+ {
67
+ "id": "mu-ago-cap-171-deposit-of-powers-of-attorney-act",
68
+ "title": "DEPOSIT OF POWERS OF ATTORNEY ACT",
69
+ "text_source": "ocr",
70
+ "garble": 0.0,
71
+ "mean_conf": 95.69,
72
+ "sections": 4,
73
+ "whole": false,
74
+ "status": "ok"
75
+ },
76
+ {
77
+ "id": "mu-ago-cap-35-gazette-charges-act",
78
+ "title": "GAZETTE (CHARGES) ACT",
79
+ "text_source": "ocr",
80
+ "garble": 0.0,
81
+ "mean_conf": 94.19,
82
+ "sections": 3,
83
+ "whole": false,
84
+ "status": "ok"
85
+ },
86
+ {
87
+ "id": "mu-ago-cap-36-gazette-privilege-act",
88
+ "title": "GAZETTE (PRIVILEGE) ACT",
89
+ "text_source": "ocr",
90
+ "garble": 0.0,
91
+ "mean_conf": 92.41,
92
+ "sections": 3,
93
+ "whole": false,
94
+ "status": "ok"
95
+ },
96
+ {
97
+ "id": "mu-ago-cap-356-government-teachers-benevolent-fund-act",
98
+ "title": "GOVERNMENT TEACHERS’ BENEVOLENT FUND ACT",
99
+ "text_source": "ocr",
100
+ "garble": 0.0,
101
+ "mean_conf": 94.65,
102
+ "sections": 2,
103
+ "whole": false,
104
+ "status": "ok"
105
+ },
106
+ {
107
+ "id": "mu-ago-act-1-1980-hotel-and-catering-training-school-levy-of-fees-act",
108
+ "title": "HOTEL AND CATERING TRAINING SCHOOL (LEVY OF FEES) ACT",
109
+ "text_source": "ocr",
110
+ "garble": 0.0,
111
+ "mean_conf": 93.16,
112
+ "sections": 3,
113
+ "whole": false,
114
+ "status": "ok"
115
+ },
116
+ {
117
+ "id": "mu-ago-act-47-1973-judicial-and-legal-service-commission-and-disciplined-forces-service-c",
118
+ "title": "JUDICIAL AND LEGAL SERVICE COMMISSION AND DISCIPLINED FORCES SERVICE COMMISSION (ALLOWANCES) ACT",
119
+ "text_source": "ocr",
120
+ "garble": 0.0,
121
+ "mean_conf": 95.13,
122
+ "sections": 2,
123
+ "whole": false,
124
+ "status": "ok"
125
+ },
126
+ {
127
+ "id": "mu-ago-act-31-2008-offices-of-minister-act",
128
+ "title": "OFFICES OF MINISTER ACT",
129
+ "text_source": "ocr",
130
+ "garble": 0.0,
131
+ "mean_conf": 94.66,
132
+ "sections": 2,
133
+ "whole": false,
134
+ "status": "ok"
135
+ },
136
+ {
137
+ "id": "mu-ago-cap-407-pawnbrokers-act",
138
+ "title": "PAWNBROKERS ACT",
139
+ "text_source": "ocr",
140
+ "garble": 0.0,
141
+ "mean_conf": 95.03,
142
+ "sections": 1,
143
+ "whole": true,
144
+ "status": "ok"
145
+ },
146
+ {
147
+ "id": "mu-ago-act-25-2016-police-membership-of-trade-union-act",
148
+ "title": "POLICE (MEMBERSHIP OF TRADE UNION) ACT",
149
+ "text_source": "ocr",
150
+ "garble": 0.0,
151
+ "mean_conf": 93.33,
152
+ "sections": 3,
153
+ "whole": false,
154
+ "status": "ok"
155
+ },
156
+ {
157
+ "id": "mu-ago-act-41-1969-prescription-of-landed-property-act",
158
+ "title": "PRESCRIPTION OF LANDED PROPERTY ACT",
159
+ "text_source": "ocr",
160
+ "garble": 0.0,
161
+ "mean_conf": 94.57,
162
+ "sections": 2,
163
+ "whole": false,
164
+ "status": "ok"
165
+ },
166
+ {
167
+ "id": "mu-ago-act-3-2002-prevention-of-terrorism-denial-of-bail-act",
168
+ "title": "PREVENTION OF TERRORISM (DENIAL OF BAIL) ACT",
169
+ "text_source": "ocr",
170
+ "garble": 0.0,
171
+ "mean_conf": 93.86,
172
+ "sections": 4,
173
+ "whole": false,
174
+ "status": "ok"
175
+ },
176
+ {
177
+ "id": "mu-ago-cap-377-prison-and-correctional-youth-centre-officers-benefit-fund-act",
178
+ "title": "PRISON AND CORRECTIONAL YOUTH CENTRE OFFICERS’ BENEFIT FUND ACT",
179
+ "text_source": "ocr",
180
+ "garble": 0.0,
181
+ "mean_conf": 92.45,
182
+ "sections": 3,
183
+ "whole": false,
184
+ "status": "ok"
185
+ },
186
+ {
187
+ "id": "mu-ago-act-39-1948-public-officers-fees-act",
188
+ "title": "PUBLIC OFFICERS’ FEES ACT",
189
+ "text_source": "ocr",
190
+ "garble": 0.0,
191
+ "mean_conf": 94.08,
192
+ "sections": 2,
193
+ "whole": false,
194
+ "status": "ok"
195
+ },
196
+ {
197
+ "id": "mu-ago-cap-340-registrar-general-act-cap-340",
198
+ "title": "REGISTRAR-GENERAL ACT, CAP. 340",
199
+ "text_source": "ocr",
200
+ "garble": 0.0,
201
+ "mean_conf": 94.7,
202
+ "sections": 2,
203
+ "whole": false,
204
+ "status": "ok"
205
+ },
206
+ {
207
+ "id": "mu-ago-act-49-1973-reprint-of-laws-act",
208
+ "title": "REPRINT OF LAWS ACT",
209
+ "text_source": "ocr",
210
+ "garble": 0.0,
211
+ "mean_conf": 94.28,
212
+ "sections": 6,
213
+ "whole": false,
214
+ "status": "ok"
215
+ },
216
+ {
217
+ "id": "mu-ago-cap-219-safety-of-dockers-act",
218
+ "title": "SAFETY OF DOCKERS ACT",
219
+ "text_source": "ocr",
220
+ "garble": 0.0,
221
+ "mean_conf": 94.42,
222
+ "sections": 3,
223
+ "whole": false,
224
+ "status": "ok"
225
+ },
226
+ {
227
+ "id": "mu-ago-act-23-1975-students-relief-fund-act",
228
+ "title": "STUDENTS’ RELIEF FUND ACT",
229
+ "text_source": "ocr",
230
+ "garble": 0.0,
231
+ "mean_conf": 94.51,
232
+ "sections": 6,
233
+ "whole": false,
234
+ "status": "ok"
235
+ },
236
+ {
237
+ "id": "mu-ago-act-63-1973-sugar-brokerage-tax-act",
238
+ "title": "SUGAR BROKERAGE TAX ACT",
239
+ "text_source": "ocr",
240
+ "garble": 0.0,
241
+ "mean_conf": 94.64,
242
+ "sections": 2,
243
+ "whole": false,
244
+ "status": "ok"
245
+ },
246
+ {
247
+ "id": "mu-ago-supplementary-appropriation-act",
248
+ "title": "SUPPLEMENTARY APPROPRIATION ACT",
249
+ "text_source": "ocr",
250
+ "garble": 0.0,
251
+ "mean_conf": 92.42,
252
+ "sections": 1,
253
+ "whole": true,
254
+ "status": "ok"
255
+ },
256
+ {
257
+ "id": "mu-ago-act-4-1962-technical-co-operation-agreements-immunities-and-privileges-act",
258
+ "title": "TECHNICAL CO-OPERATION AGREEMENTS (IMMUNITIES AND PRIVILEGES) ACT",
259
+ "text_source": "ocr",
260
+ "garble": 0.0,
261
+ "mean_conf": 94.76,
262
+ "sections": 2,
263
+ "whole": false,
264
+ "status": "ok"
265
+ },
266
+ {
267
+ "id": "mu-ago-act-16-1968-united-nations-act",
268
+ "title": "UNITED NATIONS ACT",
269
+ "text_source": "ocr",
270
+ "garble": 0.0,
271
+ "mean_conf": 94.91,
272
+ "sections": 3,
273
+ "whole": false,
274
+ "status": "ok"
275
+ }
276
+ ],
277
+ "codec": "ZSTD",
278
+ "row_groups": 1,
279
+ "heading_only_dropped": 1036,
280
+ "repealed_placeholders": 455,
281
+ "schedules": 379,
282
+ "number_mismatches": 10,
283
+ "webmail_redactions": 0,
284
+ "license_paraphrase": "Consolidated Acts of Mauritius as published by the Attorney General's Office (attorneygeneral.govmu.org). Described, not quoted: the site's Term of Use lets people make personal copies and printouts of the legislation under the Copyright Act, but publishing, disseminating or incorporating it for commercial use needs the prior approval of the Solicitor General; the site also says that only the LexisNexis 2016 Revised Laws of Mauritius (with their supplements) are the authoritative text, so these copies are for information only. Terms: https://attorneygeneral.govmu.org/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx . Not legal advice.",
285
+ "terms_url": "https://attorneygeneral.govmu.org/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx",
286
+ "staged_at": "2026-10-25T02:41:58Z"
287
+ }
manifests/pii_scan_notes.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # PII scan notes (batch mu_b1)
2
+
3
+ - Scope: every string column of the 526 new law rows and 16881 new article rows.
4
+ - FAIL hits in new rows: 0.
5
+ - WARN hits: {}.
6
+
7
+ WARN hits are telephone/fax numbers printed in the Acts themselves (office numbers of public bodies, forms) or P.O. Box addresses of institutions; they are official texts and are kept. Values are not reproduced here.
8
+
9
+ Rows with WARN hits:
10
+
manifests/webmail_redactions.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "placeholder": "[redacted-webmail]",
3
+ "total": 0,
4
+ "laws": [],
5
+ "note": "free-webmail addresses (standard, typo-domain, truncated, spaced, line-split) redacted in laws.text before splitting, so article slices inherit it; offsets refer to the stored text; no values recorded"
6
+ }
scrapers/mu_b1/README.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scrapers/mu_b1 — Mauritius AGO consolidated Acts, batch mu_b1 (ipfs_mauritius_laws)
2
+
3
+ Self-contained bundle that produced the mu_b1 append to the Hugging Face dataset
4
+ `endomorphosis/ipfs_mauritius_laws`. Nothing here imports from outside this directory
5
+ (the earlier tip scrapers in `scrapers/*.py` are left untouched and are not needed).
6
+
7
+ ## Source
8
+ - Official only: Attorney General's Office, Republic of Mauritius,
9
+ https://attorneygeneral.govmu.org/ — "Laws of Mauritius" A–Z consolidated Acts
10
+ (index page plus one sub-page per letter group; PDFs under /Documents/Laws of Mauritius/).
11
+ - Terms of use: https://attorneygeneral.govmu.org/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx
12
+ (see the dataset README for our paraphrase; the site notes that the authoritative
13
+ printed version is the LexisNexis-published edition, so this text is unofficial).
14
+ - No archives (no Wayback / Common Crawl / archive.is), no logins, forms or challenge bypass.
15
+
16
+ ## Files
17
+ | file | role |
18
+ |---|---|
19
+ | pipeline_mu.sh | orchestrator: gates, slot, catalog, fetch, extract, OCR, stage, verify |
20
+ | collect_mu.py | catalog + PDF fetch (one request in flight, pacing max(8 s, Crawl-Delay)) |
21
+ | mu_net.py | HTTP layer: robots_guard on every hop/redirect, challenge detection, requests.jsonl |
22
+ | robots_guard.py | shared fleet robots guard (see "Changed sha" below) |
23
+ | challenge_detector_v2.py | shared challenge/captcha detector |
24
+ | br_waiting.sh | shared fleet helper: yields when the Americas BR lane is waiting |
25
+ | extract_mu.py | pdftotext -layout per page; flags PDFs without a text layer |
26
+ | ocr_mu.py | tesseract (system tessdata, self-test) only for PDFs without a text layer |
27
+ | split_mu.py, classify_mu.py, articles_mu.py | section splitter, repeal-placeholder tagging, verbatim slices |
28
+ | validate_split_mu.py | split check on the first 10 PDFs before the full fetch |
29
+ | webmail_mu.py, pii_scan_mu.py | free-webmail redaction and PII scan |
30
+ | stage_mu.py, readme_mu.py, finalize_mu.py | dedupe against the Hub tip, build parquet + README/MANIFEST/manifests |
31
+ | verify_mu.py | all checks (substring gate, bounds, schema parity, secret scans, YAML, SHA256SUMS) |
32
+ | requirements.txt | pinned Python dependencies |
33
+
34
+ ## How to run
35
+ ```bash
36
+ pip install -r requirements.txt # plus poppler-utils, tesseract-ocr (eng), ripgrep
37
+ export MU_WORK=$PWD/work # all caches, logs and the pack go here
38
+ bash pipeline_mu.sh # resumable; re-run after any stop
39
+ tail -f "$MU_WORK/status.txt" # PIPELINE_DONE / HARD_STOP / PARKED / *_FAIL
40
+ ```
41
+ Environment variables:
42
+ - `MU_WORK` – work directory (default `.`); `MU_SHM` – lock dir (default /dev/shm).
43
+ - `BRW_BR_LOGS`, `BRW_LOCKS` – read by br_waiting.sh to locate the BR lane logs/locks
44
+ (if absent the helper reports "not waiting").
45
+ - `LEGAL_CORPORA_ROOT` – set by mu_net.py to `$MU_WORK/legal-corpora` for robots caches.
46
+
47
+ Outputs: `$MU_WORK/cache/*.pdf` (raw PDFs, kept), `requests.jsonl` (every request),
48
+ `texts.jsonl`, and the pack in `$MU_WORK/hf_mu_b1/ipfs_mauritius_laws/`. The pipeline never uploads.
49
+
50
+ ## Stop rules
51
+ 403, 429, 503, a challenge/captcha (including on robots.txt) or a certificate-verification error
52
+ stops the lane at once. A transport SSLError/connection reset gets one retry after 120 s;
53
+ a second consecutive failure or 3 transport errors in total stops the run.
54
+
55
+ ## Changed sha
56
+ `robots_guard.py` differs from the fleet original (sha256 fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542)
57
+ only in its default ROOT ("legal-corpora", relative, instead of an absolute fleet path).
58
+ The bundled sha256 of every file is recorded in `manifests/mu_b1_code.json` and `SHA256SUMS`.
scrapers/mu_b1/articles_mu.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Article rows for one MU consolidated Act (batch mu_b1), with the verbatim-slice gate.
3
+ * Sections come from split_mu.split_offsets(): each article text is law_text[start:end], a raw verbatim slice of the STORED law
4
+ text (no reflow); offsets ascending, non-overlapping, kept in metadata_json (char_start / char_end).
5
+ * Schedules: a stand-alone capitals line '[FIRST ...] SCHEDULE' inside a section ends that section; the schedule becomes its own
6
+ article (-sch / -schN, title 'Schedule'), still a raw slice.
7
+ * classify_mu: heading-only rows (arrangement-of-sections entries with no body) are DROPPED and returned for known_gaps; repeal
8
+ placeholders ('Repealed by ...', 'Omitted', MU 'N. —' dashes) are kept with metadata_json.body_status = 'repealed_placeholder'.
9
+ * Dominant-article gate: a law with >= 5 articles where one article holds > 60 % of the article characters is demoted to one
10
+ whole-text article (reason dominant_article, listed in known_gaps).
11
+ * Whole-text fallback (no numbered sections): one article = law_text.strip() (also a raw slice).
12
+ * Ids: <law id>-s<n> / -sp<part>-<n>, assigned over ALL detected sections before dropping; clashes -> -dupN.
13
+ gate(law_text, arts) returns the list of substring / order violations (must be empty)."""
14
+ import json, os, re, sys
15
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
16
+ import split_mu as S, classify_mu as C
17
+ SCH = re.compile(r"(?m)^[ \t]*(?:(?:FIRST|SECOND|THIRD|FOURTH|FIFTH|SIXTH|SEVENTH|EIGHTH|NINTH|TENTH|ELEVENTH|TWELFTH)\s+)?SCHEDULE(?:\s+[IVXLC\d]+)?[ \t]*$")
18
+ NUMH = re.compile(r"^\s*\d{1,3}[A-Z]{0,2}\.\s+")
19
+ def _heading(sec_text, prev_head):
20
+ first = NUMH.sub("", sec_text.split("\n", 1)[0]).strip()
21
+ if first and len(first) <= 80 and not re.search(r"[.;:,—–-]\s*$", first) and first[:1].isupper() and "\n" in sec_text: return first
22
+ return prev_head
23
+ def _cut_schedules(text, secs):
24
+ out = []
25
+ for s in secs:
26
+ body = text[s["start"]:s["end"]]
27
+ m = None
28
+ for mm in SCH.finditer(body):
29
+ if mm.start() > 0: m = mm; break
30
+ if not m: out.append(s); continue
31
+ cut = s["start"] + m.start() + (len(m.group(0)) - len(m.group(0).lstrip()))
32
+ en1 = cut
33
+ while en1 > s["start"] and text[en1 - 1].isspace(): en1 -= 1
34
+ a = dict(s, end=en1, text=text[s["start"]:en1])
35
+ b = {"num": "sch", "part": s["part"], "part_title": s["part_title"], "heading": "Schedule", "start": cut, "end": s["end"],
36
+ "text": text[cut:s["end"]], "schedule": True}
37
+ out += [a, b]
38
+ return out
39
+ def build(lid, text, offid, src_url, jur=None, batch="mu_b1"):
40
+ secs = S.split_offsets(text) if text else []
41
+ secs = _cut_schedules(text, secs) if secs else []
42
+ for s in secs:
43
+ if s.get("schedule"): s["body_status"] = "body"
44
+ nonsch = [s for s in secs if not s.get("schedule")]
45
+ C.classify(nonsch)
46
+ whole_reason = None if secs else "no_numbered_sections"
47
+ if secs:
48
+ kept = [s for s in secs if s["body_status"] != "heading_only"]
49
+ tot = sum(s["end"] - s["start"] for s in kept) or 1
50
+ if len(kept) >= 5 and max(s["end"] - s["start"] for s in kept) > 0.6 * tot: whole_reason = "dominant_article"
51
+ if not kept: whole_reason = "only_heading_rows"
52
+ whole = whole_reason is not None
53
+ if whole:
54
+ st = len(text) - len(text.lstrip()); en = len(text.rstrip())
55
+ secs = [{"num": "1", "part": 1, "part_title": "", "heading": "", "start": st, "end": en, "text": text[st:en], "body_status": "body"}]
56
+ arts, dropped, aids, prev_head = [], [], set(), ""
57
+ for s in secs:
58
+ n = s["num"] if s["part"] == 1 else f"p{s['part']}-{s['num']}"
59
+ aid = f"{lid}-s{n}" if n != "sch" and not n.endswith("-sch") else f"{lid}-{n.replace('-sch', '-sch') if s['part'] > 1 else 'sch'}"
60
+ base, k = aid, 1
61
+ while aid in aids: k += 1; aid = f"{base}-dup{k}" if not s.get("schedule") else f"{base}{k}"
62
+ aids.add(aid)
63
+ if s["body_status"] == "heading_only":
64
+ dropped.append({"law_id": lid, "article_id": aid, "article_number": n, "part": s["part"], "char_start": s["start"], "char_end": s["end"],
65
+ "reason": "heading_only_toc_entry", "heading_text": s["text"][:200]}); continue
66
+ if whole: label, head = "Whole text", ""
67
+ elif s.get("schedule"): label, head = "Schedule", "Schedule"
68
+ else:
69
+ head = _heading(s["text"], s.get("heading", "")) if not whole else ""
70
+ label = f"Section {s['num']}" + (f" ({head})" if head else "")
71
+ if s["part"] > 1 and s["part_title"] and not whole: label = f"{s['part_title']} — {label}"
72
+ md = {"batch": batch, "law_identifier": lid, "part": s["part"], "part_title": s["part_title"], "heading": head,
73
+ "whole_text_fallback": whole, "whole_text_reason": whole_reason, "char_start": s["start"], "char_end": s["end"],
74
+ "body_status": s["body_status"], "schedule": bool(s.get("schedule"))}
75
+ arts.append({"law_id": lid, "id": aid, "title": label, "text": text[s["start"]:s["end"]], "source_url": src_url,
76
+ "document_number": offid, "article_number": n, "record_type": "article",
77
+ "metadata_json": json.dumps(md, ensure_ascii=False)})
78
+ return arts, dropped, whole_reason
79
+ def gate(text, arts):
80
+ bad, last = [], -1
81
+ for a in arts:
82
+ md = json.loads(a["metadata_json"]); st, en = md.get("char_start"), md.get("char_end")
83
+ if st is None or text[st:en] != a["text"]: bad.append({"id": a["id"], "why": "slice_mismatch"}); continue
84
+ if a["text"] not in text: bad.append({"id": a["id"], "why": "not_substring"}); continue
85
+ if st < last: bad.append({"id": a["id"], "why": "offsets_not_ascending"})
86
+ last = en
87
+ return bad
88
+ def dominant(arts):
89
+ if len(arts) < 5: return False
90
+ L = [len(a["text"]) for a in arts]; return max(L) > 0.6 * (sum(L) or 1)
scrapers/mu_b1/br_waiting.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Exit 0 if an Americas BR job is alive and WAITING for a runner slot (we must yield), 1 otherwise. Read-only.
3
+ # BR job = the BR runner pid in americas/br/logs/b*_runner.pid, or any process running collect_br_sigpub / an americas
4
+ # requeue / run_slot_job / run_br* script (br_stage_chain.py only stages/prunes and takes no slot -> ignored).
5
+ # Waiting = alive and it is neither a slot-lock holder nor an ancestor of one (a BR wrapper whose child holds a slot runs).
6
+ BRL=${BRW_BR_LOGS:-} # fleet-local dir holding Americas BR b*_runner.pid files; unset = check processes only
7
+ LOCKS=${BRW_LOCKS:-/dev/shm/muni_runner.lock /dev/shm/muni_runner.slot2.lock /dev/shm/muni_runner.slot3.lock}
8
+ cand=""
9
+ for f in ${BRL:+$BRL/b*_runner.pid}; do
10
+ [ -f "$f" ] || continue; p=$(tr -dc 0-9 < "$f"); [ -n "$p" ] && kill -0 "$p" 2>/dev/null && cand="$cand $p"
11
+ done
12
+ cand="$cand $(pgrep -f 'collect_br_sigpub|americas/[^ ]*(requeue|run_slot_job|run_br)|run_br_|br_pack4' 2>/dev/null | tr '\n' ' ')"
13
+ pids=""
14
+ for p in $cand; do
15
+ [ "$p" = "$$" ] && continue
16
+ c=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null) || continue
17
+ case "$c" in *br_stage_chain*|*br_waiting*|*pgrep*) continue;; esac
18
+ pids="$pids $p"
19
+ done
20
+ [ -z "$pids" ] && exit 1
21
+ fam=" "
22
+ for h in $(fuser $LOCKS 2>/dev/null); do
23
+ x=$h
24
+ while [ -n "$x" ] && [ "$x" -gt 1 ] 2>/dev/null; do fam="$fam$x "; x=$(awk '{print $4}' /proc/$x/stat 2>/dev/null); done
25
+ done
26
+ for p in $pids; do
27
+ case "$fam" in *" $p "*) continue;; esac
28
+ echo "BR waiting: pid $p $(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null | cut -c1-120)"; exit 0
29
+ done
30
+ exit 1
scrapers/mu_b1/challenge_detector_v2.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ARMED in collect_gh_ir.py 2026-10-14 ~21:50 PT (CoS GO 21:39 PT; re-read showed passive-only markers). Narrowed challenge detector for GH ir_b1 -- written 2026-10-14 after the 21:29:39 PT hard stop.
3
+
4
+ Why: the v1 CHAL regex in collect_gh_ir.py hard-stops on ANY bare 'recaptcha' / 'hcaptcha' substring anywhere in the
5
+ first 400 KB. repository.parliament.gh is a DSpace 7 (Angular SSR) site whose ~499 KB home page carries inline config /
6
+ cookie-consent / i18n state; DSpace 7 ships a 'google-recaptcha' cookie-consent service and registration-verification
7
+ config, so a bare-word hit there is passive configuration, not an interactive gate (same class as KZN's .wpcf7-recaptcha).
8
+
9
+ Design (fail closed by default):
10
+ STRONG -> hard stop, anywhere in the body: interstitial titles, Cloudflare/Turnstile/Sucuri/Incapsula/DataDome/
11
+ PerimeterX/AWS-WAF/DDoS-Guard/Imunify/SG markers, and *rendered* captcha widgets (g-recaptcha / h-captcha /
12
+ cf-turnstile elements with a data-sitekey, or the captcha api.js loaded in a small page).
13
+ WEAK -> bare recaptcha/hcaptcha/captcha words. Hard stop ONLY if the page does not look like a real DSpace page
14
+ (no DSpace generator/app markers) or is small (< 60 KB, typical of an interstitial). Otherwise log WEAK_MARKER
15
+ and continue.
16
+ Header checks (cf-mitigated, 403/429/503) stay in the collector unchanged.
17
+ Integration (when CoS arms it): in collect_gh_ir.get() replace `m = CHAL.search(txt[:400000])` with
18
+ `v, m = classify(txt); if v == "challenge": ...hard stop...; elif v == "weak": status(f"WEAK_MARKER ...")`.
19
+ """
20
+ from __future__ import annotations
21
+ import re
22
+
23
+ STRONG = re.compile(
24
+ r"<title[^>]*>\s*(?:Just a moment|Attention Required|Access denied|Please wait|One more step|DDoS-Guard|"
25
+ r"Checking your browser|Security check|Human verification)|"
26
+ r"_cf_chl_opt|/cdn-cgi/challenge-platform/|cf-browser-verification|cf_chl_|"
27
+ r"class=\"[^\"]*\bcf-turnstile\b|challenges\.cloudflare\.com/turnstile|"
28
+ r"checking your browser before accessing|Enable JavaScript and cookies to continue|"
29
+ r"sgcaptcha|ddos-guard\.net|_Incapsula_Resource|incapsula incident|px-captcha|captcha-delivery\.com|"
30
+ r"awswaf|aws-waf-token|imunify360-webshield|sucuri_cloudproxy|"
31
+ r"class=\"[^\"]*\bg-recaptcha\b[^\"]*\"[^>]*data-sitekey|class=\"[^\"]*\bh-captcha\b[^\"]*\"[^>]*data-sitekey",
32
+ re.I)
33
+ WIDGET_JS = re.compile(r"(?:www\.google\.com|www\.recaptcha\.net)/recaptcha/api\.js|hcaptcha\.com/1/api\.js", re.I)
34
+ WEAK = re.compile(r"recaptcha|hcaptcha|captcha|bot-check", re.I)
35
+ DSPACE = re.compile(r"<meta[^>]+name=\"Generator\"[^>]+content=\"DSpace|<ds-app\b|dspace-angular|<ds-root\b|"
36
+ r"/server/api/core/|ds-themed-|dspace-angular-state", re.I)
37
+ SMALL = 60 * 1024
38
+
39
+
40
+ def classify(txt: str, limit: int = 400_000):
41
+ """Return (verdict, match) with verdict in {'challenge', 'weak', 'clean'}; match is an re.Match or None."""
42
+ body = txt[:limit]
43
+ m = STRONG.search(body)
44
+ if m:
45
+ return "challenge", m
46
+ m = WIDGET_JS.search(body)
47
+ if m and len(txt) < SMALL:
48
+ return "challenge", m # captcha api loaded by a small interstitial page
49
+ w = WEAK.search(body)
50
+ if w:
51
+ if len(txt) < SMALL or not DSPACE.search(body):
52
+ return "challenge", w # can't prove it's a real content page -> fail closed
53
+ return "weak", w # passive marker inside a full DSpace page
54
+ return "clean", None
55
+
56
+
57
+ if __name__ == "__main__": # offline self-test only; makes no network requests
58
+ cases = {
59
+ "cf": ("<html><head><title>Just a moment...</title></head><body><script>window._cf_chl_opt={}</script>", "challenge"),
60
+ "turnstile": ("<html><div class=\"cf-turnstile\" data-sitekey=\"x\"></div>" + "x" * 100000, "challenge"),
61
+ "g-widget": ("<html><form><div class=\"g-recaptcha\" data-sitekey=\"k\"></div></form>" + "x" * 100000, "challenge"),
62
+ "dspace-passive": ("<html><head><meta name=\"Generator\" content=\"DSpace 7.6\"></head><ds-app></ds-app>"
63
+ + "x" * 200000 + "{\"name\":\"google-recaptcha\",\"purposes\":[\"registration-password-recovery\"]}", "weak"),
64
+ "small-weak": ("<html><body>please solve the recaptcha</body>", "challenge"),
65
+ "big-nondspace-weak": ("<html>" + "x" * 100000 + "recaptcha", "challenge"),
66
+ "clean": ("<html><meta name=\"Generator\" content=\"DSpace 7\">" + "x" * 100000, "clean"),
67
+ }
68
+ bad = 0
69
+ for k, (t, want) in cases.items():
70
+ v, _ = classify(t); ok = v == want; bad += not ok
71
+ print(f"{'ok ' if ok else 'BAD'} {k}: {v} (want {want})")
72
+ raise SystemExit(1 if bad else 0)
scrapers/mu_b1/classify_mu.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Heading-only / repeal-placeholder classification for split_offsets() sections (fix batch 2026-10-24).
2
+ heading_only: the section's first line is a short heading (<= 80 chars after the number, not a fee line or sentence fragment, no closing . ; : ?) and every further non-blank
3
+ line is an ALL-CAPS header (PART / ORDER / SCHEDULE titles) -- i.e. an arrangement-of-sections / table-of-contents entry with no body.
4
+ repealed_placeholder: a section whose body is only 'Omitted' / 'Repealed ...' / 'Revoked ...' and which is NOT inside a TOC block
5
+ (a part where >= 60 % of >= 3 sections are heading-only or placeholders)."""
6
+ import re
7
+ NUM = re.compile(r"^\s*\d{1,3}[A-Z]{0,2}\.\s*")
8
+ PL = re.compile(r"(?i)^\W*(?:omitted|spent|deleted|(?:repealed|revoked|omitted|deleted|lapsed)\b[^\n]{0,120})\W*$"
9
+ r"|^(?:[–—-]\s*\d{1,3}[A-Z]{0,2}\.?\s*)?[—–-]+\s*$") # MU Revised Laws print a repealed/spent section as 'N. —' or 'N. – M. —'
10
+ def _kind(t):
11
+ ls = t.split("\n"); first = NUM.sub("", ls[0]).strip()
12
+ prose = [l for l in ls[1:] if l.strip() and (l.strip().upper() != l.strip() or not re.search(r"[A-Z]{2}", l))]
13
+ if prose: return "body"
14
+ if PL.match(first): return "placeholder"
15
+ if re.search(r"(?i)\bcited as\b|\bmeans\b|^in th(?:is|ese)\b", first): return "body"
16
+ if re.search(r"£|\d+p\b|\?|\b(?:and|or)\s*$", first) or first[:1].islower(): return "body"
17
+ if len(first) <= 80 and not re.search(r"[.;:?]\s*$", first) and (len(ls) == 1 or not prose): return "heading"
18
+ return "body"
19
+ def classify(secs):
20
+ by = {}
21
+ for s in secs: s["_k"] = _kind(s["text"]); by.setdefault(s["part"], []).append(s["_k"])
22
+ toc = {p for p, ks in by.items() if len(ks) >= 3 and sum(k != "body" for k in ks) >= 0.6 * len(ks)}
23
+ for s in secs:
24
+ k = s.pop("_k")
25
+ s["body_status"] = ("heading_only" if k == "heading" or (k == "placeholder" and s["part"] in toc)
26
+ else "repealed_placeholder" if k == "placeholder" else "body")
27
+ return secs
scrapers/mu_b1/collect_mu.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """MU mu_b1 collector: consolidated Acts ("Acts A-Z", Revised Laws of Mauritius) from the Attorney General's Office site
3
+ https://attorneygeneral.govmu.org (official). Public pages only: no logins, forms, search endpoints or archives.
4
+ Modes:
5
+ --catalog-only fetch the Acts A-Z index, every two-letter sub-page and the Term of Use page -> catalog.json, raw/
6
+ [--max N] fetch the next N (default all) catalog PDFs into cache/<sha256>.pdf (resumable; fetched.jsonl)
7
+ Only PDF links under /Documents/Laws of Mauritius/ on the same host are taken; other hosts are never contacted.
8
+ 300 MB tree cap: PDFs are cached; once the work tree passes 250 MB the PDF of a text-layer document is removed after its text is
9
+ extracted (its sha256 stays in fetched.jsonl). Exit: 0 done, 3 HARD_STOP, 4 MEM_STOP, 5 tree/RSS cap, 2 other error. Env MU_WORK."""
10
+ import argparse, html, json, os, re, sys, threading, time, hashlib
11
+ from urllib.parse import urljoin, urlsplit, unquote, quote
12
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
+ from mu_net import Net, HardStop, Skip
14
+ from extract_mu import extract_one
15
+ W = os.environ.get("MU_WORK", ".")
16
+ BASE = "https://attorneygeneral.govmu.org"
17
+ INDEX = "/Pages/Laws%20of%20Mauritius/A-Z%20Acts/ActsAZ.aspx"
18
+ TERMS = "/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx"
19
+ TREE_CAP = 300 * 1024 * 1024; SOFT = 250 * 1024 * 1024
20
+ ST = os.path.join(W, "status.txt")
21
+ def status(msg):
22
+ with open(ST, "a") as f: f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} COLLECT {msg}\n")
23
+ STOP = {"mem": False}
24
+ def memwatch():
25
+ low = None
26
+ while True:
27
+ kb = int(re.search(r"MemAvailable:\s+(\d+)", open("/proc/meminfo").read()).group(1))
28
+ if kb < 1.5 * 1048576:
29
+ low = low or time.time()
30
+ if time.time() - low >= 15: STOP["mem"] = True; status(f"MEM_STOP mem_kb={kb}"); return
31
+ else: low = None
32
+ time.sleep(3)
33
+ def tree_bytes():
34
+ return sum(os.path.getsize(os.path.join(dp, f)) for dp, _, fs in os.walk(W) for f in fs)
35
+ def rss_mb():
36
+ try: return int(re.search(r"VmRSS:\s+(\d+)", open("/proc/self/status").read()).group(1)) / 1024
37
+ except Exception: return 0
38
+ def norm_url(h):
39
+ u = urljoin(BASE + "/", html.unescape(h).strip())
40
+ return u.replace(" ", "%20") # keep the site's own percent-encoding
41
+ def text_of(t): return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", t))).replace("\u200b", "").strip()
42
+ def parse_index(htm):
43
+ out = []
44
+ for h, t in re.findall(r'<a[^>]+href="([^"#]+)"[^>]*>(.*?)</a>', htm, re.S):
45
+ if re.search(r"/A-Z%20Acts/[A-Z]/[A-Za-z]{1,3}\.aspx$", h) or re.search(r"/A-Z Acts/[A-Z]/[A-Za-z]{1,3}\.aspx$", h):
46
+ u = norm_url(h)
47
+ if u not in out: out.append(u)
48
+ return out
49
+ def parse_sub(htm, page):
50
+ out = []
51
+ for h, t in re.findall(r'<a[^>]+href="([^"#]+?\.pdf)"[^>]*>(.*?)</a>', htm, re.S | re.I):
52
+ u = norm_url(h)
53
+ if urlsplit(u).hostname != urlsplit(BASE).hostname: continue
54
+ if "/Documents/Laws%20of%20Mauritius/" not in u: continue
55
+ out.append({"title": text_of(t), "url": u, "page": page, "file": unquote(u.rsplit("/", 1)[1])})
56
+ return out
57
+ def main():
58
+ ap = argparse.ArgumentParser(); ap.add_argument("--catalog-only", action="store_true"); ap.add_argument("--max", type=int)
59
+ a = ap.parse_args()
60
+ threading.Thread(target=memwatch, daemon=True).start()
61
+ os.makedirs(os.path.join(W, "raw"), exist_ok=True); os.makedirs(os.path.join(W, "cache"), exist_ok=True)
62
+ net = Net(W)
63
+ cat_p = os.path.join(W, "catalog.json"); pages_p = os.path.join(W, "catalog_pages.jsonl")
64
+ try:
65
+ if not os.path.exists(cat_p):
66
+ if not os.path.exists(os.path.join(W, "raw/termofuse.html")):
67
+ u, st, ct, raw = net.get(BASE + TERMS); open(os.path.join(W, "raw/termofuse.html"), "wb").write(raw)
68
+ ip = os.path.join(W, "raw/actsaz.html")
69
+ if not os.path.exists(ip):
70
+ u, st, ct, raw = net.get(BASE + INDEX); open(ip, "wb").write(raw)
71
+ subs = parse_index(open(ip, encoding="utf-8", errors="replace").read())
72
+ status(f"index: {len(subs)} sub-pages")
73
+ if len(subs) < 50: status(f"INDEX_TOO_SMALL {len(subs)}"); return 2
74
+ done = {}
75
+ if os.path.exists(pages_p):
76
+ for l in open(pages_p): d = json.loads(l); done[d["page"]] = d
77
+ for sp in subs:
78
+ if sp in done: continue
79
+ if STOP["mem"]: return 4
80
+ u, st, ct, raw = net.get(sp)
81
+ items = parse_sub(raw.decode("utf-8", "replace"), sp) if st == 200 else []
82
+ with open(pages_p, "a") as f: f.write(json.dumps({"page": sp, "status": st, "items": items}, ensure_ascii=False) + "\n")
83
+ done[sp] = {"items": items}
84
+ seen, cat = set(), []
85
+ for sp in subs:
86
+ for x in done[sp]["items"]:
87
+ k = unquote(x["url"]).lower()
88
+ if k in seen: continue
89
+ seen.add(k); x["key"] = hashlib.sha1(x["url"].encode()).hexdigest()[:16]; x["kind"] = "consolidated_act"; cat.append(x)
90
+ json.dump(cat, open(cat_p, "w"), indent=1, ensure_ascii=False); status(f"CATALOG_DONE items={len(cat)} requests={net.n}")
91
+ if a.catalog_only: return 0
92
+ cat = json.load(open(cat_p)); fp = os.path.join(W, "fetched.jsonl")
93
+ done = set()
94
+ if os.path.exists(fp):
95
+ for l in open(fp): done.add(json.loads(l)["key"])
96
+ todo = [x for x in cat if x["key"] not in done]
97
+ if a.max: todo = todo[:a.max]
98
+ status(f"FETCH_START todo={len(todo)} done={len(done)}")
99
+ for i, x in enumerate(todo, 1):
100
+ if STOP["mem"]: status("MEM_STOP exit"); return 4
101
+ tb = tree_bytes()
102
+ if tb > TREE_CAP: status("TREE_CAP 300 MB reached; stop"); return 5
103
+ if rss_mb() > 300: status(f"RSS_CAP {rss_mb():.0f} MB; stop"); return 5
104
+ rec = dict(x)
105
+ try:
106
+ u, st, ct, raw = net.get(x["url"])
107
+ if st != 200 or not raw.startswith(b"%PDF"):
108
+ rec.update(status_code=st, error=f"not_pdf ct={ct}")
109
+ else:
110
+ sha = hashlib.sha256(raw).hexdigest(); p = os.path.join(W, "cache", sha + ".pdf")
111
+ if not os.path.exists(p):
112
+ open(p + ".part", "wb").write(raw); os.replace(p + ".part", p)
113
+ tm = extract_one(sha, p)
114
+ with open(os.path.join(W, "texts_pre.jsonl"), "a") as tf: tf.write(json.dumps(tm) + "\n")
115
+ pruned = False
116
+ if tb > SOFT and not tm["needs_ocr"]: os.remove(p); pruned = True
117
+ rec.update(final_url=u, sha256=sha, bytes=len(raw), status_code=st, pdf_pruned_for_tree_cap=pruned,
118
+ retrieved_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
119
+ except Skip as e:
120
+ rec.update(error=f"skip: {e}")
121
+ with open(fp, "a") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n")
122
+ if i % 25 == 0: status(f"progress {i}/{len(todo)} requests={net.n} tree_mb={tree_bytes()/1e6:.0f}")
123
+ status(f"FETCH_DONE fetched={len(todo)} requests={net.n}")
124
+ return 0
125
+ except HardStop as e:
126
+ status(f"HARD_STOP {e}"); open(os.path.join(W, "HARD_STOP"), "w").write(f"{time.strftime('%FT%T%z')} {e}\n"); return 3
127
+ if __name__ == "__main__":
128
+ sys.exit(main())
scrapers/mu_b1/extract_mu.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Text-layer extraction for MU mu_b1 (pdftotext -layout, page split on form feeds). A document needs OCR when its text layer is
3
+ missing/thin: mean non-space chars per page < 200, or >= 50 % of pages with < 40 non-space chars. Garble ratio = share of
4
+ characters outside printable Latin-1 + common typographic punctuation. Output cache/text/<sha>.txt + texts.jsonl. Env MU_WORK.
5
+ The collector calls extract_one() right after each download and deletes the PDF of a good text-layer document (300 MB tree cap);
6
+ its result is kept in texts_pre.jsonl and reused here. PDFs are kept only for documents that need OCR."""
7
+ import json, os, re, subprocess, sys
8
+ W = os.environ.get("MU_WORK", ".")
9
+ OKCH = re.compile(r"[\x20-\x7e\xa0-\xff\u2018\u2019\u201c\u201d\u2013\u2014\u2026\u00a3\u20ac\u2022\u00b7\u2122\n\r\t\f]")
10
+ def garble(t):
11
+ t2 = re.sub(r"\s", "", t)
12
+ if not t2: return 1.0
13
+ return round(sum(1 for c in t2 if not OKCH.match(c)) / len(t2), 4)
14
+ def extract_one(sha, pdf):
15
+ os.makedirs(f"{W}/cache/text", exist_ok=True)
16
+ p = subprocess.run(["pdftotext", "-layout", "-enc", "UTF-8", pdf, "-"], capture_output=True, timeout=600)
17
+ txt = p.stdout.decode("utf-8", "replace")
18
+ pages = txt.split("\f")
19
+ if pages and not pages[-1].strip(): pages = pages[:-1]
20
+ nch = [len(re.sub(r"\s", "", pg)) for pg in pages] or [0]
21
+ thin = sum(1 for c in nch if c < 40)
22
+ needs = (sum(nch) / len(nch) < 200) or (thin / len(nch) >= 0.5)
23
+ open(f"{W}/cache/text/{sha}.txt", "w").write(txt)
24
+ return {"sha256": sha, "pages": len(pages), "chars": sum(nch), "thin_pages": thin, "needs_ocr": needs, "garble": garble(txt), "rc": p.returncode}
25
+ if __name__ == "__main__":
26
+ pre = {}
27
+ if os.path.exists(f"{W}/texts_pre.jsonl"):
28
+ for l in open(f"{W}/texts_pre.jsonl"):
29
+ d = json.loads(l); pre[d["sha256"]] = d
30
+ out, seen = [], set()
31
+ for l in open(f"{W}/fetched.jsonl"):
32
+ r = json.loads(l)
33
+ if not r.get("sha256") or r["sha256"] in seen: continue
34
+ seen.add(r["sha256"]); pdf = f"{W}/cache/{r['sha256']}.pdf"
35
+ if os.path.exists(pdf): out.append(extract_one(r["sha256"], pdf))
36
+ elif r["sha256"] in pre and os.path.exists(f"{W}/cache/text/{r['sha256']}.txt"): out.append(pre[r["sha256"]])
37
+ with open(f"{W}/texts.jsonl", "w") as f:
38
+ for o in out: f.write(json.dumps(o) + "\n")
39
+ print(json.dumps({"docs": len(out), "needs_ocr": sum(o["needs_ocr"] for o in out), "garble_gt_0.08": sum(o["garble"] > 0.08 for o in out)}))
scrapers/mu_b1/finalize_mu.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Finalize the MU mu_b1 pack: copy the code bundle into scrapers/mu_b1 (never touching the tip's published scrapers/*.py),
3
+ write manifests (known_gaps.json, changed_ids.json, webmail_redactions.json, mu_b1_code.json, mu_b1_summary.json,
4
+ mu_b1_pii_scan.json, pii_scan_notes.md), update the tip's MANIFEST.json / provenance/changes.json additively when the tip has them,
5
+ then SHA256SUMS over every pack file. Never uploads. Env MU_WORK."""
6
+ import hashlib, json, os, shutil, sys
7
+ from collections import Counter
8
+ from pathlib import Path
9
+ import pyarrow.parquet as pq
10
+ HERE = Path(__file__).resolve().parent; sys.path.insert(0, str(HERE))
11
+ from pii_scan_mu import scan
12
+ W = Path(os.environ.get("MU_WORK", ".")).resolve(); S = json.load(open(W / "stage_summary.json")); P = W / "hf_mu_b1" / S["repo"].split("/")[1]
13
+ TD = W / "tip_stage" / S["parent"][:8]; X = json.load(open(W / "stage_extra.json"))
14
+ M = P / "manifests"; SC = P / "scrapers/mu_b1"
15
+ if SC.exists(): shutil.rmtree(SC)
16
+ SC.mkdir(parents=True)
17
+ for pat in ("*.py", "*.sh", "requirements.txt"):
18
+ for f in sorted(HERE.glob(pat)): shutil.copy2(f, SC / f.name)
19
+ shutil.copy2(HERE / "README_scrapers.md", SC / "README.md")
20
+ shutil.copy2(HERE / "requirements.txt", P / "scrapers/requirements.txt")
21
+ sh = lambda f: hashlib.sha256(f.read_bytes()).hexdigest()
22
+ json.dump({"bundle": "scrapers/mu_b1", "files": {f.name: sh(f) for f in sorted(SC.iterdir()) if f.is_file()},
23
+ "requirements": {"scrapers/requirements.txt": sh(P / "scrapers/requirements.txt")},
24
+ "robots_guard": {"upstream_sha256": "fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542", "bundled_sha256": sh(SC / "robots_guard.py"),
25
+ "change": "cache root default changed from an absolute fleet path to the relative 'legal-corpora' (LEGAL_CORPORA_ROOT overrides); no logic change"}},
26
+ open(M / "mu_b1_code.json", "w"), indent=1)
27
+ drops = [json.loads(l) for l in open(M / "mu_b1_drops.jsonl")]
28
+ hd = json.load(open(W / "heading_drops.json"))
29
+ dup = [d for d in drops if d["reason"].startswith("duplicate")]
30
+ json.dump({"batch": "mu_b1",
31
+ "whole_text_fallback_laws": {"count": len(X["whole"]), "items": X["whole"]},
32
+ "duplicate_drops": {"count": len(dup), "by_reason": dict(Counter(d["reason"] for d in dup)), "items": dup},
33
+ "other_source_drops": {"count": len(drops) - len(dup), "by_reason": dict(Counter(d["reason"] for d in drops if d not in dup)), "items": [d for d in drops if d not in dup]},
34
+ "act_number_or_title_mismatch": {"count": len(X["number_issues"]), "note": "listing/file-name number, year or title differs from the printed title block; the printed value is used", "items": X["number_issues"]},
35
+ "heading_only_rows_dropped": {"count": len(hd), "laws": len({d["law_id"] for d in hd}),
36
+ "note": "arrangement-of-sections entries with no body; the text stays in laws.text at char_start:char_end", "items": hd}},
37
+ open(M / "known_gaps.json", "w"), indent=1, ensure_ascii=False)
38
+ A = pq.read_table(P / "data/articles.parquet", columns=["id", "law_id", "metadata_json"]).to_pylist()
39
+ Lr = pq.read_table(P / "data/laws.parquet", columns=["id"]).to_pylist()
40
+ json.dump({"parent": S["parent"], "removed_law_ids": [], "removed_article_ids": [], "changed_live_rows": 0,
41
+ "added_law_ids": [r["id"] for r in Lr[S["tip_laws"]:]], "added_article_ids": [a["id"] for a in A[S["tip_articles"]:]]},
42
+ open(M / "changed_ids.json", "w"), indent=1)
43
+ json.dump({"placeholder": "[redacted-webmail]", "total": sum(r["count"] for r in X["webmail"]), "laws": X["webmail"],
44
+ "note": "free-webmail addresses (standard, typo-domain, truncated, spaced, line-split) redacted in laws.text before splitting, so article slices inherit it; offsets refer to the stored text; no values recorded"},
45
+ open(M / "webmail_redactions.json", "w"), indent=1)
46
+ hits = scan([str(P / "data/laws.parquet"), str(P / "data/articles.parquet")])
47
+ pj = {"new_fail": sum(h["level"] == "fail" for h in hits), "new_hits": hits}
48
+ json.dump(pj, open(M / "mu_b1_pii_scan.json", "w"), indent=1); json.dump(pj, open(W / "pii_scan.json", "w"), indent=1)
49
+ warn = sorted({h["id"] for h in hits if h["level"] == "warn"})
50
+ (M / "pii_scan_notes.md").write_text("\n".join([
51
+ "# PII scan notes (batch mu_b1)", "", f"- Scope: every string column of the {S['new_laws']} new law rows and {S['new_articles']} new article rows.",
52
+ f"- FAIL hits in new rows: {pj['new_fail']}.", f"- WARN hits: {dict(Counter(h['kind'] for h in hits if h['level'] == 'warn'))}.", "",
53
+ "WARN hits are telephone/fax numbers printed in the Acts themselves (office numbers of public bodies, forms) or P.O. Box addresses "
54
+ "of institutions; they are official texts and are kept. Values are not reproduced here.", "", "Rows with WARN hits:", ""] + [f"- `{i}`" for i in warn] + [""]))
55
+ S2 = {k: v for k, v in S.items() if k != "quality"}; json.dump(S2, open(M / "mu_b1_summary.json", "w"), indent=1, ensure_ascii=False)
56
+ for f in ("MANIFEST.json", "provenance/changes.json"):
57
+ if (TD / f).exists():
58
+ d = json.load(open(TD / f)); (P / f).parent.mkdir(parents=True, exist_ok=True)
59
+ if isinstance(d, dict):
60
+ d["mu_b1"] = {"parent": S["parent"], "new_laws": S["new_laws"], "new_articles": S["new_articles"], "laws_rows": S["laws_rows"], "articles_rows": S["articles_rows"]}
61
+ json.dump(d, open(P / f, "w"), indent=1, ensure_ascii=False)
62
+ files = sorted(f for f in P.rglob("*") if f.is_file() and f.name != "SHA256SUMS" and "__pycache__" not in f.parts)
63
+ (P / "SHA256SUMS").write_text("".join(f"{sh(f)} {f.relative_to(P)}\n" for f in files))
64
+ print(json.dumps({"finalize": "ok", "files": len(files), "heading_only": len(hd), "whole": len(X["whole"]), "pii_new_fail": pj["new_fail"]}))
scrapers/mu_b1/mu_net.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Guarded, paced, fail-closed HTTP GET for the SH mu_b1 lane (CoS rules 2026-10-16).
3
+ * shared robots_guard (one-hop patched copy, bundled here as robots_guard.py) checked on EVERY hop; content redirects are
4
+ followed only on the same host (each hop guarded + paced); a cross-host content redirect is NOT followed (logged, item skipped);
5
+ * pacing max(8 s, Crawl-delay) on one clock, one request in flight; verify=True (certifi); unchanged UA (robots_guard.ROBOTS_UA);
6
+ * HARD_STOP (exit 3 by caller) on 403/429/503, cf-mitigated, challenge page, any cert-verify error, robots unavailable/challenge;
7
+ * transport SSLError / connection reset: ONE retry after 120 s, logged; a 2nd consecutive failure or 3 transport errors total -> HARD_STOP;
8
+ * timeout: one retry, then skip the item.
9
+ Every request is appended to requests.jsonl (url, status, bytes, ct, elapsed; never bodies)."""
10
+ import json, os, re, sys, time, hashlib
11
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # bundled robots_guard.py
12
+ os.environ["LEGAL_CORPORA_ROOT"] = os.path.join(os.path.abspath(os.environ.get("MU_WORK", ".")), "legal-corpora") # guard cache/logs under the work dir
13
+ import requests
14
+ import robots_guard as rg
15
+ from urllib.parse import urlsplit, urljoin
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from challenge_detector_v2 import STRONG, WIDGET_JS, WEAK
18
+ rg.set_country("mu")
19
+ # MU lane extra interstitial markers (checked on EVERY response incl. robots.txt and non-200 bodies)
20
+ EXTRA = re.compile(r"One moment,? please|rejected request|support id|bot[- ]verification|verify (?:that )?you are (?:a )?human|"
21
+ r"Request unsuccessful|Pardon Our Interruption|are you a robot", re.I)
22
+ ROBOTS_FLAG = {"challenge": None}
23
+ _LOGP = {"path": None}
24
+ def _robots_fetch(url):
25
+ code, text, note = rg._default_fetch(url)
26
+ row = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "kind": "robots", "url": url, "status": code, "bytes": len(text or ""), "note": (note or "")[:200]}
27
+ v = "clean"
28
+ if text:
29
+ v, m = classify(text)
30
+ if v != "challenge" and EXTRA.search(text[:400_000]): v, m = "challenge", EXTRA.search(text[:400_000]).group(0)
31
+ row["challenge_verdict"] = v
32
+ if v == "challenge": row["marker"] = m; ROBOTS_FLAG["challenge"] = url
33
+ if _LOGP["path"]:
34
+ with open(_LOGP["path"], "a") as f: f.write(json.dumps(row) + "\n")
35
+ if v == "challenge": return 0, "", "challenge_on_robots"
36
+ return code, text, note
37
+ rg._robots_fetcher = _robots_fetch
38
+ MIN_GAP = 8.0
39
+
40
+ class HardStop(Exception): pass
41
+ class Skip(Exception): pass
42
+
43
+ def _now(): return time.strftime("%Y-%m-%dT%H:%M:%S%z")
44
+
45
+ def classify(txt):
46
+ body = txt[:400_000]
47
+ m = EXTRA.search(body) if "EXTRA" in globals() else None
48
+ if m: return "challenge", m.group(0)[:80]
49
+ m = STRONG.search(body)
50
+ if m: return "challenge", m.group(0)[:80]
51
+ m = WIDGET_JS.search(body)
52
+ if m and len(txt) < 60 * 1024: return "challenge", m.group(0)[:80]
53
+ w = WEAK.search(body)
54
+ if w:
55
+ words = len(re.sub(r"<[^>]+>", " ", body).split())
56
+ return ("challenge" if len(txt) < 60 * 1024 and words < 300 else "weak"), w.group(0)[:80]
57
+ return "clean", None
58
+
59
+ class Net:
60
+ def __init__(self, work, max_bytes=60_000_000):
61
+ self.W = work; self.req = os.path.join(work, "requests.jsonl"); self.last = 0.0
62
+ self.transport_errors = 0; self.n = 0; self.max_bytes = max_bytes
63
+ self.s = requests.Session(); self.s.headers["User-Agent"] = rg.ROBOTS_UA; _LOGP["path"] = self.req
64
+ def log(self, row):
65
+ with open(self.req, "a") as f: f.write(json.dumps({"ts": _now(), **row}, ensure_ascii=False) + "\n")
66
+ def _pace(self, gap):
67
+ d = gap - (time.time() - self.last)
68
+ if d > 0: time.sleep(d)
69
+ def _one(self, url):
70
+ d = rg.check(url)
71
+ if ROBOTS_FLAG["challenge"]:
72
+ self.log({"url": url, "event": "robots_challenge", "robots_url": ROBOTS_FLAG["challenge"]}); raise HardStop(f"challenge on robots {ROBOTS_FLAG['challenge']}")
73
+ if d.robots_status == "unavailable":
74
+ rg.report_blocked(d, caller="mu_net"); self.log({"url": url, "event": "robots_unavailable", "rule": d.rule})
75
+ raise HardStop(f"robots_unavailable {d.host}: {d.rule}")
76
+ if not d.allowed:
77
+ rg.report_blocked(d, caller="mu_net"); self.log({"url": url, "event": "robots_disallowed", "rule": d.rule})
78
+ raise Skip(f"robots_disallowed {url}")
79
+ gap = max(MIN_GAP, d.crawl_delay or 0)
80
+ consecutive = 0
81
+ for attempt in (1, 2):
82
+ self._pace(gap); t = time.time()
83
+ try:
84
+ r = self.s.get(url, timeout=(20, 120), verify=rg.ca_verify_for(url), allow_redirects=False, stream=True)
85
+ raw = b""
86
+ for ch in r.iter_content(65536):
87
+ raw += ch
88
+ if len(raw) > self.max_bytes: break
89
+ r.close(); self.last = time.time(); self.n += 1
90
+ return r, raw, time.time() - t, d
91
+ except requests.exceptions.SSLError as e:
92
+ self.last = time.time(); self.n += 1; es = str(e)
93
+ self.log({"url": url, "event": "ssl_error", "error": es[:300], "attempt": attempt})
94
+ if re.search(r"CERTIFICATE_VERIFY_FAILED|certificate verify failed|hostname mismatch", es): raise HardStop("cert_verify_error")
95
+ self.transport_errors += 1
96
+ if attempt == 2 or self.transport_errors >= 3: raise HardStop(f"transport_ssl x{self.transport_errors}")
97
+ time.sleep(120)
98
+ except requests.exceptions.ConnectionError as e:
99
+ self.last = time.time(); self.n += 1
100
+ self.log({"url": url, "event": "conn_error", "error": str(e)[:300], "attempt": attempt})
101
+ self.transport_errors += 1
102
+ if attempt == 2 or self.transport_errors >= 3: raise HardStop(f"transport_conn x{self.transport_errors}")
103
+ time.sleep(120)
104
+ except requests.exceptions.Timeout:
105
+ self.last = time.time(); self.n += 1
106
+ self.log({"url": url, "event": "timeout", "attempt": attempt})
107
+ if attempt == 2: raise Skip(f"timeout x2 {url}")
108
+ raise Skip("unreachable")
109
+ def get(self, url):
110
+ """Returns (final_url, status, content_type, bytes). Raises HardStop / Skip."""
111
+ hops = 0
112
+ while True:
113
+ r, raw, el, d = self._one(url)
114
+ ct = r.headers.get("Content-Type", ""); loc = r.headers.get("Location")
115
+ row = {"url": url, "status": r.status_code, "bytes": len(raw), "content_type": ct, "location": loc,
116
+ "elapsed_s": round(el, 2), "n": self.n}
117
+ row["last_modified"] = r.headers.get("Last-Modified")
118
+ if r.headers.get("cf-mitigated"): self.log(row); raise HardStop("cf-mitigated")
119
+ if not raw.startswith(b"%PDF"):
120
+ v0, m0 = classify(raw[:400_000].decode("utf-8", "replace"))
121
+ if v0 == "challenge": row["challenge_verdict"] = v0; row["marker"] = m0; self.log(row); raise HardStop(f"challenge {url}")
122
+ if r.status_code in (403, 429, 503): self.log(row); raise HardStop(f"http_{r.status_code} {url}")
123
+ if r.status_code in (301, 302, 303, 307, 308) and loc:
124
+ nxt = urljoin(url, loc); self.log(row)
125
+ if (urlsplit(nxt).hostname or "").lower() != (urlsplit(url).hostname or "").lower():
126
+ self.log({"url": url, "event": "cross_host_redirect_not_followed", "location": nxt})
127
+ raise Skip(f"cross_host_redirect {nxt}")
128
+ hops += 1
129
+ if hops > 5: raise Skip("too_many_redirects")
130
+ url = nxt; continue
131
+ if "html" in ct.lower() or raw[:200].lstrip().lower().startswith((b"<!doctype", b"<html")):
132
+ v, m = classify(raw.decode("utf-8", "replace")); row["challenge_verdict"] = v
133
+ if v == "challenge": row["marker"] = m; self.log(row); raise HardStop(f"challenge {url}")
134
+ row["sha256"] = hashlib.sha256(raw).hexdigest(); self.log(row)
135
+ return url, r.status_code, ct, raw
scrapers/mu_b1/ocr_mu.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """OCR MU mu_b1 needs_ocr PDFs (adapted from GH ir_b1 ocr_gh_ir.py) (no usable text layer). Fleet v2 gates: start MemAvailable >= 5.5 GiB held 120 s,
3
+ pause < 4 GiB held 60 s (resume >= 5.5 GiB held 120 s), hard stop < 3 GiB held 15 s, tree RSS cap 1 GiB, disk >= 12,600 MiB,
4
+ 10-min requeue. ONE worker, page by page (render 1 page at 300 dpi gray, OCR, delete). Runs inside the pipeline's held slot
5
+ (/dev/shm/mu_b1_job.<pipeline pid>); no new stagger stamp. tesseract: system tessdata (/usr/share/tesseract-ocr/5/tessdata,
6
+ has configs/tsv), -l eng. One-page self-test must return words > 0 before any document; a document with 0 words is NOT
7
+ marked done (fails loud: OCR_EMPTY; > 2 in a row or > 20 % of >= 5 docs -> FATAL rc=4). mean_conf < 80 -> DEGRADED.
8
+ Output cache/ocr/<ident>.txt (+ .json {pages, words, mean_conf, status}). Resumable. Env MU_WORK, MU_PIPE_PID."""
9
+ import json, os, shutil, subprocess, sys, tempfile, threading, time
10
+ from pathlib import Path
11
+ W = Path(os.environ.get("MU_WORK", ".")); OUT = W / "cache/ocr"; OUT.mkdir(parents=True, exist_ok=True)
12
+ TESSDATA = "/usr/share/tesseract-ocr/5/tessdata"
13
+ ST = W / "status.txt"
14
+ def log(m):
15
+ with open(ST, "a") as f: f.write(time.strftime("%Y-%m-%dT%H:%M:%S%z") + " OCR " + m + "\n")
16
+ def mem():
17
+ for l in open("/proc/meminfo"):
18
+ if l.startswith("MemAvailable"): return int(l.split()[1]) / 1048576
19
+ def tree_rss():
20
+ out = subprocess.run(["ps", "-e", "-o", "pid=,ppid=,rss="], capture_output=True, text=True).stdout.split("\n")
21
+ rows = [tuple(map(int, l.split())) for l in out if l.strip()]
22
+ kids, ch = {os.getpid()}, True
23
+ while ch:
24
+ ch = False
25
+ for p, pp, r in rows:
26
+ if pp in kids and p not in kids: kids.add(p); ch = True
27
+ return sum(r for p, pp, r in rows if p in kids) / 1024
28
+ def held(t, cond, every=5):
29
+ t0 = time.time()
30
+ while time.time() - t0 < t:
31
+ if not cond(): return False
32
+ time.sleep(every)
33
+ return True
34
+ def start_gate():
35
+ while True:
36
+ free = shutil.disk_usage(str(W)).free / 1048576
37
+ if free >= 12600 and held(120, lambda: mem() >= 5.5): return
38
+ log(f"GATE_WAIT v2 mem={mem():.2f}GiB disk={free:.0f}MiB requeue 600s"); time.sleep(600)
39
+ STOP = threading.Event(); REASON = []; PEAK = [0.0]
40
+ def monitor():
41
+ low = None
42
+ while not STOP.is_set():
43
+ m = mem()
44
+ if m < 3.0:
45
+ low = low or time.time()
46
+ if time.time() - low >= 15: REASON.append(f"HARD_STOP mem={m:.2f}GiB<3.0 held 15s"); STOP.set()
47
+ else: low = None
48
+ r = tree_rss(); PEAK[0] = max(PEAK[0], r)
49
+ if r > 1024: REASON.append(f"RSS_CAP rss={r:.0f}MB"); STOP.set()
50
+ time.sleep(3)
51
+ def pause_gate():
52
+ if mem() >= 4.0: return
53
+ t0 = time.time()
54
+ while not STOP.is_set() and mem() < 4.0:
55
+ if time.time() - t0 >= 60:
56
+ log(f"PAUSE mem={mem():.2f}GiB<4.0 held 60s")
57
+ while not STOP.is_set():
58
+ if held(120, lambda: mem() >= 5.5 and not STOP.is_set()): log("RESUME"); return
59
+ return
60
+ time.sleep(5)
61
+ TENV = {**os.environ, "TESSDATA_PREFIX": TESSDATA, "OMP_THREAD_LIMIT": "1"}
62
+ def tess_tsv(png):
63
+ r = subprocess.run(["tesseract", png, "-", "-l", "eng", "--psm", "6", "tsv"], capture_output=True, text=True, timeout=600, env=TENV)
64
+ return r.stdout, r.stderr
65
+ def parse_tsv(tsv):
66
+ lines, confs = {}, []
67
+ for row in tsv.split("\n")[1:]:
68
+ c = row.split("\t")
69
+ if len(c) < 12 or c[0] != "5": continue
70
+ cf = float(c[10]); w = c[11]
71
+ if cf >= 0 and w.strip(): confs.append(cf); lines.setdefault((int(c[2]), int(c[3]), int(c[4])), []).append(w)
72
+ return lines, confs
73
+ def check_tess():
74
+ if not (Path(TESSDATA) / "configs" / "tsv").exists(): log(f"FATAL tessdata {TESSDATA} lacks configs/tsv"); sys.exit(5)
75
+ r = subprocess.run(["tesseract", "--list-langs"], capture_output=True, text=True, env=TENV)
76
+ if "eng" not in (r.stdout + r.stderr).split(): log(f"FATAL tesseract lang eng missing prefix={TESSDATA}"); sys.exit(5)
77
+ def render(pdf, p, base):
78
+ subprocess.run(["pdftoppm", "-r", "300", "-gray", "-f", str(p), "-l", str(p), "-png", "-singlefile", str(pdf), base], check=True, timeout=300)
79
+ def self_test(todo):
80
+ for i in todo:
81
+ pdf = W / "cache" / f"{i}.pdf"
82
+ with tempfile.TemporaryDirectory(dir=str(W)) as td:
83
+ try: render(pdf, 1, f"{td}/st")
84
+ except Exception: continue
85
+ tsv, err = tess_tsv(f"{td}/st.png"); _, confs = parse_tsv(tsv)
86
+ if not confs: log(f"FATAL SELFTEST words=0 prefix={TESSDATA} pdf={pdf.name} err={err.strip()[:200]!r}"); sys.exit(6)
87
+ log(f"SELFTEST ok prefix={TESSDATA} lang=eng pdf={pdf.name} p1 words={len(confs)} mean_conf={sum(confs)/len(confs):.1f}"); return
88
+ log("FATAL SELFTEST no renderable PDF"); sys.exit(6)
89
+ EMPTY, SEEN, RUN = [], [0], [0]
90
+ def done(i):
91
+ f = OUT / f"{i}.json"
92
+ try: d = json.loads(f.read_text()); return d.get("words", 0) > 0 or d.get("status") == "FAILED"
93
+ except Exception: return False
94
+ def ocr_doc(ident):
95
+ pdf = W / "cache" / f"{ident}.pdf"; texts, confs = [], []
96
+ info = subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True).stdout
97
+ pl = [l for l in info.split("\n") if l.startswith("Pages")]
98
+ if not pl:
99
+ meta = {"ident": ident, "pages": 0, "words": 0, "mean_conf": 0.0, "status": "FAILED", "error": "pdfinfo_no_pages"}
100
+ (OUT / f"{ident}.json").write_text(json.dumps(meta)); log(f"FAIL {ident} pdfinfo_no_pages"); return meta
101
+ n = int(pl[0].split()[1])
102
+ with tempfile.TemporaryDirectory(dir=str(W)) as td:
103
+ for p in range(1, n + 1):
104
+ pause_gate()
105
+ if STOP.is_set(): return None
106
+ base = f"{td}/p"; render(pdf, p, base)
107
+ tsv, _ = tess_tsv(base + ".png"); lines, pc = parse_tsv(tsv); confs.extend(pc)
108
+ texts.append("\n".join(" ".join(v) for k, v in sorted(lines.items())))
109
+ os.remove(base + ".png")
110
+ SEEN[0] += 1
111
+ if not confs:
112
+ EMPTY.append(ident); RUN[0] += 1
113
+ log(f"OCR_EMPTY {ident} pages={n} (not marked done)")
114
+ if RUN[0] > 2 or (SEEN[0] >= 5 and len(EMPTY) / SEEN[0] > 0.20):
115
+ log(f"FATAL OCR_EMPTY run={RUN[0]} empty={len(EMPTY)}/{SEEN[0]} empties={EMPTY}"); sys.exit(4)
116
+ return None
117
+ RUN[0] = 0
118
+ mc = sum(confs) / len(confs)
119
+ (OUT / f"{ident}.txt").write_text("\f".join(texts))
120
+ ver = subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.split()[1]
121
+ meta = {"ident": ident, "pages": n, "words": len(confs), "mean_conf": round(mc, 2), "status": "ok" if mc >= 80 else "DEGRADED",
122
+ "engine": f"tesseract {ver}", "lang": "eng", "dpi": 300, "psm": 6, "tessdata": TESSDATA}
123
+ (OUT / f"{ident}.json").write_text(json.dumps(meta)); log(f"DONE {ident} pages={n} words={len(confs)} conf={mc:.1f} {meta['status']} peak_tree_rss={PEAK[0]:.0f}MB")
124
+ return meta
125
+ def main():
126
+ check_tess()
127
+ todo = []
128
+ for l in open(W / "texts.jsonl"):
129
+ d = json.loads(l)
130
+ if d.get("needs_ocr") and d["sha256"] not in todo: todo.append(d["sha256"])
131
+ todo = [i for i in todo if not done(i) and (W / "cache" / f"{i}.pdf").exists()]
132
+ jf = Path(f"/dev/shm/mu_b1_job.{os.environ.get('MU_PIPE_PID', '')}")
133
+ log(f"MODE v2 5.5/4.0/3.0 rss1024 workers=1 todo={len(todo)} slot={jf.read_text().strip() if jf.exists() else 'NONE'}")
134
+ if todo and not jf.exists(): log("FATAL no pipeline slot held (run via pipeline_mu.sh)"); sys.exit(7)
135
+ selftested = False
136
+ while todo:
137
+ start_gate()
138
+ if not selftested: self_test(todo); selftested = True
139
+ log(f"START todo={len(todo)} mem={mem():.2f}GiB"); STOP.clear(); REASON.clear()
140
+ th = threading.Thread(target=monitor, daemon=True); th.start()
141
+ for i in todo:
142
+ if STOP.is_set(): break
143
+ ocr_doc(i)
144
+ STOP.set(); th.join(5)
145
+ todo = [i for i in todo if not done(i)]
146
+ if REASON:
147
+ log("STOPPED " + REASON[0] + f" peak_tree_rss={PEAK[0]:.0f}MB remaining={len(todo)}")
148
+ if REASON[0].startswith("RSS_CAP"): sys.exit(3)
149
+ time.sleep(600)
150
+ elif todo:
151
+ log(f"EMPTY_LEFT {todo} (not retried in this run)"); break
152
+ log(f"OCR_DONE remaining={len(todo)} empty={EMPTY}")
153
+ main()
scrapers/mu_b1/pii_scan_mu.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PII scan for MU mu_b1 shards: every string column of every row. Rows from batch mu_b1 (metadata_json) gate the pack.
3
+ FAIL kinds: email_non_gov (any address that is not a government / institutional domain), phone_mobile (Mauritius mobile:
4
+ 8 digits starting 5, optional +230, introduced by a tel/fax cue), name_near_street_address, nic_like (Mauritius National
5
+ Identity Card pattern). WARN kinds: phone_landline (7-digit number introduced by a tel/fax cue), name_near_po_box.
6
+ Output records row id, column, kind and offset only, never the value."""
7
+ import json, re, sys
8
+ from collections import Counter
9
+ import pyarrow.parquet as pq
10
+ GOV = re.compile(r"(?i)@(?:[a-z0-9-]+\.)*(?:govmu\.org|gov\.mu|ac\.mu|int|org)$")
11
+ EMAIL = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")
12
+ PHONE = re.compile(r"(?<![0-9A-Za-z£$.,/])(?:\(?\+?230\)?[\s-]?)?[2-9]\d{2,3}[\s-]?\d{4}(?![0-9A-Za-z])")
13
+ PCUE = re.compile(r"(?i)\b(?:tel|telephone|phone|fax|mobile|cell)\b")
14
+ NIC = re.compile(r"\b[A-Z]\d{12}[A-Z0-9]\b")
15
+ NAME = re.compile(r"\b(?:Mr|Mrs|Ms|Miss|Dr)\.?\s+(?:[A-Z]\.?\s*){0,3}[A-Z][a-z]+")
16
+ STREET = re.compile(r"\b\d{1,5}[A-Za-z]?,?\s+(?:[A-Z][a-z]+\s+){1,3}(?:Street|Road|Avenue|Drive|Lane|Close|Way)\b")
17
+ POBOX = re.compile(r"(?i)\bP\.?\s?[O0]\.?\s?Box\b")
18
+ FAIL = {"email_non_gov", "phone_mobile", "name_near_street_address", "nic_like"}
19
+ def scan_value(v):
20
+ out = []
21
+ for m in EMAIL.finditer(v):
22
+ if not GOV.search(m.group(0)) and "[redacted-webmail]" not in m.group(0): out.append(("email_non_gov", m.start()))
23
+ for m in PHONE.finditer(v):
24
+ if not PCUE.search(v[max(0, m.start() - 60): m.start()]): continue
25
+ d = re.sub(r"\D", "", m.group(0)); d = d[3:] if d.startswith("230") and len(d) > 8 else d
26
+ out.append(("phone_mobile" if len(d) == 8 and d[0] == "5" else "phone_landline", m.start()))
27
+ for m in NIC.finditer(v): out.append(("nic_like", m.start()))
28
+ for m in NAME.finditer(v):
29
+ ctx = v[max(0, m.start() - 200): m.end() + 200]
30
+ if STREET.search(ctx): out.append(("name_near_street_address", m.start()))
31
+ elif POBOX.search(ctx): out.append(("name_near_po_box", m.start()))
32
+ return out
33
+ def scan(paths):
34
+ hits = []
35
+ for p in paths:
36
+ t = pq.read_table(p); ids = t.column("id").to_pylist(); mj = t.column("metadata_json").to_pylist()
37
+ new = ['"batch": "mu_b1"' in (x or "") for x in mj]
38
+ for c in t.column_names:
39
+ if str(t.schema.field(c).type) not in ("string", "large_string"): continue
40
+ for rid, v, nw in zip(ids, t.column(c).to_pylist(), new):
41
+ if v and nw:
42
+ for k, o in scan_value(v):
43
+ hits.append({"file": p.split("/")[-1], "id": rid, "column": c, "kind": k, "offset": o,
44
+ "level": "fail" if k in FAIL else "warn", "rows": "new"})
45
+ return hits
46
+ if __name__ == "__main__":
47
+ h = scan(sys.argv[1:])
48
+ print(json.dumps({"new_counts": {f"{a}:{b}": n for (a, b), n in Counter((x["level"], x["kind"]) for x in h).items()},
49
+ "new_fail": sum(1 for x in h if x["level"] == "fail")}, indent=1))
scrapers/mu_b1/pipeline_mu.sh ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # MU mu_b1 chain: catalog -> fetch first 10 + split validation -> fetch (light gate) -> extract -> OCR (v2, only PDFs without a text
3
+ # layer) -> stage (Hub re-read, diff-limited append) -> verify. Never uploads.
4
+ # Usage: MU_WORK=<work dir> bash pipeline_mu.sh (status lines in $MU_WORK/status.txt: PIPELINE_DONE, HARD_STOP, PARKED, *_FAIL)
5
+ # Fleet gates: light fetch gate MemAvailable >= 4.0 GiB held 120 s, disk >= 12,600 MiB, 300 s stagger on /dev/shm/muni_last_start
6
+ # (stamped ONCE at the real start), one runner slot via flock -n (slot1/2/3 = /dev/shm/muni_runner{,.slot2,.slot3}.lock), yield to
7
+ # Americas BR (bundled br_waiting.sh). In-run: collector hard stop < 1.5 GiB held 15 s and 300 MB tree cap. v2 gate for OCR/stage/
8
+ # verify: start >= 5.5 GiB held 120 s; pause (SIGSTOP) < 4 GiB held 60 s; hard stop < 3 GiB held 15 s; RSS <= 1 GiB.
9
+ set -u; W=$(mkdir -p "${MU_WORK:-.}" && cd "${MU_WORK:-.}" && pwd); HERE=$(cd "$(dirname "$0")" && pwd); export MU_WORK=$W; cd "$W"
10
+ export MU_PIPE_PID=$$
11
+ SHM=${MU_SHM:-/dev/shm}
12
+ unset TESSDATA_PREFIX HTTP_PROXY HTTPS_PROXY http_proxy https_proxy REQUESTS_CA_BUNDLE CURL_CA_BUNDLE HF_HUB_OFFLINE
13
+ log(){ echo "$(date +%FT%T%z) PIPE $*" >> "$W/status.txt"; }
14
+ memkb(){ awk '/MemAvailable/{print $2}' /proc/meminfo; }
15
+ need_kb=$((40*1048576/10))
16
+ memgate(){ local ok_since="" t0 now mem disk; t0=$(date +%s)
17
+ while :; do mem=$(memkb); disk=$(df -m --output=avail "$W" | tail -1 | tr -d ' '); now=$(date +%s)
18
+ if [ "$mem" -ge "$need_kb" ] && [ "$disk" -ge 12600 ]; then ok_since=${ok_since:-$now}; [ $((now-ok_since)) -ge 120 ] && return 0; else ok_since=""; fi
19
+ if [ $((now-t0)) -gt 600 ]; then log "GATE_STALL mem_kb=$mem disk_mib=$disk; requeue 10 min"; sleep 600; t0=$(date +%s); ok_since=""; continue; fi
20
+ sleep 5; done; }
21
+ v2gate(){ local t0 ok; while :; do t0=$(date +%s); ok=1
22
+ while [ $(( $(date +%s)-t0 )) -lt 120 ]; do [ "$(memkb)" -ge $((55*1048576/10)) ] || { ok=0; break; }; sleep 5; done
23
+ [ $ok = 1 ] && return 0; log "V2_GATE_WAIT $1 mem_kb=$(memkb); requeue 10 min"; sleep 600; done; }
24
+ # run a python step under the v2 in-run watchdog
25
+ v2run(){ local name=$1; shift; "$@" & local p=$! low4="" low3="" paused=0 rss
26
+ while kill -0 $p 2>/dev/null; do m=$(memkb); now=$(date +%s)
27
+ rss=$(awk '/VmRSS/{print $2}' /proc/$p/status 2>/dev/null || echo 0)
28
+ if [ "${rss:-0}" -gt 1048576 ]; then log "V2_RSS_STOP $name rss_kb=$rss"; kill $p; wait $p; return 9; fi
29
+ if [ "$m" -lt $((3*1048576)) ]; then low3=${low3:-$now}; [ $((now-low3)) -ge 15 ] && { log "V2_HARD_STOP $name mem_kb=$m"; kill -CONT $p; kill $p; wait $p; return 9; }; else low3=""; fi
30
+ if [ "$m" -lt $((4*1048576)) ]; then low4=${low4:-$now}; if [ $paused = 0 ] && [ $((now-low4)) -ge 60 ]; then kill -STOP $p; paused=1; log "V2_PAUSE $name mem_kb=$m"; fi
31
+ else low4=""; if [ $paused = 1 ] && [ "$m" -ge $((55*1048576/10)) ]; then kill -CONT $p; paused=0; log "V2_RESUME $name mem_kb=$m"; fi; fi
32
+ sleep 3; done; wait $p; }
33
+ log "PIPELINE_START pid=$$ GATE_WAIT"
34
+ while :; do
35
+ memgate
36
+ if why=$("$HERE/br_waiting.sh"); then log "YIELD_BR $why; requeue 10 min"; sleep 600; continue; fi
37
+ if ls "$SHM"/muni_br/* >/dev/null 2>&1 && find "$SHM/muni_br" -maxdepth 2 -name '*wait*' -newermt '-30 min' 2>/dev/null | grep -q .; then log "YIELD_BR muni_br waiting marker; requeue 10 min"; sleep 600; continue; fi
38
+ age=$(( $(date +%s) - $(stat -c %Y "$SHM/muni_last_start" 2>/dev/null || echo 0) ))
39
+ stag_t0=$(date +%s); memok=1
40
+ while [ "$age" -le 300 ]; do
41
+ [ "$(memkb)" -ge "$need_kb" ] || { memok=0; break; }
42
+ [ $(( $(date +%s) - stag_t0 )) -gt 1800 ] && break
43
+ sleep 5; age=$(( $(date +%s) - $(stat -c %Y "$SHM/muni_last_start" 2>/dev/null || echo 0) ))
44
+ done
45
+ [ $memok = 1 ] && [ "$age" -gt 300 ] || continue
46
+ SLOT=""
47
+ for s in muni_runner.lock muni_runner.slot2.lock muni_runner.slot3.lock; do exec 9>"$SHM/$s"; if flock -n 9; then SLOT=$s; break; fi; exec 9>&-; done
48
+ if [ -n "$SLOT" ]; then
49
+ ( flock -w 30 8 && touch "$SHM/muni_last_start" ) 8>"$SHM/muni_last_start.lock"
50
+ echo "$SLOT" > "$SHM/mu_b1_job.$$"
51
+ echo "{\"slot_lock\": \"$SHM/$SLOT\", \"start\": $(date +%s), \"pid\": $$, \"job\": \"mu_b1\"}" > "$SHM/$SLOT.start"
52
+ log "GATES_OK mem_kb=$(memkb) disk_mib=$(df -m --output=avail "$W" | tail -1 | tr -d ' ') stagger_age=${age}s slot=$SLOT stamp=once"; break
53
+ fi
54
+ log "SLOT_BUSY all slots; requeue 10 min"; sleep 600
55
+ done
56
+ trap 'rm -f "$SHM/mu_b1_job.$$"; exec 9>&-' EXIT
57
+ python3 "$HERE"/collect_mu.py --catalog-only > run_catalog.out 2>&1; rc=$?; log "catalog rc=$rc"
58
+ [ $rc -eq 3 ] && { log "HARD_STOP catalog; not continuing"; exit 3; }
59
+ [ -s catalog.json ] || { log "NO_CATALOG stop"; echo "# MU mu_b1 PARKED: no catalog" > PARKED_mu_b1.md; log "PARKED no catalog"; exit 2; }
60
+ if [ ! -f split_validation.json ] || ! python3 -c 'import json,sys; sys.exit(0 if json.load(open("split_validation.json"))["pass"] else 1)'; then
61
+ python3 "$HERE"/collect_mu.py --max 10 > run_fetch10.out 2>&1; rc=$?; log "fetch10 rc=$rc"
62
+ [ $rc -eq 3 ] && { log "HARD_STOP fetch10; not continuing"; exit 3; }
63
+ [ $rc -eq 0 ] || { log "FETCH10_FAIL rc=$rc; stop"; exit 4; }
64
+ python3 "$HERE"/validate_split_mu.py >> run_validate.out 2>&1; rc=$?; log "split_validation rc=$rc"
65
+ [ $rc -eq 0 ] || { echo "# MU mu_b1 PARKED: split validation failed on the first 10 PDFs (see split_validation.json)" > PARKED_mu_b1.md; log "PARKED split validation"; exit 7; }
66
+ fi
67
+ for i in $(seq 1 12); do
68
+ python3 "$HERE"/collect_mu.py > run_fetch.out 2>&1; rc=$?; log "fetch rc=$rc attempt=$i"
69
+ [ $rc -eq 0 ] && break
70
+ [ $rc -eq 3 ] && { log "HARD_STOP fetch; not continuing"; exit 3; }
71
+ [ $rc -eq 5 ] && { echo "# MU mu_b1 PARKED: tree/RSS cap reached during fetch" > PARKED_mu_b1.md; log "PARKED cap"; exit 5; }
72
+ [ $rc -eq 4 ] && { log "REGATE light gate after MEM_STOP"; memgate; continue; }
73
+ sleep 600
74
+ done
75
+ [ $rc -eq 0 ] || { log "FETCH_FAIL rc=$rc; stop"; exit 4; }
76
+ python3 "$HERE"/extract_mu.py > run_extract.out 2>&1; rc=$?; log "extract rc=$rc $(tr '\n' ' ' < run_extract.out | cut -c1-200)"
77
+ [ $rc -eq 0 ] || { log "EXTRACT_FAIL rc=$rc"; exit 6; }
78
+ if python3 -c 'import json,sys; sys.exit(0 if any(json.loads(l)["needs_ocr"] for l in open("texts.jsonl")) else 1)'; then
79
+ v2gate ocr; v2run ocr python3 "$HERE"/ocr_mu.py >> run_ocr.out 2>&1; rc=$?; log "ocr rc=$rc"
80
+ [ $rc -eq 0 ] || { log "OCR_FAIL rc=$rc; stop before stage"; exit 6; }
81
+ else log "ocr skipped: every PDF has a text layer"; fi
82
+ v2gate stage
83
+ v2run stage python3 "$HERE"/stage_mu.py > run_stage.out 2>&1; rc=$?; log "stage rc=$rc $(tail -c 600 run_stage.out | tr '\n' ' ')"
84
+ [ $rc -eq 0 ] || { log "STAGE_FAIL rc=$rc"; exit 5; }
85
+ v2run verify python3 "$HERE"/verify_mu.py > run_verify.out 2>&1; rc=$?; log "VERIFY rc=$rc $(tail -c 120 run_verify.out | tr '\n' ' ')"
86
+ [ $rc -eq 0 ] && log "PIPELINE_DONE" || log "VERIFY_FAIL rc=$rc"
scrapers/mu_b1/readme_mu.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write the cumulative dataset README.md and MANIFEST.md for the MU mu_b1 pack: the tip's own README/MANIFEST are carried
3
+ verbatim (front matter unchanged; the Snapshot rows for laws/articles updated to the new totals) and a batch section is appended
4
+ (sources, licence paraphrase + URL, OCR/text-quality section naming every DEGRADED item, known gaps). Env MU_WORK."""
5
+ import hashlib, json, os, re
6
+ from pathlib import Path
7
+ W = Path(os.environ.get("MU_WORK", ".")).resolve()
8
+ S = json.load(open(W / "stage_summary.json")); P = W / "hf_mu_b1" / S["repo"].split("/")[1]; TD = W / "tip_stage" / S["parent"][:8]
9
+ X = json.load(open(W / "stage_extra.json"))
10
+ rd = (TD / "README.md").read_text() if (TD / "README.md").exists() else "---\nlicense: other\nconfigs:\n- config_name: laws\n data_files: data/laws.parquet\n default: true\n- config_name: articles\n data_files: data/articles.parquet\n---\n"
11
+ rd = re.sub(r"(?m)^\| Laws / instruments \| [\d,]+ \|$", f"| Laws / instruments | {S['laws_rows']:,} |", rd)
12
+ rd = re.sub(r"(?m)^\| Articles \| [\d,]+ \|$", f"| Articles | {S['articles_rows']:,} |", rd)
13
+ deg = S["degraded"]; q = S["quality"]
14
+ L = ["", "## Batch mu_b1 update (AGO consolidated Acts A-Z)", "",
15
+ f"Diff-limited append on top of `{S['repo']}`@{S['parent'][:12]}: laws/articles {S['tip_laws']}/{S['tip_articles']:,} -> "
16
+ f"{S['laws_rows']:,}/{S['articles_rows']:,} (new instruments {S['new_laws']}, new article rows {S['new_articles']:,}). Every row already in the dataset is kept unchanged; new rows follow them.", "",
17
+ "- Source: the Attorney General's Office 'Acts A-Z' pages (attorneygeneral.govmu.org, Laws of Mauritius), one consolidated PDF per Act "
18
+ "(Revised Laws of Mauritius layout). Live official pages only; robots.txt checked on every hop; no archives, logins or forms.",
19
+ "- New rows carry `source_type` = `mauritius_ago_revised_laws_acts_az` and `metadata_json.batch` = `mu_b1` (listing page, file name, PDF sha256, Last-Modified, bounds, printed Act number line).",
20
+ "- Duplicates dropped: identical PDFs, the same Act listed twice under two file names (newest copy kept) and Acts already in this dataset (normalised title + year); see `manifests/mu_b1_drops.jsonl`.",
21
+ "- Every new article `text` is a verbatim slice `laws.text[char_start:char_end]` (offsets in the article's `metadata_json`, ascending). "
22
+ "Arrangement-of-sections lines with no body are not articles (listed in `manifests/known_gaps.json`); repealed/spent sections printed as "
23
+ "'Repealed by ...' or 'N. —' are kept with `metadata_json.body_status` = `repealed_placeholder`; Schedules are separate `-sch` articles.",
24
+ "- The Act number and year in the listing/file name are checked against the printed title block; mismatches are listed in `manifests/known_gaps.json` (the printed value is used).",
25
+ "- Free-webmail addresses are redacted as `[redacted-webmail]` (`manifests/webmail_redactions.json`, offsets only).",
26
+ "- `scrapers/mu_b1/`: complete code for this batch with a how-to-run README; pinned versions in `scrapers/requirements.txt`; file hashes in `manifests/mu_b1_code.json`; `SHA256SUMS` covers every file of the pack.", "",
27
+ "### License / reuse (batch mu_b1)", "", S["license_paraphrase"], "",
28
+ "### OCR and text quality (batch mu_b1)", "",
29
+ f"- Text source: the PDFs' own text layer (pdftotext -layout) for {sum(1 for x in q if x['text_source'] == 'pdf_text_layer')} instruments; tesseract OCR (eng, system tessdata) for {sum(1 for x in q if x['text_source'] == 'ocr')}.",
30
+ "- DEGRADED means: OCR mean word confidence below 80, or more than 8 % of a text layer's characters outside printable Latin text.",
31
+ f"- Whole-text fallback (no usable numbered sections, or one section dominating): {S['whole_text_fallback']} instruments (listed in `manifests/known_gaps.json`).", ""]
32
+ L += (["DEGRADED items:", ""] + [f"- {d['title']} ({d['text_source']}, " + (f"confidence {d['mean_conf']}" if d['text_source'] == 'ocr' else f"garble {d['garble']}") + ")" for d in deg] + [""]) if deg else ["DEGRADED items: none.", ""]
33
+ L += ["### Known gaps (batch mu_b1)", "",
34
+ "- The A-Z pages are the AGO's consolidated set; Acts passed after the last consolidation on the site may be missing or not yet consolidated.",
35
+ "- Drops by reason: " + ", ".join(f"{k} {v}" for k, v in sorted(S["drops"].items())) + ".", ""]
36
+ (P / "README.md").write_text(rd.rstrip("\n") + "\n" + "\n".join(L))
37
+ md = (TD / "MANIFEST.md").read_text() if (TD / "MANIFEST.md").exists() else "# MANIFEST\n"
38
+ h = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
39
+ M = ["", "## batch mu_b1 (diff-limited append)", "", f"- parent: {S['parent']}", f"- laws_rows: {S['laws_rows']} (tip {S['tip_laws']}, new {S['new_laws']})",
40
+ f"- articles_rows: {S['articles_rows']} (tip {S['tip_articles']}, new {S['new_articles']})",
41
+ f"- laws_sha256: {h(P / 'data/laws.parquet')}", f"- articles_sha256: {h(P / 'data/articles.parquet')}",
42
+ f"- compression: {S['codec'].lower()}; row groups 1 (copied from the tip)", "- collector: scrapers/mu_b1/collect_mu.py (pipeline scrapers/mu_b1/pipeline_mu.sh)",
43
+ f"- drops: {json.dumps(S['drops'])}", f"- heading-only rows dropped {S['heading_only_dropped']}; repeal placeholders kept {S['repealed_placeholders']}; schedules {S['schedules']}; whole-text fallback {S['whole_text_fallback']}",
44
+ "- MANIFEST.json / provenance/changes.json: " + ("updated additively" if any(f in S["tip_files"] for f in ("MANIFEST.json", "provenance/changes.json")) else "not present on the parent commit (not created by this batch)"),
45
+ "- checksums: SHA256SUMS", ""]
46
+ (P / "MANIFEST.md").write_text(md.rstrip("\n") + "\n" + "\n".join(M))
scrapers/mu_b1/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Exact versions used to build mu_b1 (pip freeze of the libraries the scrapers import; Python 3.10+).
2
+ certifi==2026.7.22
3
+ pyarrow==25.0.1
4
+ PyYAML==6.0.3
5
+ requests==2.34.2
6
+ urllib3==2.8.0
7
+ # System tools (not pip): poppler-utils (pdftotext/pdfinfo/pdftoppm), tesseract 5 + eng tessdata, ripgrep (rg).
scrapers/mu_b1/robots_guard.py ADDED
@@ -0,0 +1,1277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """robots.txt guard for every shared fetch helper (CoS standing rule 2026-10-01).
3
+
4
+ Rule: before ANY download, fetch and honor the host's robots.txt (incl.
5
+ Crawl-delay), snapshot it with its UTC date, and never fetch a disallowed path
6
+ (report it instead).
7
+
8
+ What this module does
9
+ * fetches robots.txt once per (scheme, host) and caches it for the run;
10
+ * saves a dated snapshot <ROOT>/<cc>/logs/robots/<host>_<YYYY-MM-DD UTC>.txt
11
+ and appends a record to <ROOT>/<cc>/logs/robots/robots_snapshots.jsonl;
12
+ * evaluates rules Google-style (RFC 9309): the most specific matching
13
+ user-agent group (our UA product names, else "*"), longest-match Allow/Disallow
14
+ with "*" wildcards and "$" end anchors; Allow wins a length tie.
15
+ (urllib.robotparser does NOT support * and $, so it is not used.)
16
+ * enforces Crawl-delay as the minimum spacing between requests to that host, with ONE
17
+ shared per-host last-request clock (thread-safe) used by guard(), wait(), GuardedSession,
18
+ the guarded_* wrappers and the robots-gated sessions in common / archive_fallbacks: each
19
+ request waits the Crawl-delay once, measured from the last request to that host. A
20
+ pre-flight guard(url)/wait(url) followed by the gated send of that request (same thread,
21
+ same host+path, no other request to the host in between) does not wait a second time;
22
+ * a disallowed URL is NOT fetched: RobotsDisallowed is raised and the event is
23
+ appended to <ROOT>/<cc>/logs/robots_blocked.jsonl;
24
+ * fails CLOSED when robots.txt answers 5xx / 429 / 401 / 403 / non-200 2xx
25
+ (e.g. 202 WAF challenge) / an HTML challenge page, times out or errors at the
26
+ network level (RobotsUnavailable, also logged to robots_blocked.jsonl).
27
+ 404 / 410 (and other 4xx) mean "no rules": allow. A TLS-verification failure
28
+ is retried unverified for robots.txt only (public file; noted in the log).
29
+ * web.archive.org / Common Crawl / archive.is URLs are hosts like any other (Wayback
30
+ fetches are subject to web.archive.org's own robots.txt), AND (CoS ruling 2026-10-01) an
31
+ archive COPY of a URL is only fetched if the ORIGIN's robots.txt allows that URL too:
32
+ for a Wayback replay URL http(s)://web.archive.org/web/<ts>[id_|if_|im_|...]/<orig>
33
+ (or archive.is|ph/<newest|ts>/<orig>) check() also evaluates <orig> against the origin's
34
+ robots.txt; disallowed -> reason "origin_disallow", origin robots.txt unavailable ->
35
+ reason "origin_robots_unavailable" (fail closed, same policy). Discovery that downloads
36
+ no document (Wayback CDX /cdx/search/cdx, calendar /web/*/...) is judged by the archive
37
+ host's robots.txt only. check_archived_copy(orig, archive_url) does the same for other
38
+ archive copies (e.g. a Common Crawl WARC record of <orig>).
39
+ * robots_cached carve-out (CoS 2026-10-03), ARCHIVE copies only: every successful robots.txt
40
+ read (200 rules, or 404/410/other 4xx = allow) is persisted to
41
+ <ROOT>/logs/robots_snapshots/<host>.json (fetched_at, status, http_status, body); a failed
42
+ read never overwrites it. When the ORIGIN's robots.txt cannot be read now, an archive copy
43
+ is judged by that snapshot if it is at most 7 days old (logged as robots_cached; a cached
44
+ Disallow blocks as origin_disallow); no snapshot or an older one stays fail-closed
45
+ (origin_robots_unavailable). Direct live fetches to the origin are unchanged (fail closed).
46
+
47
+ Usage
48
+ import robots_guard as rg
49
+ rg.set_country("gt") # or env ROBOTS_COUNTRY / COLLECTOR_CC
50
+ rg.guard(url) # raises RobotsBlocked, else waits crawl-delay
51
+ d = rg.check(url) # Decision(allowed=..., rule=..., ...) no wait/raise
52
+ s = rg.GuardedSession() # requests.Session; every send() (incl. each
53
+ # redirect hop) goes through guard()
54
+ rg.guarded_curl_run(["curl", "-sL", url], capture_output=True)
55
+ # curl never follows redirects itself (-L stripped,
56
+ # --max-redirs 0); the wrapper follows Location hops
57
+ # (max 10), guard()ing each hop incl. Crawl-delay
58
+ try: ...
59
+ except rg.RobotsBlocked as e: # a PermissionError; put it BEFORE `except Exception`
60
+ rg.log_robots_blocked(e, caller="collect_xx:fetch") # robots_blocked, not a failure
61
+ """
62
+ from __future__ import annotations
63
+
64
+ import hashlib
65
+ import json
66
+ import os
67
+ import re
68
+ import sys
69
+ import threading
70
+ import time
71
+ from dataclasses import dataclass, field, asdict
72
+ from datetime import datetime, timezone
73
+ from pathlib import Path
74
+ from typing import Callable, Optional
75
+ from urllib.parse import urlsplit, unquote, quote
76
+
77
+ ROOT = Path(os.environ.get("LEGAL_CORPORA_ROOT", "legal-corpora"))
78
+ # UA product names we answer to (matched case-insensitively against User-agent lines; RFC 9309 product names).
79
+ OUR_UA_PRODUCTS = ("legal-corpora-collector", "justicedao-legal-corpus")
80
+ ROBOTS_UA = (
81
+ "legal-corpora-collector/1.0 "
82
+ "(research archive of official national gazettes; polite; "
83
+ "contact via local operator)"
84
+ )
85
+ MAX_ROBOTS_BYTES = 512 * 1024 # RFC 9309: parse at least 500 KiB
86
+ ROBOTS_TIMEOUT = (15, 30)
87
+
88
+
89
+ class RobotsBlocked(PermissionError):
90
+ """Base: the guard refused to fetch (do not retry this URL in this run)."""
91
+
92
+ def __init__(self, msg: str, decision: "Decision"):
93
+ super().__init__(msg)
94
+ self.decision = decision
95
+
96
+
97
+ class RobotsDisallowed(RobotsBlocked):
98
+ pass
99
+
100
+
101
+ class RobotsUnavailable(RobotsBlocked):
102
+ """robots.txt could not be read (5xx / timeout / ...): fail closed."""
103
+
104
+
105
+ # ---------------------------------------------------------------- parsing
106
+
107
+ @dataclass
108
+ class Group:
109
+ agents: list = field(default_factory=list)
110
+ rules: list = field(default_factory=list) # (allow: bool, pattern: str)
111
+ crawl_delay: Optional[float] = None
112
+
113
+
114
+ @dataclass
115
+ class Robots:
116
+ groups: list
117
+ sitemaps: list
118
+ raw_sha256: str = ""
119
+
120
+ def select(self, ua_products=OUR_UA_PRODUCTS) -> Optional[Group]:
121
+ """Merge every group naming our most specific product name; else the * groups."""
122
+ toks = [t.lower() for t in ua_products]
123
+ best_len, merged = -1, None
124
+ for g in self.groups:
125
+ for a in g.agents:
126
+ al = a.lower()
127
+ if al == "*":
128
+ continue
129
+ for t in toks:
130
+ # product-name match: the UA line name is a prefix of ours
131
+ if t == al or t.startswith(al):
132
+ if len(al) > best_len:
133
+ best_len, merged = len(al), Group([a], list(g.rules), g.crawl_delay)
134
+ elif len(al) == best_len and merged is not None:
135
+ merged.rules.extend(g.rules)
136
+ if merged.crawl_delay is None:
137
+ merged.crawl_delay = g.crawl_delay
138
+ if merged is not None:
139
+ return merged
140
+ star = None
141
+ for g in self.groups:
142
+ if "*" in g.agents:
143
+ if star is None:
144
+ star = Group(["*"], list(g.rules), g.crawl_delay)
145
+ else:
146
+ star.rules.extend(g.rules)
147
+ if star.crawl_delay is None:
148
+ star.crawl_delay = g.crawl_delay
149
+ return star
150
+
151
+
152
+ _LINE = re.compile(r"^\s*([A-Za-z-]+)\s*:\s*(.*?)\s*$")
153
+
154
+
155
+ def parse_robots(text: str) -> Robots:
156
+ groups: list[Group] = []
157
+ sitemaps: list[str] = []
158
+ cur: Optional[Group] = None
159
+ last_was_agent = False
160
+ text = (text or "")
161
+ for bom in ("\ufeff", "\u00ef\u00bb\u00bf"): # BOM, also when mis-decoded as latin-1
162
+ if text.startswith(bom):
163
+ text = text[len(bom):]
164
+ for raw in text.splitlines():
165
+ line = raw.split("#", 1)[0]
166
+ m = _LINE.match(line)
167
+ if not m:
168
+ continue
169
+ key, val = m.group(1).lower(), m.group(2)
170
+ if key in ("user-agent", "useragent", "user agent"):
171
+ if cur is None or not last_was_agent:
172
+ cur = Group()
173
+ groups.append(cur)
174
+ cur.agents.append(val.strip())
175
+ last_was_agent = True
176
+ continue
177
+ if key == "sitemap":
178
+ sitemaps.append(val)
179
+ continue # sitemap does not end an agent run
180
+ last_was_agent = False
181
+ if cur is None:
182
+ continue # rules before any User-agent are ignored
183
+ if key in ("allow", "disallow"):
184
+ if key == "disallow" and val == "":
185
+ continue # "Disallow:" (empty) = allow everything = no rule
186
+ if val == "" and key == "allow":
187
+ continue
188
+ cur.rules.append((key == "allow", val))
189
+ elif key in ("crawl-delay", "crawl_delay"):
190
+ try:
191
+ cur.crawl_delay = float(val)
192
+ except ValueError:
193
+ pass
194
+ sha = hashlib.sha256((text or "").encode("utf-8", "replace")).hexdigest()
195
+ return Robots(groups, sitemaps, sha)
196
+
197
+
198
+ def _norm(s: str) -> str:
199
+ """Normalise percent-encoding so /a%7Eb and /a~b compare equal."""
200
+ try:
201
+ return quote(unquote(s), safe="/?&=;:@!$'()*+,~-._%")
202
+ except Exception:
203
+ return s
204
+
205
+
206
+ def _glob_prefix(pat: str, s: str, anchored: bool) -> bool:
207
+ """Wildcard match ('*' = any run) WITHOUT regex backtracking (ReDoS-safe, O(len*len)).
208
+
209
+ Unanchored patterns match a prefix of s (implicit trailing '*'); '$' anchors the end.
210
+ """
211
+ if not anchored:
212
+ pat = pat + "*"
213
+ i = j = 0
214
+ star, mark = -1, 0
215
+ n, m = len(pat), len(s)
216
+ while j < m:
217
+ if i < n and pat[i] == "*":
218
+ star, mark = i, j
219
+ i += 1
220
+ elif i < n and pat[i] == s[j]:
221
+ i += 1
222
+ j += 1
223
+ elif star != -1:
224
+ i = star + 1
225
+ mark += 1
226
+ j = mark
227
+ else:
228
+ return False
229
+ while i < n and pat[i] == "*":
230
+ i += 1
231
+ return i == n
232
+
233
+
234
+ _pat_cache: dict = {}
235
+
236
+
237
+ def _prep(pattern: str):
238
+ v = _pat_cache.get(pattern)
239
+ if v is None:
240
+ p = _norm(pattern)
241
+ anchored = p.endswith("$")
242
+ if anchored:
243
+ p = p[:-1]
244
+ p = re.sub(r"\*{2,}", "*", p)
245
+ v = (p, anchored)
246
+ if len(_pat_cache) < 50000:
247
+ _pat_cache[pattern] = v
248
+ return v
249
+
250
+
251
+ def match_rule(group: Optional[Group], path: str):
252
+ """Return (allowed, matched_rule_str or None). Longest pattern wins; Allow wins ties."""
253
+ if group is None or not group.rules:
254
+ return True, None
255
+ if not path:
256
+ path = "/"
257
+ p = _norm(path)
258
+ best = None # (len, allow, pattern)
259
+ for allow, pattern in group.rules:
260
+ pat = pattern if pattern.startswith(("/", "*")) else "/" + pattern
261
+ gp, anchored = _prep(pat)
262
+ if _glob_prefix(gp, p, anchored):
263
+ ln = len(pattern)
264
+ if best is None or ln > best[0] or (ln == best[0] and allow and not best[1]):
265
+ best = (ln, allow, pattern)
266
+ if best is None:
267
+ return True, None
268
+ return best[1], f"{'Allow' if best[1] else 'Disallow'}: {best[2]}"
269
+
270
+
271
+ def path_of(url: str) -> str:
272
+ sp = urlsplit(url)
273
+ path = sp.path or "/"
274
+ if sp.query:
275
+ path += "?" + sp.query
276
+ return path
277
+
278
+
279
+ def evaluate(robots_text: Optional[str], url_or_path: str, ua_products=OUR_UA_PRODUCTS):
280
+ """Pure helper (used by the audit): (allowed, rule, crawl_delay, agent_group)."""
281
+ if robots_text is None:
282
+ return True, None, None, None
283
+ rb = parse_robots(robots_text)
284
+ g = rb.select(ua_products)
285
+ path = path_of(url_or_path) if "://" in url_or_path else url_or_path
286
+ if path in ("/robots.txt",):
287
+ return True, None, (g.crawl_delay if g else None), (g.agents[0] if g else None)
288
+ ok, rule = match_rule(g, path)
289
+ return ok, rule, (g.crawl_delay if g else None), (g.agents[0] if g else None)
290
+
291
+
292
+ # ---------------------------------------------------------------- runtime
293
+
294
+ @dataclass
295
+ class HostState:
296
+ origin: str
297
+ status: str # ok | missing | unavailable
298
+ http_status: int = 0
299
+ robots: Optional[Robots] = None
300
+ group: Optional[Group] = None
301
+ crawl_delay: float = 0.0
302
+ snapshot: str = ""
303
+ fetched_at: str = ""
304
+ error: str = ""
305
+
306
+
307
+ @dataclass
308
+ class Decision:
309
+ allowed: bool
310
+ url: str
311
+ host: str
312
+ reason: str # allowed | disallowed | robots_unavailable
313
+ rule: Optional[str] = None
314
+ agent: Optional[str] = None
315
+ crawl_delay: float = 0.0
316
+ robots_status: str = ""
317
+ robots_http_status: int = 0
318
+ snapshot: str = ""
319
+ robots_fetched_at: str = ""
320
+ origin_url: str = "" # archive copies: the original URL whose origin robots.txt was checked
321
+ robots_source: str = "" # "cached" when the origin decision came from a persisted snapshot
322
+
323
+
324
+ _lock = threading.RLock()
325
+ _host_locks: dict = {}
326
+ _cache: dict = {} # origin -> HostState
327
+ _last_req: dict = {} # host -> monotonic time of last request (THE shared per-host clock)
328
+ _tls = threading.local() # per-thread pre-flight grant: (host, path, clock stamp)
329
+ _country: Optional[str] = None
330
+ _robots_fetcher: Optional[Callable] = None # test hook: fn(robots_url) -> (status, text)
331
+
332
+
333
+ def set_country(cc: Optional[str]) -> None:
334
+ global _country
335
+ _country = (cc or "").strip().lower() or None
336
+
337
+
338
+ def _utc_iso() -> str:
339
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
340
+
341
+
342
+ def country() -> str:
343
+ if _country:
344
+ return _country
345
+ for k in ("ROBOTS_COUNTRY", "COLLECTOR_CC", "COUNTRY_CC", "CC"):
346
+ v = (os.environ.get(k) or "").strip().lower()
347
+ if re.fullmatch(r"[a-z]{2}", v):
348
+ return v
349
+ m = re.search(r"(?:collect|fill|densify|expand|fix)_([a-z]{2})(?:_|\.py|$)", os.path.basename(sys.argv[0] if sys.argv else ""))
350
+ if m and (ROOT / m.group(1)).is_dir():
351
+ return m.group(1)
352
+ m = re.match(r"^_([a-z]{2})_", os.path.basename(sys.argv[0] if sys.argv else ""))
353
+ if m and (ROOT / m.group(1)).is_dir():
354
+ return m.group(1)
355
+ return "_shared"
356
+
357
+
358
+ def _logdir() -> Path:
359
+ cc = country()
360
+ return (ROOT / "logs") if cc == "_shared" else (ROOT / cc / "logs")
361
+
362
+
363
+ def _append_jsonl(path: Path, row: dict) -> None:
364
+ try:
365
+ path.parent.mkdir(parents=True, exist_ok=True)
366
+ with _lock:
367
+ with path.open("a", encoding="utf-8") as fh:
368
+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")
369
+ except Exception:
370
+ pass
371
+
372
+
373
+ # --- TLS for the robots.txt fetch: always verified (certifi by default), optional per-host CA bundle ----------
374
+ # Hosts whose server omits an intermediate can be given a bundle (certifi/system CAs + that intermediate):
375
+ # * in code: robots_guard.set_ca_bundle("www.example.gov", "/path/bundle.pem") (or update ROBOTS_CA_BUNDLES)
376
+ # * by env: ROBOTS_GUARD_CA_BUNDLES='{"www.example.gov": "/path/bundle.pem"}' or 'host=/path.pem,host2=/p2.pem'
377
+ # A host entry also covers its subdomains ("example.gov" matches "www.example.gov"). A TLS failure is returned like
378
+ # any other fetch error (status 0), so the host is treated as robots-unavailable, i.e. fail closed.
379
+ ROBOTS_CA_BUNDLES: dict = {}
380
+
381
+
382
+ def _env_ca_bundles() -> dict:
383
+ raw = (os.environ.get("ROBOTS_GUARD_CA_BUNDLES") or "").strip()
384
+ if not raw:
385
+ return {}
386
+ try:
387
+ if raw.startswith("{"):
388
+ return {str(k).lower(): str(v) for k, v in json.loads(raw).items()}
389
+ out = {}
390
+ for part in re.split(r"[,;]", raw):
391
+ if "=" in part:
392
+ k, v = part.split("=", 1)
393
+ out[k.strip().lower()] = v.strip()
394
+ return out
395
+ except Exception:
396
+ return {}
397
+
398
+
399
+ def set_ca_bundle(host: str, path) -> None:
400
+ """Register a CA bundle for host (and its subdomains) for the robots.txt fetch."""
401
+ ROBOTS_CA_BUNDLES[(host or "").lower().strip(".")] = str(path)
402
+
403
+
404
+ def _default_ca() -> object:
405
+ try:
406
+ import certifi
407
+ return certifi.where()
408
+ except Exception:
409
+ return True # requests' own default CA store; still verified
410
+
411
+
412
+ def ca_verify_for(url_or_host: str) -> object:
413
+ """verify= value for requests: the host bundle if one is registered, else certifi. Never False."""
414
+ host = (urlsplit(url_or_host).hostname if "://" in url_or_host else url_or_host) or ""
415
+ host = host.lower().strip(".")
416
+ table = {**_env_ca_bundles(), **ROBOTS_CA_BUNDLES}
417
+ h = host
418
+ while h:
419
+ if h in table and table[h] and os.path.exists(table[h]):
420
+ return table[h]
421
+ h = h.split(".", 1)[1] if "." in h else ""
422
+ return _default_ca()
423
+
424
+
425
+ # --- per-host TLS: clear ONLY ssl.VERIFY_X509_STRICT (CoS GO 2026-10-16, Taiwan municipal law hosts) ------------
426
+ # Python 3.13 / urllib3 2.3+ turn on VERIFY_X509_STRICT, which rejects some TW government certificates
427
+ # ("Missing Subject Key Identifier") that OpenSSL otherwise verifies fine. For the EXACT hosts below (no subdomains,
428
+ # no wildcards) the SSL context is the normal urllib3/certifi one with that single flag cleared:
429
+ # * verify_mode stays ssl.CERT_REQUIRED, check_hostname stays True, the full chain is still verified against
430
+ # certifi (or the host's registered CA bundle), all other verify_flags (e.g. VERIFY_X509_PARTIAL_CHAIN) unchanged;
431
+ # * verify=False is refused for these hosts (never used anywhere);
432
+ # * every use (context build and every request) is appended to <logdir>/tls/tls_relaxed_strict.jsonl.
433
+ # Applied to the robots.txt fetch (_default_fetch) and to GuardedSession (and guarded_get/... wrappers). Not applied
434
+ # to guarded_urlopen / guarded_curl_run (curl uses system OpenSSL, which does not enable X509_STRICT).
435
+ import ssl as _ssl # noqa: E402
436
+
437
+ TLS_RELAX_STRICT_HOSTS = frozenset({
438
+ "laws.gov.taipei", # Taipei City law system (臺北市法規查詢系統)
439
+ "www.laws.taipei.gov.tw", # Taipei legacy host (301 -> laws.gov.taipei)
440
+ "web.law.ntpc.gov.tw", # New Taipei City (新北市法規查詢系統)
441
+ "outlaw.kcg.gov.tw", # Kaohsiung City (高雄市法規查詢系統)
442
+ })
443
+
444
+
445
+ class TLSPolicyError(ValueError):
446
+ """Refused TLS configuration (e.g. verify=False on a relaxed-strict host, or a host not on the allowlist)."""
447
+
448
+
449
+ def tls_relax_strict_allowed(url_or_host: str) -> bool:
450
+ host = (urlsplit(url_or_host).hostname if "://" in url_or_host else url_or_host) or ""
451
+ return host.lower().strip(".") in TLS_RELAX_STRICT_HOSTS
452
+
453
+
454
+ def _log_tls_relax(row: dict) -> None:
455
+ _append_jsonl(_logdir() / "tls" / "tls_relaxed_strict.jsonl", {"ts": _utc_iso(), "country": country(), **row})
456
+
457
+
458
+ def relaxed_strict_ssl_context(host: str, cafile=None, caller: str = ""):
459
+ """SSL context for an allowlisted host: default verified context minus VERIFY_X509_STRICT only."""
460
+ host = (host or "").lower().strip(".")
461
+ if host not in TLS_RELAX_STRICT_HOSTS:
462
+ raise TLSPolicyError(f"host not on TLS_RELAX_STRICT_HOSTS: {host!r}")
463
+ try:
464
+ from urllib3.util.ssl_ import create_urllib3_context
465
+ ctx = create_urllib3_context(cert_reqs=_ssl.CERT_REQUIRED)
466
+ except Exception: # pragma: no cover - urllib3 missing
467
+ ctx = _ssl.create_default_context()
468
+ if cafile is None:
469
+ cafile = ca_verify_for(host)
470
+ if isinstance(cafile, str) and os.path.isdir(cafile):
471
+ ctx.load_verify_locations(capath=cafile)
472
+ elif isinstance(cafile, str):
473
+ ctx.load_verify_locations(cafile=cafile)
474
+ else:
475
+ ctx.load_default_certs()
476
+ before = int(ctx.verify_flags)
477
+ ctx.verify_flags &= ~_ssl.VERIFY_X509_STRICT
478
+ ctx.verify_mode = _ssl.CERT_REQUIRED
479
+ ctx.check_hostname = True
480
+ assert ctx.verify_mode == _ssl.CERT_REQUIRED and ctx.check_hostname
481
+ assert not (ctx.verify_flags & _ssl.VERIFY_X509_STRICT)
482
+ _log_tls_relax({"event": "context", "host": host, "caller": caller, "cafile": str(cafile),
483
+ "verify_flags_before": before, "verify_flags_after": int(ctx.verify_flags),
484
+ "verify_mode": "CERT_REQUIRED", "check_hostname": True})
485
+ return ctx
486
+
487
+
488
+ try:
489
+ from requests.adapters import HTTPAdapter as _HTTPAdapter
490
+
491
+ class _RelaxedStrictAdapter(_HTTPAdapter):
492
+ """HTTPS adapter bound to ONE allowlisted host; pools use relaxed_strict_ssl_context(host)."""
493
+
494
+ def __init__(self, host: str, caller: str = "", **kw):
495
+ self._rs_host = host.lower().strip(".")
496
+ if self._rs_host not in TLS_RELAX_STRICT_HOSTS:
497
+ raise TLSPolicyError(f"host not on TLS_RELAX_STRICT_HOSTS: {host!r}")
498
+ self._rs_caller = caller
499
+ super().__init__(**kw)
500
+
501
+ def init_poolmanager(self, *a, **kw):
502
+ kw["ssl_context"] = relaxed_strict_ssl_context(self._rs_host, caller=self._rs_caller)
503
+ return super().init_poolmanager(*a, **kw)
504
+
505
+ def proxy_manager_for(self, proxy, **kw):
506
+ kw["ssl_context"] = relaxed_strict_ssl_context(self._rs_host, caller=self._rs_caller + ":proxy")
507
+ return super().proxy_manager_for(proxy, **kw)
508
+
509
+ def send(self, request, **kw):
510
+ host = (urlsplit(request.url).hostname or "").lower()
511
+ if host != self._rs_host:
512
+ raise TLSPolicyError(f"relaxed adapter for {self._rs_host} got {host}")
513
+ if kw.get("verify") is False:
514
+ _log_tls_relax({"event": "refused_verify_false", "host": host, "url": request.url, "caller": self._rs_caller})
515
+ raise TLSPolicyError(f"verify=False refused for {host}")
516
+ _log_tls_relax({"event": "request", "host": host, "method": request.method, "url": request.url,
517
+ "caller": self._rs_caller})
518
+ return super().send(request, **kw)
519
+
520
+ class TLSPolicyAdapter(_HTTPAdapter):
521
+ """Mounted on https:// : allowlisted hosts go through their _RelaxedStrictAdapter, all others unchanged."""
522
+
523
+ def __init__(self, caller: str = "", **kw):
524
+ self._caller, self._relaxed = caller, {}
525
+ super().__init__(**kw)
526
+
527
+ def send(self, request, **kw):
528
+ host = (urlsplit(request.url).hostname or "").lower().strip(".")
529
+ if urlsplit(request.url).scheme == "https" and host in TLS_RELAX_STRICT_HOSTS:
530
+ ad = self._relaxed.get(host)
531
+ if ad is None:
532
+ ad = self._relaxed[host] = _RelaxedStrictAdapter(host, caller=self._caller)
533
+ return ad.send(request, **kw)
534
+ return super().send(request, **kw)
535
+
536
+ def close(self):
537
+ for ad in self._relaxed.values():
538
+ ad.close()
539
+ super().close()
540
+ except Exception: # pragma: no cover - requests missing
541
+ TLSPolicyAdapter = None # type: ignore
542
+
543
+
544
+ def mount_tls_policy(sess, caller: str = ""):
545
+ """Mount TLSPolicyAdapter on a requests.Session (no-op for objects without .mount, e.g. test fakes)."""
546
+ if TLSPolicyAdapter is not None and hasattr(sess, "mount"):
547
+ sess.mount("https://", TLSPolicyAdapter(caller=caller))
548
+ return sess
549
+
550
+
551
+ # --- robots.txt redirect policy (CoS GO 2026-10-14 21:39 PT, "one-hop" fix) ---------------------------------------
552
+ # Redirects on a robots.txt fetch are followed manually, one hop at a time:
553
+ # * same-host hop (scheme change allowed): followed, at most ROBOTS_MAX_HOPS hops in total;
554
+ # * cross-host hop: followed ONLY if the target path is exactly "/robots.txt" (that host's robots file);
555
+ # any other cross-host target (e.g. a bare home page) is NOT fetched -> status 0 -> robots unavailable -> fail closed;
556
+ # * a repeated URL (loop), > ROBOTS_MAX_HOPS hops or a non-http(s) target -> status 0 -> fail closed;
557
+ # * every hop after the first waits >= ROBOTS_HOP_MIN_INTERVAL s (and the host's known Crawl-delay) on the shared
558
+ # per-host clock and stamps it; every hop is appended to <logdir>/robots/robots_fetch_hops.jsonl.
559
+ # Incident: 2026-10-14 ir.parliament.gh/robots.txt 302 -> https://repository.parliament.gh (home page) was fetched
560
+ # before that host's robots.txt had been read, unpaced and unlogged.
561
+ ROBOTS_MAX_HOPS = 5
562
+ ROBOTS_HOP_MIN_INTERVAL = float(os.environ.get("ROBOTS_HOP_MIN_INTERVAL", "8") or 8)
563
+
564
+
565
+ def _robots_hop_log(row: dict) -> None:
566
+ _append_jsonl(_logdir() / "robots" / "robots_fetch_hops.jsonl", {"ts": _utc_iso(), "country": country(), **row})
567
+
568
+
569
+ def _robots_hop_clock(url: str, paced: bool) -> None:
570
+ """Stamp (and, for redirect hops, first wait on) the shared per-host clock. Never touches the thread's grant."""
571
+ sp = urlsplit(url)
572
+ host = (sp.hostname or "").lower()
573
+ st = _cache.get(f"{(sp.scheme or 'http').lower()}://{sp.netloc.lower()}")
574
+ gap = max(ROBOTS_HOP_MIN_INTERVAL, st.crawl_delay if st else 0.0) if paced else 0.0
575
+ with _lock:
576
+ hl = _host_locks.setdefault("wait:" + host, threading.Lock())
577
+ with hl:
578
+ last = _last_req.get(host)
579
+ if gap > 0 and last is not None:
580
+ delta = gap - (time.monotonic() - last)
581
+ if delta > 0:
582
+ time.sleep(delta)
583
+ _last_req[host] = time.monotonic()
584
+
585
+
586
+ def _robots_redirect_refusal(cur: str, nxt: str, seen: set, hops: int) -> str:
587
+ """'' if the hop cur -> nxt may be fetched, else the fail-closed reason."""
588
+ sp = urlsplit(nxt)
589
+ if sp.scheme not in ("http", "https") or not sp.hostname:
590
+ return f"redirect_to_unsupported_scheme: {nxt}"
591
+ if nxt in seen:
592
+ return f"robots_redirect_loop: {nxt}"
593
+ if hops >= ROBOTS_MAX_HOPS:
594
+ return "too_many_redirects"
595
+ if (sp.hostname or "").lower() != (urlsplit(cur).hostname or "").lower() and sp.path != "/robots.txt":
596
+ return f"robots_redirect_cross_host_not_followed: {nxt}"
597
+ return ""
598
+
599
+
600
+ def _default_fetch(robots_url: str):
601
+ """Returns (http_status, text, error). Uses a plain session (never guarded).
602
+ TLS is always verified (per-host CA bundle or certifi). Redirects are followed manually under the one-hop policy
603
+ above (same host: ok; cross host: only to that host's /robots.txt; else fail closed). Any refusal, loop, network
604
+ or TLS error returns status 0 => robots unavailable => fail closed."""
605
+ import requests
606
+ from urllib.parse import urljoin
607
+ note = ""
608
+ try:
609
+ url, r, hops, seen = robots_url, None, 0, {robots_url}
610
+ with requests.Session() as sess:
611
+ mount_tls_policy(sess, caller="robots_fetch")
612
+ while True:
613
+ _robots_hop_clock(url, paced=hops > 0)
614
+ r = sess.get(url, timeout=ROBOTS_TIMEOUT, allow_redirects=False, verify=ca_verify_for(url),
615
+ headers={"User-Agent": ROBOTS_UA, "Accept": "text/plain,*/*"}, stream=True)
616
+ loc = r.headers.get("Location")
617
+ if r.status_code in (301, 302, 303, 307, 308) and loc:
618
+ r.close()
619
+ nxt = urljoin(url, loc)
620
+ why = _robots_redirect_refusal(url, nxt, seen, hops)
621
+ _robots_hop_log({"robots_url": robots_url, "hop": hops, "url": url, "status": r.status_code,
622
+ "location": nxt, "action": "refused" if why else "follow", "reason": why or None})
623
+ if why:
624
+ return 0, "", why[:300]
625
+ if urlsplit(nxt).hostname != urlsplit(url).hostname:
626
+ note = f"cross_host_robots_redirect: {nxt}"[:300]
627
+ seen.add(nxt); url = nxt; hops += 1
628
+ continue
629
+ if hops:
630
+ _robots_hop_log({"robots_url": robots_url, "hop": hops, "url": url, "status": r.status_code,
631
+ "action": "final"})
632
+ break
633
+ raw = b""
634
+ for chunk in r.iter_content(65536):
635
+ raw += chunk
636
+ if len(raw) >= MAX_ROBOTS_BYTES:
637
+ break
638
+ r.close()
639
+ raw = raw[:MAX_ROBOTS_BYTES]
640
+ try: # RFC 9309: robots.txt is UTF-8 (strip a BOM)
641
+ txt = raw.decode("utf-8-sig")
642
+ except UnicodeDecodeError:
643
+ txt = raw.decode(r.encoding or "latin-1", "replace")
644
+ return r.status_code, txt, note
645
+ except Exception as exc: # timeout, DNS, TLS (SSLError => fail closed), reset ...
646
+ return 0, "", f"{type(exc).__name__}: {exc}"[:300]
647
+
648
+
649
+ _CHALLENGE = re.compile(r"just a moment|cf-browser-verification|challenge-platform|captcha|awswaf|"
650
+ r"checking your browser|enable javascript|request rejected|access denied|"
651
+ r"rejected request|support id", re.I) # + F5 BIG-IP ASM page (CoS 2026-10-16; OCM/Senate KH)
652
+
653
+
654
+ def _load_host(origin: str, host: str) -> HostState:
655
+ with _lock:
656
+ st = _cache.get(origin)
657
+ if st is not None:
658
+ return st
659
+ hl = _host_locks.setdefault(origin, threading.Lock())
660
+ with hl:
661
+ with _lock:
662
+ st = _cache.get(origin)
663
+ if st is not None:
664
+ return st
665
+ robots_url = origin + "/robots.txt"
666
+ fetch = _robots_fetcher or _default_fetch
667
+ code, text, err = fetch(robots_url)
668
+ now = _utc_iso()
669
+ looks_html = bool(re.search(r"<\s*(html|!doctype)", (text or "")[:600], re.I))
670
+ if code == 200 and not looks_html:
671
+ rb = parse_robots(text)
672
+ g = rb.select()
673
+ st = HostState(origin, "ok", code, rb, g, float(g.crawl_delay or 0) if g else 0.0, fetched_at=now, error=err)
674
+ elif code == 200 and looks_html and _CHALLENGE.search((text or "")[:4000]):
675
+ st = HostState(origin, "unavailable", code, fetched_at=now, error="waf_challenge_page")
676
+ elif code == 200 and looks_html:
677
+ st = HostState(origin, "missing", code, fetched_at=now, error="html_body_treated_as_no_rules")
678
+ elif code in (401, 403, 429) or code >= 500 or code == 0 or (200 < code < 300):
679
+ st = HostState(origin, "unavailable", code, fetched_at=now, error=err or f"http_{code}")
680
+ else: # 404, 410, other 4xx/3xx-without-target: no rules -> allow
681
+ st = HostState(origin, "missing", code, fetched_at=now, error=f"http_{code}" + (f";{err}" if err else ""))
682
+ # dated snapshot (also for missing/unavailable, so the decision is auditable)
683
+ day = now[:10]
684
+ safe_host = re.sub(r"[^A-Za-z0-9.-]+", "_", host)
685
+ snap = _logdir() / "robots" / f"{safe_host}_{day}.txt"
686
+ try:
687
+ snap.parent.mkdir(parents=True, exist_ok=True)
688
+ body = text if st.status == "ok" else f"# robots.txt {robots_url} status={st.status} http={code} {st.error}\n"
689
+ prev = snap.read_text(encoding="utf-8", errors="replace") if snap.exists() else None
690
+ if prev != body:
691
+ snap.write_text(body, encoding="utf-8")
692
+ st.snapshot = str(snap.relative_to(ROOT))
693
+ except Exception:
694
+ pass
695
+ _append_jsonl(_logdir() / "robots" / "robots_snapshots.jsonl", {
696
+ "fetched_at": now, "country": country(), "host": host, "robots_url": robots_url,
697
+ "http_status": code, "status": st.status, "error": st.error or None,
698
+ "sha256": hashlib.sha256((text or "").encode("utf-8", "replace")).hexdigest() if st.status == "ok" else None,
699
+ "bytes": len(text or ""), "agent_group": (st.group.agents[0] if st.group else None),
700
+ "crawl_delay": st.crawl_delay or None, "snapshot": st.snapshot,
701
+ })
702
+ if st.status in ("ok", "missing"):
703
+ _save_persisted_snapshot(origin, host, st, text, robots_url)
704
+ with _lock:
705
+ _cache[origin] = st
706
+ return st
707
+
708
+
709
+ CACHED_MAX_AGE_S = 7 * 24 * 3600
710
+
711
+
712
+ def _persist_dir() -> Path:
713
+ return ROOT / "logs" / "robots_snapshots"
714
+
715
+
716
+ def _persist_path(host: str) -> Path:
717
+ return _persist_dir() / (re.sub(r"[^A-Za-z0-9.-]+", "_", host or "_") + ".json")
718
+
719
+
720
+ def _save_persisted_snapshot(origin: str, host: str, st: "HostState", text: str, robots_url: str) -> None:
721
+ """Successful robots.txt read only (status ok / missing): write <host>.json atomically."""
722
+ try:
723
+ p = _persist_path(host)
724
+ p.parent.mkdir(parents=True, exist_ok=True)
725
+ row = {"host": host, "origin": origin, "robots_url": robots_url, "fetched_at": st.fetched_at,
726
+ "status": st.status, "http_status": st.http_status,
727
+ "body": (text or "") if st.status == "ok" else "",
728
+ "sha256": hashlib.sha256((text or "").encode("utf-8", "replace")).hexdigest() if st.status == "ok" else None}
729
+ tmp = p.with_name(p.name + f".tmp{os.getpid()}_{threading.get_ident()}")
730
+ tmp.write_text(json.dumps(row, ensure_ascii=False), encoding="utf-8")
731
+ os.replace(tmp, p)
732
+ except Exception:
733
+ pass
734
+
735
+
736
+ def load_persisted_snapshot(host: str) -> Optional[dict]:
737
+ try:
738
+ return json.loads(_persist_path(host).read_text(encoding="utf-8"))
739
+ except Exception:
740
+ return None
741
+
742
+
743
+ def _snapshot_age_s(snap: dict) -> Optional[float]:
744
+ try:
745
+ t = datetime.fromisoformat(str(snap.get("fetched_at")).replace("Z", "+00:00"))
746
+ if t.tzinfo is None:
747
+ t = t.replace(tzinfo=timezone.utc)
748
+ return (datetime.now(timezone.utc) - t).total_seconds()
749
+ except Exception:
750
+ return None
751
+
752
+
753
+ def _cached_origin_decision(original_url: str, od: "Decision") -> Optional["Decision"]:
754
+ """Origin robots.txt unreadable now: decide from a persisted snapshot <= 7 days old, else None."""
755
+ snap = load_persisted_snapshot(od.host)
756
+ if not snap or snap.get("status") not in ("ok", "missing"):
757
+ return None
758
+ age = _snapshot_age_s(snap)
759
+ if age is None or age < -300 or age > CACHED_MAX_AGE_S:
760
+ return None
761
+ base = dict(url=original_url, host=od.host, robots_status="cached", robots_http_status=int(snap.get("http_status") or 0),
762
+ snapshot=str(_persist_path(od.host).relative_to(ROOT)) if str(_persist_path(od.host)).startswith(str(ROOT)) else str(_persist_path(od.host)),
763
+ robots_fetched_at=str(snap.get("fetched_at") or ""), robots_source="cached")
764
+ if snap.get("status") == "missing" or urlsplit(original_url).path == "/robots.txt":
765
+ return Decision(True, reason="allowed", rule="cached: no rules", **base)
766
+ g = parse_robots(snap.get("body") or "").select()
767
+ ok, rule = match_rule(g, path_of(original_url))
768
+ return Decision(ok, reason="allowed" if ok else "disallowed", rule=f"cached {snap.get('fetched_at')}: {rule}",
769
+ agent=(g.agents[0] if g else None), crawl_delay=float(g.crawl_delay or 0) if g else 0.0, **base)
770
+
771
+
772
+ def _log_robots_cached(original_url: str, archive_url: str, cd: "Decision", live: "Decision") -> None:
773
+ row = {"ts": _utc_iso(), "country": country(), "event": "robots_cached", "status": "robots_cached",
774
+ "host": cd.host, "url": archive_url, "origin_url": original_url, "allowed": cd.allowed,
775
+ "rule": cd.rule, "snapshot": cd.snapshot, "snapshot_fetched_at": cd.robots_fetched_at,
776
+ "live_robots_error": live.rule}
777
+ _append_jsonl(_logdir() / "robots_cached.jsonl", row)
778
+ try:
779
+ import logging
780
+ logging.getLogger("robots_guard").warning("robots_cached %s %s via snapshot %s (live robots.txt: %s)",
781
+ "allow" if cd.allowed else "disallow", original_url, cd.robots_fetched_at, live.rule)
782
+ except Exception:
783
+ pass
784
+
785
+
786
+ def check(url: str) -> Decision:
787
+ """Decide without waiting or raising (does fetch robots.txt on first use)."""
788
+ sp = urlsplit(url)
789
+ scheme = (sp.scheme or "http").lower()
790
+ host = (sp.hostname or "").lower()
791
+ if scheme not in ("http", "https") or not host:
792
+ return Decision(False, url, host, "robots_unavailable", rule="unsupported_url")
793
+ origin = f"{scheme}://{sp.netloc.lower()}"
794
+ st = _load_host(origin, host)
795
+ base = dict(url=url, host=host, crawl_delay=st.crawl_delay, robots_status=st.status,
796
+ robots_http_status=st.http_status, snapshot=st.snapshot, robots_fetched_at=st.fetched_at)
797
+ if sp.path == "/robots.txt":
798
+ return Decision(True, reason="allowed", **base)
799
+ if st.status == "unavailable":
800
+ return Decision(False, reason="robots_unavailable", rule=st.error, **base)
801
+ if st.status == "missing":
802
+ d = Decision(True, reason="allowed", **base)
803
+ else:
804
+ ok, rule = match_rule(st.group, path_of(url))
805
+ d = Decision(ok, reason="allowed" if ok else "disallowed", rule=rule,
806
+ agent=(st.group.agents[0] if st.group else None), **base)
807
+ if d.allowed:
808
+ orig = archived_original(url)
809
+ if orig:
810
+ return check_archived_copy(orig, url, _archive_decision=d)
811
+ return d
812
+
813
+
814
+ # Archive replay URLs that serve a COPY of <orig> (not discovery listings such as /web/*/...).
815
+ _REPLAY_RES = (
816
+ re.compile(r"^https?://(?:web|wayback)\.archive\.org/web/\d{1,14}(?:[a-z]{2}_)?/+(?P<orig>.+)$", re.I | re.S),
817
+ re.compile(r"^https?://(?:www\.)?archive\.(?:is|ph|today|li|vn|fo|md)/(?:newest|oldest|timegate|\d{4,14})/+(?P<orig>.+)$",
818
+ re.I | re.S),
819
+ )
820
+
821
+
822
+ def archived_original(url: str) -> Optional[str]:
823
+ """The original URL inside an archive replay URL (Wayback /web/<ts>[mod_]/<orig>,
824
+ archive.is|ph /newest|<ts>/<orig>), else None. Scheme-less originals get http://."""
825
+ for rx in _REPLAY_RES:
826
+ m = rx.match(url or "")
827
+ if not m:
828
+ continue
829
+ orig = m.group("orig").strip()
830
+ orig = re.sub(r"^(https?):/+", lambda mm: mm.group(1).lower() + "://", orig, flags=re.I)
831
+ if not re.match(r"^https?://", orig, re.I):
832
+ if re.match(r"^[a-z][a-z0-9+.-]*:", orig, re.I) and not re.match(r"^[^/:]+:\d+(/|$)", orig):
833
+ return None # non-http original (mailto:, ftp:, ...): nothing to check
834
+ orig = "http://" + orig.lstrip("/")
835
+ return orig
836
+ return None
837
+
838
+
839
+ def check_archived_copy(original_url: str, archive_url: str = "", _archive_decision: Optional[Decision] = None) -> Decision:
840
+ """May an archive copy of original_url be fetched? Checks the ORIGIN's robots.txt for
841
+ original_url (fail closed). Returns the archive decision (or an allow) when the origin
842
+ allows; else a refusing Decision with reason origin_disallow / origin_robots_unavailable."""
843
+ od = check(original_url)
844
+ if not od.allowed and od.reason == "robots_unavailable":
845
+ cd = _cached_origin_decision(original_url, od) # robots_cached carve-out (archive copies only)
846
+ if cd is not None:
847
+ _log_robots_cached(original_url, archive_url or original_url, cd, od)
848
+ od = cd
849
+ a = _archive_decision
850
+ if a is None:
851
+ sp = urlsplit(archive_url or original_url)
852
+ a = Decision(True, archive_url or original_url, (sp.hostname or "").lower(), "allowed")
853
+ if od.allowed:
854
+ if not a.origin_url:
855
+ a.origin_url = original_url
856
+ if od.robots_source:
857
+ a.robots_source = od.robots_source
858
+ return a
859
+ reason = "origin_robots_unavailable" if od.reason in ("robots_unavailable", "origin_robots_unavailable") else "origin_disallow"
860
+ return Decision(False, a.url, a.host, reason, rule=f"origin {od.host}: {od.reason} ({od.rule})",
861
+ agent=od.agent, crawl_delay=a.crawl_delay, robots_status=od.robots_status,
862
+ robots_http_status=od.robots_http_status, snapshot=od.snapshot,
863
+ robots_fetched_at=od.robots_fetched_at, origin_url=original_url, robots_source=od.robots_source)
864
+
865
+
866
+ def _clock(url: str, min_interval: float, send: bool) -> float:
867
+ """The shared per-host clock. Sleeps until max(Crawl-delay, min_interval) has passed since
868
+ the last request to this host, then stamps the clock. Returns the seconds slept.
869
+
870
+ send=False (pre-flight: guard()/wait()): also leaves a one-shot grant for this thread.
871
+ send=True (the actual send: GuardedSession, guarded_* wrappers, gated sessions in
872
+ common/archive_fallbacks): if this thread holds a grant for the same host+path and no
873
+ other request to that host was stamped since, the grant is used instead of waiting again
874
+ (the wait already happened in the pre-flight); the clock is re-stamped at send time.
875
+ Any send clears the thread's grant, so retries / redirect hops / later requests wait."""
876
+ sp = urlsplit(url)
877
+ host = (sp.hostname or "").lower()
878
+ path = sp.path or "/"
879
+ origin = f"{(sp.scheme or 'http').lower()}://{sp.netloc.lower()}"
880
+ st = _cache.get(origin)
881
+ gap = max(float(min_interval or 0), st.crawl_delay if st else 0.0)
882
+ with _lock:
883
+ hl = _host_locks.setdefault("wait:" + host, threading.Lock())
884
+ slept = 0.0
885
+ with hl: # serialises same-host requests across threads
886
+ if send:
887
+ g = getattr(_tls, "grant", None)
888
+ _tls.grant = None
889
+ if g is not None and g[0] == host and g[1] == path and _last_req.get(host) == g[2]:
890
+ _last_req[host] = time.monotonic()
891
+ return 0.0
892
+ if gap > 0:
893
+ last = _last_req.get(host)
894
+ if last is not None:
895
+ delta = gap - (time.monotonic() - last)
896
+ if delta > 0:
897
+ time.sleep(delta)
898
+ slept = delta
899
+ now = time.monotonic()
900
+ _last_req[host] = now
901
+ if not send:
902
+ _tls.grant = (host, path, now)
903
+ return slept
904
+
905
+
906
+ def wait(url: str, min_interval: float = 0.0) -> None:
907
+ """Pre-flight: sleep so requests to this host are >= max(Crawl-delay, min_interval) apart
908
+ (shared per-host clock). The gated send of the same request will not wait again."""
909
+ _clock(url, min_interval, send=False)
910
+
911
+
912
+ def wait_send(url: str, min_interval: float = 0.0) -> float:
913
+ """Send gate: wait on the shared per-host clock unless this thread's pre-flight
914
+ guard()/wait() already waited for this request. Returns the seconds slept."""
915
+ return _clock(url, min_interval, send=True)
916
+
917
+
918
+ _blocked_urls: set = set() # URLs refused by the guard in this process
919
+
920
+
921
+ def report_blocked(d: Decision, caller: str = "") -> None:
922
+ with _lock:
923
+ _blocked_urls.add(d.url)
924
+ row = {"ts": _utc_iso(), "country": country(), "event": "guard_refused", "status": "robots_blocked",
925
+ "host": d.host, "url": d.url,
926
+ "reason": d.reason, "rule": d.rule, "agent_group": d.agent,
927
+ "robots_status": d.robots_status, "robots_http_status": d.robots_http_status,
928
+ "robots_snapshot": d.snapshot, "robots_fetched_at": d.robots_fetched_at,
929
+ "caller": caller or None}
930
+ if getattr(d, "origin_url", ""):
931
+ row["origin_url"] = d.origin_url
932
+ if getattr(d, "robots_source", ""):
933
+ row["robots_source"] = d.robots_source
934
+ _append_jsonl(_logdir() / "robots_blocked.jsonl", row)
935
+
936
+
937
+ def guard(url: str, *, min_interval: float = 0.0, caller: str = "") -> Decision:
938
+ """Call immediately before every request. Raises RobotsBlocked instead of fetching."""
939
+ d = check(url)
940
+ if not d.allowed:
941
+ report_blocked(d, caller)
942
+ exc = RobotsUnavailable if d.reason in ("robots_unavailable", "origin_robots_unavailable") else RobotsDisallowed
943
+ raise exc(f"robots guard: {d.reason} {url} ({d.rule})", d)
944
+ wait(url, min_interval)
945
+ return d
946
+
947
+
948
+ def guard_send(url: str, *, min_interval: float = 0.0, caller: str = "") -> Decision:
949
+ """guard() for the code that actually sends the request (sessions, wrappers): same
950
+ robots decision, but uses a pre-flight guard()'s wait instead of waiting twice."""
951
+ d = check(url)
952
+ if not d.allowed:
953
+ report_blocked(d, caller)
954
+ exc = RobotsUnavailable if d.reason in ("robots_unavailable", "origin_robots_unavailable") else RobotsDisallowed
955
+ raise exc(f"robots guard: {d.reason} {url} ({d.rule})", d)
956
+ wait_send(url, min_interval)
957
+ return d
958
+
959
+
960
+ def log_robots_blocked(exc_or_url, caller: str = "", **extra) -> dict:
961
+ """For a script's `except robots_guard.RobotsBlocked` branch: record the URL as
962
+ robots_blocked (NOT a fetch failure) in <cc>/logs/robots_blocked.jsonl and return the row.
963
+
964
+ The guard has already written an event="guard_refused" row when it raised; this adds an
965
+ event="script_skipped" row naming the script/function that skipped the URL.
966
+ """
967
+ d = getattr(exc_or_url, "decision", None)
968
+ url = d.url if d is not None else str(exc_or_url)
969
+ host = d.host if d is not None else (urlsplit(url).hostname or "").lower()
970
+ row = {"ts": _utc_iso(), "country": country(), "event": "script_skipped", "status": "robots_blocked",
971
+ "host": host, "url": url,
972
+ "reason": d.reason if d is not None else "robots_blocked",
973
+ "rule": d.rule if d is not None else None,
974
+ "exception": type(exc_or_url).__name__ if isinstance(exc_or_url, BaseException) else None,
975
+ "caller": caller or None}
976
+ row.update({k: v for k, v in extra.items() if k not in row})
977
+ with _lock:
978
+ _blocked_urls.add(url)
979
+ _append_jsonl(_logdir() / "robots_blocked.jsonl", row)
980
+ return row
981
+
982
+
983
+ def was_blocked(url: str) -> bool:
984
+ """True if the guard refused this exact URL earlier in this process."""
985
+ return url in _blocked_urls
986
+
987
+
988
+ def reset_cache() -> None:
989
+ with _lock:
990
+ _cache.clear()
991
+ _last_req.clear()
992
+ _blocked_urls.clear()
993
+
994
+
995
+ try:
996
+ import requests as _requests
997
+
998
+ class GuardedSession(_requests.Session):
999
+ """requests.Session whose every send() (each redirect hop too) passes guard()."""
1000
+
1001
+ min_interval: float = 0.0
1002
+
1003
+ def __init__(self, *a, **kw):
1004
+ super().__init__(*a, **kw)
1005
+ mount_tls_policy(self, caller="GuardedSession") # per-host VERIFY_X509_STRICT relax (allowlist only)
1006
+
1007
+ def send(self, request, **kwargs):
1008
+ guard_send(request.url, min_interval=self.min_interval, caller="GuardedSession")
1009
+ return super().send(request, **kwargs)
1010
+ except Exception: # pragma: no cover - requests missing
1011
+ GuardedSession = None # type: ignore
1012
+
1013
+
1014
+ # ---------------------------------------------------------------- drop-in wrappers for our scripts
1015
+ # (CoS ruling R1 2026-10-01: our own collector scripts call these instead of requests/urllib/curl directly)
1016
+
1017
+ def guarded_request(method: str, url: str, **kwargs):
1018
+ """Drop-in for requests.request(): fresh GuardedSession per call (like requests.api), every hop guarded."""
1019
+ with GuardedSession() as s:
1020
+ return s.request(method=method, url=url, **kwargs)
1021
+
1022
+
1023
+ def guarded_get(url: str, params=None, **kwargs):
1024
+ """Drop-in for requests.get()."""
1025
+ return guarded_request("GET", url, params=params, **kwargs)
1026
+
1027
+
1028
+ def guarded_head(url: str, **kwargs):
1029
+ """Drop-in for requests.head() (allow_redirects defaults to False, as in requests)."""
1030
+ kwargs.setdefault("allow_redirects", False)
1031
+ return guarded_request("HEAD", url, **kwargs)
1032
+
1033
+
1034
+ def guarded_post(url: str, data=None, json=None, **kwargs):
1035
+ """Drop-in for requests.post()."""
1036
+ return guarded_request("POST", url, data=data, json=json, **kwargs)
1037
+
1038
+
1039
+ import socket as _socket # noqa: E402
1040
+ import urllib.request as _urlreq # noqa: E402
1041
+
1042
+
1043
+ class _GuardedRedirectHandler(_urlreq.HTTPRedirectHandler):
1044
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
1045
+ guard_send(newurl, caller="guarded_urlopen(redirect)")
1046
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
1047
+
1048
+
1049
+ def guarded_urlopen(url, data=None, timeout=_socket._GLOBAL_DEFAULT_TIMEOUT, *, context=None):
1050
+ """Drop-in for urllib.request.urlopen(): guards the URL and every redirect hop."""
1051
+ target = url.full_url if isinstance(url, _urlreq.Request) else str(url)
1052
+ guard_send(target, caller="guarded_urlopen")
1053
+ handlers = [_GuardedRedirectHandler()]
1054
+ if context is not None:
1055
+ handlers.append(_urlreq.HTTPSHandler(context=context))
1056
+ return _urlreq.build_opener(*handlers).open(url, data, timeout)
1057
+
1058
+
1059
+ # ---- curl / wget
1060
+ # curl short options that take an argument (the rest of the word, or the next word).
1061
+ _CURL_SHORT_ARG = set("AbcCdDeEFHKmoPQrtTuUwxXyYz")
1062
+ # curl long options that take an argument (anything else is treated as a flag).
1063
+ _CURL_LONG_ARG = {
1064
+ "--url", "--user-agent", "--referer", "--header", "--proxy-header", "--output", "--output-dir",
1065
+ "--data", "--data-ascii", "--data-binary", "--data-raw", "--data-urlencode", "--json", "--form",
1066
+ "--form-string", "--cookie", "--cookie-jar", "--max-time", "--connect-timeout", "--retry",
1067
+ "--retry-delay", "--retry-max-time", "--request", "--proxy", "--proxy-user", "--preproxy",
1068
+ "--noproxy", "--cacert", "--capath", "--cert", "--cert-type", "--key", "--key-type", "--pass",
1069
+ "--range", "--write-out", "--dump-header", "--max-filesize", "--limit-rate", "--resolve",
1070
+ "--connect-to", "--interface", "--user", "--config", "--time-cond", "--upload-file",
1071
+ "--max-redirs", "--speed-limit", "--speed-time", "--expect100-timeout", "--keepalive-time",
1072
+ "--ciphers", "--variable", "--trace", "--trace-ascii", "--stderr", "--proto", "--proto-redir",
1073
+ "--pinnedpubkey", "--dns-servers", "--local-port", "--oauth2-bearer", "--quote", "--etag-save",
1074
+ "--etag-compare", "--happy-eyeballs-timeout-ms", "--unix-socket", "--abstract-unix-socket",
1075
+ "--aws-sigv4", "--hsts", "--alt-svc", "--continue-at", "--create-file-mode", "--rate",
1076
+ "--parallel-max", "--mail-from", "--mail-rcpt", "--login-options", "--sasl-authzid",
1077
+ }
1078
+ _CURL_LOCATION = {"-L", "--location", "--location-trusted"}
1079
+ MAX_CURL_HOPS = 10
1080
+ _curl_runner: Optional[Callable] = None # test hook: fn(argv, **kwargs) -> CompletedProcess
1081
+
1082
+
1083
+ def _is_curl(args) -> bool:
1084
+ return bool(args) and os.path.basename(str(args[0])) in ("curl", "curl.exe")
1085
+
1086
+
1087
+ def _curl_parse(args):
1088
+ """Sanitise a curl argv: drop -L/--location(-trusted) (also inside combined short flags such
1089
+ as -sfL) and any --max-redirs N, then append --max-redirs 0.
1090
+ Returns (new_args, had_location, url_positions_in_new_args, dump_header_path_or_None)."""
1091
+ out = [args[0]]
1092
+ urls = []
1093
+ had_loc = False
1094
+ dump = None
1095
+ i = 1
1096
+ n = len(args)
1097
+ while i < n:
1098
+ a = args[i]
1099
+ if a in _CURL_LOCATION:
1100
+ had_loc = True
1101
+ i += 1
1102
+ continue
1103
+ if a == "--max-redirs":
1104
+ i += 2
1105
+ continue
1106
+ if a.startswith("--"):
1107
+ if a in _CURL_LONG_ARG and i + 1 < n:
1108
+ if a == "--url":
1109
+ urls.append(len(out) + 1)
1110
+ if a == "--dump-header":
1111
+ dump = args[i + 1]
1112
+ out += [a, args[i + 1]]
1113
+ i += 2
1114
+ continue
1115
+ out.append(a)
1116
+ i += 1
1117
+ continue
1118
+ if a.startswith("-") and len(a) > 1:
1119
+ kept = "-"
1120
+ takes_next = False
1121
+ j = 1
1122
+ while j < len(a):
1123
+ c = a[j]
1124
+ if c == "L":
1125
+ had_loc = True
1126
+ j += 1
1127
+ continue
1128
+ kept += c
1129
+ if c in _CURL_SHORT_ARG:
1130
+ rest = a[j + 1:]
1131
+ if rest:
1132
+ kept += rest
1133
+ if c == "D":
1134
+ dump = rest
1135
+ else:
1136
+ takes_next = True
1137
+ if c == "D" and i + 1 < n:
1138
+ dump = args[i + 1]
1139
+ break
1140
+ j += 1
1141
+ if kept != "-":
1142
+ out.append(kept)
1143
+ if takes_next and i + 1 < n:
1144
+ out.append(args[i + 1])
1145
+ i += 2
1146
+ else:
1147
+ i += 1
1148
+ continue
1149
+ if re.match(r"^https?://", a, re.I):
1150
+ urls.append(len(out))
1151
+ out.append(a)
1152
+ i += 1
1153
+ out += ["--max-redirs", "0"]
1154
+ return out, had_loc, urls, dump
1155
+
1156
+
1157
+ def curl_precheck(argv):
1158
+ """Guard every http(s) URL a curl/wget argv would fetch BEFORE running it (raises RobotsBlocked).
1159
+
1160
+ For curl it also returns a SANITISED argv: -L/--location is stripped and --max-redirs 0 is
1161
+ appended, so curl itself never follows a redirect. Run the returned argv, or use
1162
+ guarded_curl_run(), which follows redirects itself and guards every hop (Crawl-delay too).
1163
+ """
1164
+ as_str = isinstance(argv, str)
1165
+ import shlex
1166
+ args = shlex.split(argv) if as_str else [str(a) for a in argv]
1167
+ if _is_curl(args):
1168
+ new, _had_loc, urls, _dump = _curl_parse(args)
1169
+ for k in urls:
1170
+ guard(new[k], caller="curl_precheck(curl)")
1171
+ return shlex.join(new) if as_str else new
1172
+ for a in args[1:]: # wget etc.: guard URL arguments (no redirect rewriting)
1173
+ if re.match(r"^https?://", a, re.I):
1174
+ guard(a, caller=f"curl_precheck({os.path.basename(args[0])})")
1175
+ return argv
1176
+
1177
+
1178
+ def _last_header_block(text: str):
1179
+ """(status, headers-dict-lowercase) of the final HTTP response block in a curl -D dump."""
1180
+ blocks = [b for b in re.split(r"\r?\n\r?\n", text or "") if b.strip()]
1181
+ for b in reversed(blocks):
1182
+ lines = b.strip().splitlines()
1183
+ m = re.match(r"^HTTP/\S+\s+(\d{3})", lines[0].strip())
1184
+ if not m:
1185
+ continue
1186
+ hdrs = {}
1187
+ for ln in lines[1:]:
1188
+ if ":" in ln:
1189
+ k, v = ln.split(":", 1)
1190
+ hdrs[k.strip().lower()] = v.strip()
1191
+ return int(m.group(1)), hdrs
1192
+ return 0, {}
1193
+
1194
+
1195
+ def guarded_curl_run(argv, *args, **kwargs):
1196
+ """subprocess.run() for a curl/wget argv, robots-guarded.
1197
+
1198
+ curl: -L/--location is stripped and --max-redirs 0 added, so curl never follows a redirect
1199
+ on its own. If the caller asked for -L, the wrapper follows the redirect itself: it reads
1200
+ the Location header (curl -D dump), resolves relative URLs, guard()s every hop (robots rules
1201
+ AND Crawl-delay), and re-runs curl for that hop, up to MAX_CURL_HOPS (10) hops. A disallowed
1202
+ hop raises RobotsBlocked (logged to <cc>/logs/robots_blocked.jsonl) and is never requested.
1203
+ More than 10 hops gives returncode 47 (curl's "too many redirects").
1204
+ """
1205
+ import shlex
1206
+ import subprocess
1207
+ import tempfile
1208
+ from urllib.parse import urljoin
1209
+ runner = _curl_runner or subprocess.run
1210
+ shell_str = isinstance(argv, str)
1211
+ base = shlex.split(argv) if shell_str else [str(a) for a in argv]
1212
+ if not _is_curl(base):
1213
+ curl_precheck(argv)
1214
+ return runner(argv, *args, **kwargs)
1215
+ new, had_loc, urls, user_dump = _curl_parse(base)
1216
+ for k in urls:
1217
+ guard_send(new[k], caller="guarded_curl_run(curl)")
1218
+ if not had_loc or len(urls) != 1 or user_dump == "-":
1219
+ # no -L requested (curl would not have followed either), or several URLs / headers to
1220
+ # stdout (-D -): run once with redirects disabled; a 3xx is returned to the caller as is.
1221
+ cmd = shlex.join(new) if shell_str else new
1222
+ return runner(cmd, *args, **kwargs)
1223
+ pos = urls[0]
1224
+ tmp = None
1225
+ if user_dump is None:
1226
+ fd, tmp = tempfile.mkstemp(prefix="rg_curl_hdr_", suffix=".txt")
1227
+ os.close(fd)
1228
+ new = new[:-2] + ["-D", tmp] + new[-2:]
1229
+ dump = tmp
1230
+ else:
1231
+ dump = user_dump
1232
+ try:
1233
+ current = new[pos]
1234
+ for hop in range(MAX_CURL_HOPS + 1):
1235
+ cmd = list(new)
1236
+ cmd[pos] = current
1237
+ try:
1238
+ open(dump, "w").close()
1239
+ except Exception:
1240
+ pass
1241
+ res = runner(shlex.join(cmd) if shell_str else cmd, *args, **kwargs)
1242
+ try:
1243
+ hdr_text = open(dump, encoding="latin-1").read()
1244
+ except Exception:
1245
+ hdr_text = ""
1246
+ status, hdrs = _last_header_block(hdr_text)
1247
+ loc = hdrs.get("location")
1248
+ if status not in (301, 302, 303, 307, 308) or not loc:
1249
+ return res
1250
+ if hop == MAX_CURL_HOPS:
1251
+ break
1252
+ nxt = urljoin(current, loc)
1253
+ guard_send(nxt, caller=f"guarded_curl_run(redirect hop {hop + 1})") # robots + Crawl-delay
1254
+ current = nxt
1255
+ msg = f"guarded_curl_run: more than {MAX_CURL_HOPS} redirects ({current})\n"
1256
+ err = res.stderr
1257
+ if isinstance(err, bytes):
1258
+ err = err + msg.encode()
1259
+ elif isinstance(err, str):
1260
+ err = err + msg
1261
+ return subprocess.CompletedProcess(res.args, 47, res.stdout, err)
1262
+ finally:
1263
+ if tmp:
1264
+ try:
1265
+ os.unlink(tmp)
1266
+ except Exception:
1267
+ pass
1268
+
1269
+
1270
+ __all__ = [
1271
+ "RobotsBlocked", "RobotsDisallowed", "RobotsUnavailable", "Decision",
1272
+ "parse_robots", "match_rule", "evaluate", "check", "guard", "wait", "guard_send", "wait_send",
1273
+ "archived_original", "check_archived_copy", "load_persisted_snapshot", "CACHED_MAX_AGE_S",
1274
+ "set_country", "country", "report_blocked", "GuardedSession", "reset_cache",
1275
+ "guarded_request", "guarded_get", "guarded_head", "guarded_post", "guarded_urlopen",
1276
+ "curl_precheck", "guarded_curl_run", "log_robots_blocked", "was_blocked", "MAX_CURL_HOPS",
1277
+ ]
scrapers/mu_b1/split_mu.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Page-boundary filtering (bounds) and section splitting for MU legislation texts (pdftotext -layout or OCR text, pages split on \\f).
3
+ bounds.trim(pages): drops page-number-only lines and furniture lines repeated on >= 50 % of >= 3 pages (top 3 / bottom 3 lines);
4
+ returns (text, stats).
5
+ split(text): sections start at a line ' N. text' / 'N. text' (N = 1..999 with optional capital suffix, e.g. 5A) AFTER the body start
6
+ (first 'AN ORDINANCE' / 'ORDINANCE to' / 'In exercise of' / 'WHEREAS' / 'BE IT ENACTED' line; else after the 'ARRANGEMENT OF ...'
7
+ block's last entry; else the start). Numbering must be monotone within a part; a return to 1 after >= 2 opens a new part
8
+ (subsidiary legislation printed after its Ordinance). The marginal note (previous short non-section line) is the heading."""
9
+ import re
10
+ from collections import Counter
11
+ PNUM = re.compile(r"^\s*(?:-\s*)?\d{1,4}(?:\s*-)?\s*$|^\s*(?:page\s+)?\d{1,4}\s+of\s+\d{1,4}\s*$", re.I)
12
+ def _norm(l): return re.sub(r"\d+", "#", re.sub(r"\s+", " ", l.strip().lower()))
13
+ FOOT = re.compile(r"(?s)[ \t]*\d{0,2}[ \t]*Under section 10 of the Revised Edition of the Laws Ordinance,?\s*1999,?\s+this\s+text\s+is\s+authoritative.{0,200}?as\s+at\s+\d{1,2}\s+[A-Za-z]+\s+\d{4}\.?")
14
+ MUFURN = re.compile(r"^\s*(?:[A-Z]{1,3}\d{0,3}[A-Z]?\s*[–-]\s*\d{1,4}\s*(?:\[\s*Issue\s+\d+\s*\])?|\[\s*Issue\s+\d+\s*\]|Revised Laws of Mauritius)\s*$")
15
+ def trim(pages):
16
+ nf = 0
17
+ for i, p in enumerate(pages):
18
+ pages[i], k = FOOT.subn("", p); nf += k
19
+ pages = [p.splitlines() for p in pages]
20
+ cand = Counter()
21
+ for ls in pages:
22
+ nz = [l for l in ls if l.strip()]
23
+ for l in set(_norm(x) for x in nz[:3] + nz[-3:]): cand[l] += 1
24
+ rep = {k for k, v in cand.items() if len(pages) >= 3 and v >= 0.5 * len(pages) and len(k) > 1 and not re.match(r"^#\.", k)}
25
+ out, st = [], {"pages": len(pages), "revised_edition_footnotes": nf, "page_number_lines": 0, "furniture_lines": 0, "furniture_patterns": len(rep)}
26
+ for ls in pages:
27
+ nz_idx = [i for i, l in enumerate(ls) if l.strip()]
28
+ edge = set(nz_idx[:3] + nz_idx[-3:])
29
+ keep = []
30
+ for i, l in enumerate(ls):
31
+ if PNUM.match(l) and l.strip(): st["page_number_lines"] += 1; continue
32
+ if MUFURN.match(l): st["furniture_lines"] += 1; st["mu_furniture_lines"] = st.get("mu_furniture_lines", 0) + 1; continue
33
+ if i in edge and _norm(l) in rep: st["furniture_lines"] += 1; continue
34
+ keep.append(l)
35
+ out.append("\n".join(keep))
36
+ return "\n".join(out), st
37
+ BODY = re.compile(r"(?m)^\s*(?:AN\s+ORDINANCE\b|.*\bORDINANCE\s+to\b|In\s+exercise\s+of\b|WHEREAS\b|BE\s+IT\s+ENACTED\b|"
38
+ r"ENACTED\s+by\b|IT\s+IS\s+ORDERED\b|The\s+Governor.{0,60}\bmakes\b)")
39
+ SEC = re.compile(r"^\s{0,12}(\d{1,3}[A-Z]{0,2})\.(?:\s{1,}|\t)(?=\S)(.*)$")
40
+ def _num(s):
41
+ m = re.match(r"(\d+)([A-Z]*)", s); return int(m.group(1)), m.group(2)
42
+ def body_start(lines):
43
+ txt = "\n".join(lines); m = BODY.search(txt)
44
+ if m: return txt[:m.start()].count("\n")
45
+ last = None
46
+ for i, l in enumerate(lines[:400]):
47
+ if re.search(r"ARRANGEMENT\s+OF\s+(SECTIONS|REGULATIONS|RULES|PARAGRAPHS|CLAUSES|ARTICLES)", l): last = i
48
+ if last is not None:
49
+ # MU (Revised Laws): headings are inline ('1. Short title'), so the TOC and body both start with a '1.' line;
50
+ # the body starts at the second '1.' line after the ARRANGEMENT block (the first is the TOC's first entry).
51
+ ones = [i for i in range(last + 1, len(lines)) if re.match(r"^\s{0,12}1\.\s+\S", lines[i])]
52
+ if len(ones) >= 2: return ones[1]
53
+ # skip the TOC: entries are 'N. short heading' lines; body starts at the first line after them that is long prose
54
+ j = last + 1
55
+ while j < len(lines) and (not lines[j].strip() or SEC.match(lines[j]) and len(lines[j].strip()) < 90
56
+ or re.fullmatch(r"\s*(PART|SCHEDULE|Schedule)\b.*", lines[j]) or len(lines[j].strip()) < 60):
57
+ j += 1
58
+ return j
59
+ return 0
60
+ def split(text):
61
+ lines = text.splitlines(); b = body_start(lines)
62
+ secs, part, prev, cur = [], 1, None, None
63
+ ptitle = {1: ""}
64
+ for i in range(b, len(lines)):
65
+ l = lines[i]; m = SEC.match(l)
66
+ ok = False
67
+ if m:
68
+ n, suf = _num(m.group(1))
69
+ if prev is None: ok = n == 1 or n <= 3
70
+ else:
71
+ pn, ps = prev
72
+ if (n == pn + 1) or (n == pn and suf > ps) or (n == pn + 2):
73
+ ok = True
74
+ elif n == 1 and pn >= 2:
75
+ ok = True; part += 1
76
+ pt = ""
77
+ for k in range(i - 1, max(b, i - 40) - 1, -1):
78
+ x = lines[k].strip()
79
+ if len(x) >= 6 and x.upper() == x and re.search(r"[A-Z]{3}", x) and not SEC.match(lines[k]):
80
+ pt = x; break
81
+ ptitle[part] = pt
82
+ if ok:
83
+ n, suf = _num(m.group(1))
84
+ j = i - 1
85
+ while j >= b and not lines[j].strip(): j -= 1
86
+ head = lines[j].strip() if j >= b and len(lines[j].strip()) < 90 and not SEC.match(lines[j]) and not lines[j].strip().endswith((";", ",")) else ""
87
+ if cur and head and cur["lines"] and cur["lines"][-1].strip() == head: cur["lines"].pop()
88
+ cur = {"num": m.group(1), "part": part, "heading": head, "lines": [l.strip()]}
89
+ secs.append(cur); prev = (n, suf)
90
+ elif cur is not None:
91
+ cur["lines"].append(l.rstrip())
92
+ out = []
93
+ for s in secs:
94
+ t = re.sub(r"\n{3,}", "\n\n", "\n".join(s["lines"])).strip()
95
+ out.append({"num": s["num"], "part": s["part"], "part_title": ptitle.get(s["part"], ""), "heading": s["heading"], "text": t})
96
+ return out
97
+ def split_offsets(text):
98
+ """Same section logic as split(), but every section is returned as character offsets [start, end) into `text` itself,
99
+ so text[start:end] is a verbatim raw slice (no reflow, no normalisation). Fix batch 2026-10-24 (CoS verification)."""
100
+ lines = text.split("\n"); pos = [0]
101
+ for l in lines: pos.append(pos[-1] + len(l) + 1)
102
+ b = body_start(lines)
103
+ secs, part, prev, cur = [], 1, None, None
104
+ ptitle = {1: ""}
105
+ for i in range(b, len(lines)):
106
+ l = lines[i]; m = SEC.match(l); ok = False
107
+ if m:
108
+ n, suf = _num(m.group(1))
109
+ if prev is None: ok = n == 1 or n <= 3
110
+ else:
111
+ pn, ps = prev
112
+ if (n == pn + 1) or (n == pn and suf > ps) or (n == pn + 2): ok = True
113
+ elif n == 1 and pn >= 2:
114
+ ok = True; part += 1; pt = ""
115
+ for k in range(i - 1, max(b, i - 40) - 1, -1):
116
+ x = lines[k].strip()
117
+ if len(x) >= 6 and x.upper() == x and re.search(r"[A-Z]{3}", x) and not SEC.match(lines[k]): pt = x; break
118
+ ptitle[part] = pt
119
+ if ok:
120
+ j = i - 1
121
+ while j >= b and not lines[j].strip(): j -= 1
122
+ head = lines[j].strip() if j >= b and len(lines[j].strip()) < 90 and not SEC.match(lines[j]) and not lines[j].strip().endswith((";", ",", ".", ":", "—", "-")) else ""
123
+ if cur and head and j in cur["li"] and cur["li"][0] != j: cur["li"] = cur["li"][:cur["li"].index(j)]
124
+ cur = {"num": m.group(1), "part": part, "heading": head, "li": [i]}
125
+ secs.append(cur); prev = (_num(m.group(1)))
126
+ elif cur is not None:
127
+ cur["li"].append(i)
128
+ out = []
129
+ for s in secs:
130
+ i0, i1 = s["li"][0], s["li"][-1]
131
+ st = pos[i0] + (len(lines[i0]) - len(lines[i0].lstrip()))
132
+ en = pos[i1] + len(lines[i1])
133
+ while en > st and text[en - 1].isspace(): en -= 1
134
+ out.append({"num": s["num"], "part": s["part"], "part_title": ptitle.get(s["part"], ""), "heading": s["heading"],
135
+ "start": st, "end": en, "text": text[st:en]})
136
+ return out
scrapers/mu_b1/stage_mu.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage MU mu_b1 as a diff-limited append to endomorphosis/ipfs_mauritius_laws (CoS uploads; this script never uploads).
3
+ * Re-reads the Hub tip right before staging (api/datasets/<repo>); a 401/404 is ambiguous for an existing repo -> REFUSED.
4
+ * Downloads the tip's data/laws.parquet, data/articles.parquet, README.md, MANIFEST.md (+ MANIFEST.json / provenance/changes.json
5
+ if the tip has them) into tip_stage/<sha8>/; live rows are carried cell-identical; schema (incl. metadata), codec and row-group
6
+ layout are copied from the tip; new rows are appended after them.
7
+ * New rows: consolidated Acts from the AGO 'Acts A-Z' pages. Dedupe: PDF sha256; same Act (normalised title + Act number/Cap or
8
+ year) within the batch (keep the newest Last-Modified, then the longer text); against the tip (normalised title + year).
9
+ * Verbatim-slice gate, heading-only drop, repeal-placeholder tag, dominant-article demotion, page-furniture gate, Bills out,
10
+ free-webmail redaction (manifest without '@'), Act number/year check against the printed title, -dupN ids.
11
+ * Stage only if material (>= 1 new law) AND laws_rows_out >= tip laws_rows. Env MU_WORK."""
12
+ import hashlib, json, os, re, shutil, sys, urllib.request, urllib.error, subprocess, unicodedata
13
+ from collections import Counter
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ import pyarrow as pa, pyarrow.parquet as pq
17
+ HERE = Path(__file__).resolve().parent; sys.path.insert(0, str(HERE))
18
+ import split_mu as S, articles_mu as A, webmail_mu as WM
19
+ W = Path(os.environ.get("MU_WORK", ".")).resolve()
20
+ REPO = os.environ.get("MU_REPO", "endomorphosis/ipfs_mauritius_laws")
21
+ PACK = W / "hf_mu_b1" / REPO.split("/")[1]
22
+ TERMS_URL = "https://attorneygeneral.govmu.org/Pages/Laws%20of%20Mauritius/Constitution/termofuse.aspx"
23
+ LIC = ("Consolidated Acts of Mauritius as published by the Attorney General's Office (attorneygeneral.govmu.org). Described, not quoted: "
24
+ "the site's Term of Use lets people make personal copies and printouts of the legislation under the Copyright Act, but publishing, "
25
+ "disseminating or incorporating it for commercial use needs the prior approval of the Solicitor General; the site also says that "
26
+ "only the LexisNexis 2016 Revised Laws of Mauritius (with their supplements) are the authoritative text, so these copies are for "
27
+ "information only. Terms: " + TERMS_URL + " . Not legal advice.")
28
+ MON = {m: i for i, m in enumerate(["january","february","march","april","may","june","july","august","september","october","november","december"], 1)}
29
+ FURN_LEFT = re.compile(r"(?m)^\s*(?:[A-Z]{1,3}\d{0,3}[A-Z]?\s*[–-]\s*\d{1,4}\s*\[\s*Issue\s+\d+\s*\]|\[\s*Issue\s+\d+\s*\])\s*$")
30
+ def utc(): return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
31
+ def api(repo):
32
+ try:
33
+ with urllib.request.urlopen(f"https://huggingface.co/api/datasets/{repo}", timeout=60) as r: return json.load(r)
34
+ except urllib.error.HTTPError as e:
35
+ return {"_http": e.code}
36
+ def dl(repo, sha, f, dst, required=True):
37
+ dst.parent.mkdir(parents=True, exist_ok=True)
38
+ if not dst.exists():
39
+ try: urllib.request.urlretrieve(f"https://huggingface.co/datasets/{repo}/resolve/{sha}/{f}", dst)
40
+ except urllib.error.HTTPError as e:
41
+ if required: raise
42
+ return None
43
+ return dst
44
+ def layout(p):
45
+ md = pq.ParquetFile(p).metadata
46
+ return {"rows": md.num_rows, "row_groups": md.num_row_groups, "codec": md.row_group(0).column(0).compression if md.num_row_groups else None,
47
+ "rg_rows": [md.row_group(i).num_rows for i in range(md.num_row_groups)]}
48
+ def slug(s, n=80):
49
+ s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
50
+ return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", s.lower())).strip("-")[:n].strip("-")
51
+ def ntitle(t):
52
+ t = unicodedata.normalize("NFKD", t or "").encode("ascii", "ignore").decode().lower()
53
+ t = re.sub(r"\b(?:no\.?|act|cap\.?|of)\b|\b\d+[a-z]?\b", " ", t); t = re.sub(r"\([^)]*\b(?:act|of)\b[^)]*\)", " ", t)
54
+ return re.sub(r"[^a-z]+", "", t)
55
+ NUMRX = re.compile(r"(?i)\b(Act|Ordinance|Decree|Order|Government Notice|GN)\s+(?:No\.?\s*)?(\d{1,4})\s+of\s+(1[6-9]\d\d|20[0-4]\d)\b")
56
+ CAPRX = re.compile(r"(?i)\bCap\.?\s*(\d{1,4}[A-Z]?)\b")
57
+ def printed(text):
58
+ """Printed title block: first caps title line(s) and the 'Act N of YYYY – <date>' / 'Cap N' line under it."""
59
+ h = text.splitlines()[:30]; out = {}
60
+ for i, l in enumerate(h):
61
+ m = NUMRX.search(l); c = CAPRX.search(l)
62
+ if (m or c) and len(l.strip()) < 120:
63
+ if m: out.update(kind=m.group(1), number=m.group(2), year=int(m.group(3)), line=l.strip())
64
+ if c: out.update(cap=c.group(1), line=l.strip())
65
+ d = re.search(r"(\d{1,2})\s+(" + "|".join(MON) + r")\s+((?:1[6-9]|20)\d\d)", l, re.I)
66
+ if d: out["date"] = f"{int(d.group(3)):04d}-{MON[d.group(2).lower()]:02d}-{int(d.group(1)):02d}"
67
+ tl = [x.strip() for x in h[max(0, i - 3):i] if x.strip() and x.strip().upper() == x.strip() and re.search(r"[A-Z]{3}", x)]
68
+ if tl: out["title"] = " ".join(tl)
69
+ break
70
+ return out
71
+ def from_file(name):
72
+ o = {}; m = re.search(r"(?i)\bNo\.?\s*(\d{1,4})\s+of\s+(1[6-9]\d\d|20[0-4]\d)", name) or re.search(r"(?i)\bAct\s+(\d{1,4})\s+of\s+(1[6-9]\d\d|20[0-4]\d)", name)
73
+ if m: o.update(number=m.group(1), year=int(m.group(2)))
74
+ c = CAPRX.search(name)
75
+ if c: o["cap"] = c.group(1)
76
+ return o
77
+ FR = re.compile(r"(?i)\b(?:le|la|les|des|du|est|sont|dans|pour|par|qui|une|aux|sera|article)\b")
78
+ EN = re.compile(r"(?i)\b(?:the|of|and|shall|to|in|be|by|any|which|section)\b")
79
+ def lang(text):
80
+ s = text[:20000]; f, e = len(FR.findall(s)), len(EN.findall(s)); return "fr" if f > 1.5 * e else "en"
81
+ def is_bill(title, text):
82
+ first = "\n".join(text.splitlines()[:25])
83
+ return bool(re.search(r"(?i)\bbill\b", title) or re.search(r"(?m)^\s*(?:A\s+)?BILL\b|^\s*A\s+Bill\s+(?:for|to)\b", first))
84
+ def clean_title(t):
85
+ t = re.sub(r"\s+", " ", (t or "").replace("\u200b", "")).strip(" -–,")
86
+ return t
87
+ def main():
88
+ cat = {x["key"]: x for x in json.load(open(W / "catalog.json"))}
89
+ fetched = [json.loads(l) for l in open(W / "fetched.jsonl")]
90
+ texts = {}
91
+ for l in open(W / "texts.jsonl"): d = json.loads(l); texts[d["sha256"]] = d
92
+ lm = {}
93
+ for l in open(W / "requests.jsonl"):
94
+ d = json.loads(l)
95
+ if d.get("last_modified"): lm[d["url"]] = d["last_modified"]
96
+ tip = api(REPO)
97
+ if "_http" in tip or not tip.get("sha"):
98
+ print(json.dumps({"stage": "REFUSED", "why": f"hub api {tip.get('_http')} for existing repo: ambiguous"})); return 2
99
+ parent = tip["sha"]; sibs = {s["rfilename"] for s in tip.get("siblings", [])}
100
+ td = W / "tip_stage" / parent[:8]
101
+ base_l = dl(REPO, parent, "data/laws.parquet", td / "data/laws.parquet"); base_a = dl(REPO, parent, "data/articles.parquet", td / "data/articles.parquet")
102
+ for f in ("README.md", "MANIFEST.md", "MANIFEST.json", "provenance/changes.json"):
103
+ if f in sibs: dl(REPO, parent, f, td / f)
104
+ TL, TA = pq.read_table(base_l), pq.read_table(base_a)
105
+ tip_rows = TL.to_pylist()
106
+ ids = set(TL.column("id").to_pylist()); aids_all = set(TA.column("id").to_pylist())
107
+ NONACT = re.compile(r"(?i)explanatory|guidance|report|\bbill\b|speech|press|notice|circular")
108
+ tip_keys = {}
109
+ for r in tip_rows:
110
+ if NONACT.search((r["id"] or "") + " " + (r["source_url"] or "") + " " + (r["title"] or "")): continue
111
+ k = ntitle(r["title"]);
112
+ if not k: continue
113
+ yrs = set(int(y) for y in re.findall(r"\b(1[6-9]\d\d|20[0-4]\d)\b", (r["title"] or "") + " " + (r["official_identifier"] or "")))
114
+ tip_keys.setdefault(k, []).append((r["id"], yrs))
115
+ cands, drops, seen_sha, num_issues = [], [], set(), []
116
+ for r in fetched:
117
+ x = cat.get(r["key"], r)
118
+ if not r.get("sha256"): drops.append({"key": r["key"], "url": x["url"], "reason": "fetch_" + (r.get("error") or "no_pdf").split()[0]}); continue
119
+ if r["sha256"] in seen_sha: drops.append({"key": r["key"], "url": x["url"], "reason": "duplicate_pdf_sha256"}); continue
120
+ seen_sha.add(r["sha256"]); tm = texts.get(r["sha256"], {}); src = "pdf_text_layer"; ocr = None
121
+ if tm.get("needs_ocr"):
122
+ oj = W / "cache/ocr" / f"{r['sha256']}.json"
123
+ if not oj.exists(): drops.append({"key": r["key"], "url": x["url"], "reason": "needs_ocr_no_ocr_output"}); continue
124
+ ocr = json.loads(oj.read_text())
125
+ if ocr.get("status") == "FAILED" or not ocr.get("words"): drops.append({"key": r["key"], "url": x["url"], "reason": "ocr_failed"}); continue
126
+ raw = (W / "cache/ocr" / f"{r['sha256']}.txt").read_text(); src = "ocr"
127
+ else:
128
+ raw = (W / "cache/text" / f"{r['sha256']}.txt").read_text()
129
+ pages = raw.split("\f")
130
+ if pages and not pages[-1].strip(): pages = pages[:-1]
131
+ text, bst = S.trim(pages); text = text.replace("\r", "")
132
+ text, wrec = WM.redact(text)
133
+ title = clean_title(x.get("title")) or re.sub(r"\.pdf$", "", x.get("file", ""), flags=re.I)
134
+ if is_bill(title, text): drops.append({"key": r["key"], "url": x["url"], "title": title, "reason": "bill"}); continue
135
+ if len(re.sub(r"\s", "", text)) < 200: drops.append({"key": r["key"], "url": x["url"], "title": title, "reason": "empty_text"}); continue
136
+ pr = printed(text); ff = from_file(x.get("file", "") + " " + x.get("title", ""))
137
+ mism = []
138
+ if ff.get("number") and pr.get("number") and (ff["number"], ff["year"]) != (pr["number"], pr["year"]): mism.append("number_year")
139
+ if ff.get("cap") and pr.get("cap") and ff["cap"].upper() != pr["cap"].upper(): mism.append("cap")
140
+ if pr.get("title") and ntitle(pr["title"]) and ntitle(title) and ntitle(pr["title"]) != ntitle(title): mism.append("title")
141
+ if mism: num_issues.append({"key": r["key"], "url": x["url"], "title": title, "printed_title": pr.get("title"), "mismatch": mism,
142
+ "listing_number": ff, "printed_number": {k: pr.get(k) for k in ("kind", "number", "year", "cap")}})
143
+ offid = (f"{pr['kind'].title() if pr['kind'] not in ('GN',) else 'GN'} {pr['number']} of {pr['year']}" if pr.get("number") else None)
144
+ if pr.get("cap"): offid = (offid + f" (Cap {pr['cap']})") if offid else f"Cap {pr['cap']}"
145
+ year = pr.get("year") or ff.get("year")
146
+ key = (ntitle(title), pr.get("number") or ff.get("number") or pr.get("cap") or ff.get("cap") or "", year or "")
147
+ cands.append(dict(r=r, x=x, text=text, bst=bst, wrec=wrec, title=title, pr=pr, ff=ff, offid=offid, year=year, key=key, src=src, ocr=ocr, tm=tm,
148
+ lm=lm.get(r.get("final_url") or x["url"]) or ""))
149
+ # in-batch duplicate Acts (same Act listed twice under different file names)
150
+ def lmkey(c):
151
+ try: return datetime.strptime(c["lm"], "%a, %d %b %Y %H:%M:%S %Z").timestamp()
152
+ except Exception: return 0
153
+ groups = {}
154
+ for c in cands: groups.setdefault((c["key"][0], c["key"][1], c["key"][2]) if c["key"][1] or c["key"][2] else (c["key"][0], c["r"]["sha256"]), []).append(c)
155
+ keep = []
156
+ for k, g in groups.items():
157
+ g.sort(key=lambda c: (lmkey(c), len(c["text"])), reverse=True); keep.append(g[0])
158
+ for c in g[1:]: drops.append({"key": c["r"]["key"], "url": c["x"]["url"], "title": c["title"], "reason": "duplicate_act_in_batch", "kept_url": g[0]["x"]["url"]})
159
+ keep.sort(key=lambda c: fetched.index(c["r"]))
160
+ laws, arts, quality, heading_drops, whole_list, red_manifest = [], [], [], [], [], []
161
+ def uid(base):
162
+ i, x = 1, base
163
+ while x in ids: i += 1; x = f"{base}-dup{i}"
164
+ ids.add(x); return x
165
+ for c in keep:
166
+ k = c["key"][0]; hit = None
167
+ for tid, yrs in tip_keys.get(k, []):
168
+ if not yrs or not c["year"] or c["year"] in yrs: hit = tid; break
169
+ if hit: drops.append({"key": c["r"]["key"], "url": c["x"]["url"], "title": c["title"], "reason": "duplicate_of_tip", "tip_id": hit}); continue
170
+ text = c["text"]
171
+ if FURN_LEFT.search(text): print(json.dumps({"stage": "REFUSED", "why": "page_furniture_left", "url": c["x"]["url"]})); return 2
172
+ base = "mu-ago-" + (f"act-{c['pr']['number']}-{c['pr']['year']}-" if c["pr"].get("number") else (f"cap-{c['pr']['cap'].lower()}-" if c["pr"].get("cap") else "")) + slug(c["title"], 70)
173
+ lid = uid(base)
174
+ al, dl_, whole_reason = A.build(lid, text, c["offid"], c["r"].get("final_url") or c["x"]["url"])
175
+ # article ids must be unique across the whole articles file too
176
+ for a in al:
177
+ if a["id"] in aids_all:
178
+ b0, i = a["id"], 2
179
+ while f"{b0}-dup{i}" in aids_all: i += 1
180
+ a["id"] = f"{b0}-dup{i}"
181
+ aids_all.add(a["id"])
182
+ viol = A.gate(text, al)
183
+ if viol: print(json.dumps({"stage": "REFUSED", "why": "substring_gate", "law": lid, "violations": viol[:5]})); return 2
184
+ if A.dominant(al): print(json.dumps({"stage": "REFUSED", "why": "dominant_article", "law": lid})); return 2
185
+ heading_drops.extend(dl_)
186
+ if whole_reason: whole_list.append({"law_id": lid, "title": c["title"], "reason": whole_reason})
187
+ if c["wrec"]: red_manifest.append({"law_id": lid, "count": len(c["wrec"]), "categories": dict(Counter(w["category"] for w in c["wrec"])),
188
+ "spans_in_stored_text": [[w["new_start"], w["new_end"]] for w in c["wrec"]]})
189
+ lg = lang(text)
190
+ ocr = c["ocr"]; tmv = c["tm"]
191
+ meta = {"batch": "mu_b1", "kind": "consolidated_act", "listing_page": c["x"].get("page"), "catalog_url": c["x"]["url"], "file_name": c["x"].get("file"),
192
+ "final_url": c["r"].get("final_url"), "sha256": c["r"]["sha256"], "bytes": c["r"].get("bytes"), "last_modified": c["lm"] or None,
193
+ "pages": c["bst"]["pages"], "text_source": c["src"], "ocr": ocr, "garble": tmv.get("garble"), "bounds": c["bst"],
194
+ "printed_identifier_line": c["pr"].get("line"), "printed_title": c["pr"].get("title"), "listing_number": c["ff"],
195
+ "number_check": "mismatch" if any(n["key"] == c["r"]["key"] for n in num_issues) else ("ok" if (c["pr"].get("number") or c["pr"].get("cap")) else "no_printed_number"),
196
+ "year": c["year"], "edition": "Revised Laws of Mauritius (AGO consolidated text)", "authoritative_text": "LexisNexis 2016 Revised Laws of Mauritius (per AGO Term of Use)",
197
+ "webmail_redactions": len(c["wrec"]), "sections": len(al), "heading_only_dropped": len(dl_), "whole_text_fallback": bool(whole_reason),
198
+ "whole_text_reason": whole_reason, "language_detected": lg,
199
+ "commencement_date_printed": c["pr"].get("date")} # date on the printed "Act N of YYYY – <date>" line is the commencement date, not the date of issue
200
+ laws.append({"id": lid, "title": c["title"], "text": text, "source_url": c["r"].get("final_url") or c["x"]["url"],
201
+ "source_type": "mauritius_ago_revised_laws_acts_az", "jurisdiction": "MU", "country": "Mauritius", "language": lg, "eli": None,
202
+ "date": None, "date_issued": None, "retrieved_at": c["r"].get("retrieved_at"), "license": LIC, "law_status": "current",
203
+ "identifier": lid, "official_identifier": c["offid"], "article_count": len(al), "json_path": None,
204
+ "metadata_json": json.dumps(meta, ensure_ascii=False)})
205
+ arts.extend(al)
206
+ st = "ok"
207
+ if c["src"] == "ocr": st = "DEGRADED" if (ocr.get("mean_conf") or 0) < 80 else "ok"
208
+ elif (tmv.get("garble") or 0) > 0.08: st = "DEGRADED"
209
+ quality.append({"id": lid, "title": c["title"], "text_source": c["src"], "garble": tmv.get("garble"), "mean_conf": (ocr or {}).get("mean_conf"),
210
+ "sections": len(al), "whole": bool(whole_reason), "status": st})
211
+ tip_laws = TL.num_rows
212
+ if not laws or tip_laws + len(laws) < tip_laws:
213
+ print(json.dumps({"stage": "NOT_MATERIAL", "new_laws": len(laws)})); return 2
214
+ OL = pa.concat_tables([TL, pa.Table.from_pylist(laws, schema=TL.schema)])
215
+ OA = pa.concat_tables([TA, pa.Table.from_pylist(arts, schema=TA.schema)])
216
+ if PACK.exists(): shutil.rmtree(PACK)
217
+ (PACK / "data").mkdir(parents=True); (PACK / "manifests").mkdir()
218
+ LL, LA = layout(base_l), layout(base_a)
219
+ if LL["row_groups"] != 1 or LA["row_groups"] != 1: print(json.dumps({"stage": "REFUSED", "why": "tip has >1 row group; layout copy not implemented", "l": LL, "a": LA})); return 2
220
+ pq.write_table(OL, PACK / "data/laws.parquet", compression=LL["codec"].lower(), row_group_size=OL.num_rows)
221
+ pq.write_table(OA, PACK / "data/articles.parquet", compression=LA["codec"].lower(), row_group_size=OA.num_rows)
222
+ with open(PACK / "manifests/mu_b1_drops.jsonl", "w") as f:
223
+ for d in drops: f.write(json.dumps(d, ensure_ascii=False) + "\n")
224
+ json.dump(heading_drops, open(W / "heading_drops.json", "w"), ensure_ascii=False)
225
+ json.dump({"whole": whole_list, "number_issues": num_issues, "webmail": red_manifest}, open(W / "stage_extra.json", "w"), ensure_ascii=False, indent=1)
226
+ summ = {"batch": "mu_b1", "repo": REPO, "mode": "append", "parent": parent, "tip_files": sorted(sibs), "tip_laws": tip_laws, "tip_articles": TA.num_rows,
227
+ "new_laws": len(laws), "new_articles": len(arts), "laws_rows": OL.num_rows, "articles_rows": OA.num_rows,
228
+ "languages": dict(Counter(l["language"] for l in laws)), "drops": dict(Counter(d["reason"] for d in drops)),
229
+ "quality": quality, "whole_text_fallback": len(whole_list), "degraded": [q for q in quality if q["status"] == "DEGRADED"],
230
+ "ocr_used": [q for q in quality if q["text_source"] == "ocr"], "codec": LL["codec"], "row_groups": 1,
231
+ "heading_only_dropped": len(heading_drops), "repealed_placeholders": sum('"repealed_placeholder"' in a["metadata_json"] for a in arts),
232
+ "schedules": sum('"schedule": true' in a["metadata_json"] for a in arts), "number_mismatches": len(num_issues),
233
+ "webmail_redactions": sum(r["count"] for r in red_manifest), "license_paraphrase": LIC, "terms_url": TERMS_URL, "staged_at": utc()}
234
+ json.dump(summ, open(W / "stage_summary.json", "w"), indent=1, ensure_ascii=False)
235
+ subprocess.run([sys.executable, str(HERE / "readme_mu.py")], check=True)
236
+ subprocess.run([sys.executable, str(HERE / "finalize_mu.py")], check=True)
237
+ print(json.dumps({k: summ[k] for k in ("parent", "tip_laws", "tip_articles", "new_laws", "new_articles", "laws_rows", "articles_rows", "drops", "whole_text_fallback", "heading_only_dropped", "number_mismatches")}, ensure_ascii=False))
238
+ return 0
239
+ if __name__ == "__main__":
240
+ sys.exit(main())
scrapers/mu_b1/validate_split_mu.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pre-stage validation on the first fetched PDFs (CoS rule): each must give a usable text (layer or flagged for OCR) and, for
3
+ text-layer documents, >= 1 numbered section with verbatim slices (articles_mu.build + gate), the first section numbered 1, and no section text empty.
4
+ PASS when >= 80 % of text-layer docs split into >= 2 sections. Writes split_validation.json. Env MU_WORK."""
5
+ import json, os, sys, subprocess
6
+ from pathlib import Path
7
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
8
+ import split_mu as S
9
+ import articles_mu as A
10
+ W = Path(os.environ.get("MU_WORK", "."))
11
+ rows = []
12
+ for l in open(W / "fetched.jsonl"):
13
+ r = json.loads(l)
14
+ if not r.get("sha256"): rows.append({"key": r["key"], "title": r.get("title"), "ok": None, "why": r.get("error")}); continue
15
+ t = subprocess.run(["pdftotext", "-layout", "-enc", "UTF-8", str(W / "cache" / f"{r['sha256']}.pdf"), "-"], capture_output=True).stdout.decode("utf-8", "replace")
16
+ pages = [p for p in t.split("\f")]
17
+ if pages and not pages[-1].strip(): pages = pages[:-1]
18
+ if sum(len(p.strip()) for p in pages) < 200 * max(1, len(pages)) * 0.5:
19
+ rows.append({"key": r["key"], "title": r.get("title"), "ok": None, "why": "needs_ocr"}); continue
20
+ text = S.trim(pages)[0]
21
+ arts, dropped, whole = A.build("v", text, "", "")
22
+ secs = [a for a in arts if not json.loads(a["metadata_json"])["schedule"]]
23
+ nums = [a["article_number"] for a in secs]
24
+ ok = (whole is None and len(secs) >= 2 and nums[0] == "1" and all(a["text"].strip() for a in arts) and not A.gate(text, arts))
25
+ rows.append({"key": r["key"], "title": r.get("title"), "ok": ok, "sections": len(secs), "dropped_heading_only": len(dropped),
26
+ "whole_reason": whole, "first_nums": nums[:3], "first": [json.loads(a["metadata_json"])["heading"][:60] for a in secs[:3]]})
27
+ tl = [x for x in rows if x["ok"] is not None]
28
+ p = bool(tl) and sum(1 for x in tl if x["ok"]) / len(tl) >= 0.8
29
+ json.dump({"pass": p, "docs": rows}, open(W / "split_validation.json", "w"), indent=1, ensure_ascii=False)
30
+ print(json.dumps({"pass": p, "text_docs": len(tl), "ok": sum(1 for x in tl if x["ok"]), "rows": [(x["title"], x.get("sections"), x["ok"]) for x in rows]}, ensure_ascii=False))
31
+ sys.exit(0 if p else 7)
scrapers/mu_b1/verify_mu.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verify the staged MU mu_b1 pack. Exit 0 only if every check passes. Env MU_WORK.
3
+ Checks: Hub tip unchanged since staging; schema (incl. metadata), codec and row-group layout equal to the tip; tip rows carried
4
+ cell-identical; new ids unique (laws and articles, whole file); articles reference new laws; article_count matches; no Bills;
5
+ bounds recorded; no padded dates; verbatim-slice substring gate (0 violations); no heading-only rows; no dominant article;
6
+ no page furniture; every short Omitted/Repealed/Revoked/Deleted/dash body tagged repealed_placeholder; pii_scan (0 FAIL);
7
+ rg + parquet secret scans; webmail check on new rows; redaction manifest without '@'; README YAML safe_load + text-quality
8
+ section naming every DEGRADED item + licence paraphrase with the terms URL; scrapers bundle complete and self-contained
9
+ (no absolute fleet paths, pinned requirements, how-to-run README, bundled robots_guard + br_waiting.sh, code record hashes);
10
+ no published scrapers/ file of the tip overwritten; known_gaps complete; SHA256SUMS valid and complete.
11
+ Secret patterns are assembled from fragments so this file never matches itself."""
12
+ import hashlib, json, os, re, subprocess, sys, urllib.request
13
+ from collections import Counter
14
+ from pathlib import Path
15
+ import pyarrow.parquet as pq, yaml
16
+ HERE = Path(__file__).resolve().parent; sys.path.insert(0, str(HERE))
17
+ from pii_scan_mu import scan
18
+ import articles_mu as AM, classify_mu as CM, webmail_mu as WMU, split_mu as SM
19
+ W = Path(os.environ.get("MU_WORK", ".")).resolve()
20
+ S = json.load(open(W / "stage_summary.json")); P = W / "hf_mu_b1" / S["repo"].split("/")[1]; TD = W / "tip_stage" / S["parent"][:8]
21
+ res, ok = {}, True
22
+ def chk(name, cond, detail=None):
23
+ global ok
24
+ res[name] = {"ok": bool(cond), **({"detail": detail} if detail is not None else {})}; ok &= bool(cond)
25
+ try:
26
+ live = json.load(urllib.request.urlopen(f"https://huggingface.co/api/datasets/{S['repo']}", timeout=60))["sha"]
27
+ except Exception as e:
28
+ live = f"ERR {e}"[:120]
29
+ chk("hub_tip_unchanged", live == S["parent"], {"parent": S["parent"], "live": live})
30
+ def lay(p):
31
+ md = pq.ParquetFile(p).metadata; return (md.num_row_groups, md.row_group(0).column(0).compression)
32
+ for name in ("laws", "articles"):
33
+ o, t = pq.read_table(P / f"data/{name}.parquet"), pq.read_table(TD / f"data/{name}.parquet")
34
+ chk(f"{name}_tip_prefix_identical", o.slice(0, t.num_rows).equals(t), {"tip_rows": t.num_rows, "out_rows": o.num_rows})
35
+ chk(f"{name}_schema_equal", o.schema.equals(t.schema, check_metadata=True))
36
+ chk(f"{name}_codec_rowgroups_equal", lay(P / f"data/{name}.parquet") == lay(TD / f"data/{name}.parquet"))
37
+ L, A = pq.read_table(P / "data/laws.parquet").to_pylist(), pq.read_table(P / "data/articles.parquet").to_pylist()
38
+ nt = S["tip_laws"]; new = L[nt:]; tip_ids = {r["id"] for r in L[:nt]}; nart = A[S["tip_articles"]:]
39
+ chk("material_and_rows_ge_tip", len(new) >= 1 and len(L) >= nt, {"new_laws": len(new), "laws_rows": len(L)})
40
+ chk("new_law_ids_unique_not_in_tip", len({r["id"] for r in new}) == len(new) and not ({r["id"] for r in new} & tip_ids))
41
+ _dc = Counter(a["id"] for a in A); _dups = [k for k, v in _dc.items() if v > 1]
42
+ _tipdup = [k for k in _dups if not k.startswith("mu-ago-")]
43
+ chk("article_ids_unique_whole_file", not [k for k in _dups if k.startswith("mu-ago-")], {"new_batch_dups": [k for k in _dups if k.startswith("mu-ago-")][:5], "preexisting_tip_dup_ids_count": len(_tipdup), "note": "pre-existing tip duplicates are left unchanged (append-only)"})
44
+ nid = {r["id"]: r for r in new}
45
+ chk("new_articles_reference_new_laws", all(a["law_id"] in nid for a in nart))
46
+ cnt = Counter(a["law_id"] for a in nart)
47
+ chk("article_count_matches", all(cnt.get(i, 0) == r["article_count"] for i, r in nid.items()))
48
+ chk("no_bill_titles", not [r["id"] for r in new if re.search(r"(?i)\bbill\b", r["title"])])
49
+ chk("bounds_recorded", all('"bounds"' in r["metadata_json"] for r in new))
50
+ chk("no_padded_dates", not [r["id"] for r in new if (r["date"] or "").endswith("-01-01") or (r["date_issued"] or "").endswith("-01-01")])
51
+ chk("no_empty_articles", all(r["article_count"] >= 1 for r in new) and all((a["text"] or "").strip() for a in nart))
52
+ byl = {}
53
+ for a in nart: byl.setdefault(a["law_id"], []).append(a)
54
+ sv = [v for lid, arts in byl.items() for v in AM.gate(nid[lid]["text"], arts)]
55
+ chk("substring_gate_verbatim_slices", not sv, {"violations": len(sv), "first": sv[:5]})
56
+ bs = Counter(json.loads(a["metadata_json"]).get("body_status") for a in nart)
57
+ chk("no_heading_only_rows", bs.get("heading_only", 0) == 0, dict(bs))
58
+ dom = [lid for lid, arts in byl.items() if AM.dominant(arts)]
59
+ chk("no_dominant_article", not dom, {"laws": dom[:5]})
60
+ furn = [r["id"] for r in new if re.search(r"(?m)^\s*\[\s*Issue\s+\d+\s*\]\s*$", r["text"]) or any(SM.MUFURN.match(l) for l in r["text"].splitlines())]
61
+ chk("no_page_furniture", not furn, {"laws": furn[:5]})
62
+ untag = []
63
+ for a in nart:
64
+ md = json.loads(a["metadata_json"])
65
+ if md.get("body_status") == "body" and not md.get("whole_text_fallback") and not md.get("schedule") and len(a["text"]) < 200:
66
+ first = CM.NUM.sub("", a["text"].split("\n")[0]).strip(); rest = [l for l in a["text"].split("\n")[1:] if l.strip()]
67
+ if CM.PL.match(first) and not rest: untag.append(a["id"])
68
+ chk("placeholders_tagged", not untag, {"untagged": untag[:5]})
69
+ pii = scan([str(P / "data/laws.parquet"), str(P / "data/articles.parquet")])
70
+ pn = [h for h in pii if h["level"] == "fail"]
71
+ chk("pii_manifest_matches_scan", json.load(open(P / "manifests/mu_b1_pii_scan.json")) == {"new_fail": len(pn), "new_hits": pii})
72
+ chk("pii_scan_new_rows_no_fail", not pn, {"new_fail": len(pn), "kinds": dict(Counter(h["kind"] for h in pn)), "new_warn": sum(1 for h in pii if h["level"] == "warn")})
73
+ SEC = [r"AKIA" + r"[0-9A-Z]{16}", r"xox" + r"[baprs]-[0-9A-Za-z-]{10,}", r"s" + r"k-[A-Za-z0-9]{20,}", r"gh" + r"[pousr]_[A-Za-z0-9]{30,}",
74
+ r"h" + r"f_[A-Za-z0-9]{30,}", r"-----BEGIN [A-Z ]*PRIV" + r"ATE KEY-----", r"AI" + r"za[0-9A-Za-z_\-]{35}", r"gl" + r"pat-[0-9A-Za-z_\-]{20}"]
75
+ rx = re.compile("|".join(SEC)); rg_hits = []
76
+ for pat in SEC:
77
+ r = subprocess.run(["rg", "-c", "--no-messages", "-e", pat, str(P)], capture_output=True, text=True)
78
+ rg_hits += [l.rsplit(":", 1)[0] for l in r.stdout.splitlines() if l.strip()]
79
+ pq_hits = {"new": 0, "inherited": 0}
80
+ for rows, k0 in ((L, nt), (A, S["tip_articles"])):
81
+ for i, r in enumerate(rows):
82
+ for v in r.values():
83
+ if isinstance(v, str) and rx.search(v): pq_hits["new" if i >= k0 else "inherited"] += 1
84
+ chk("secret_scan_rg_files", not [h for h in rg_hits if not h.endswith(".parquet")], {"files": sorted(set(rg_hits))})
85
+ chk("secret_scan_parquet_new_rows", pq_hits["new"] == 0, pq_hits)
86
+ WM2 = re.compile(r"[A-Za-z0-9._%+\-]+\s*@\s*(?:gmail|googlemail|yahoo|ymail|hotmail|outlook|live|msn|aol|icloud|gmx|protonmail|zoho|yandex)\b", re.I)
87
+ wm = [r.get("id") for r in new + nart for v in r.values() if isinstance(v, str) and (WM2.search(v) or WMU.WEBMAIL_CHECK.search(v) or WMU.redact(v)[1])]
88
+ chk("no_webmail_new_rows", not wm, {"rows": len(wm)})
89
+ chk("redaction_manifest_no_at", "@" not in (P / "manifests/webmail_redactions.json").read_text())
90
+ rd = (P / "README.md").read_text()
91
+ try:
92
+ fm = yaml.safe_load(rd.split("---", 2)[1]); chk("readme_yaml_safe_load", isinstance(fm, dict) and "configs" in fm)
93
+ except Exception as e:
94
+ chk("readme_yaml_safe_load", False, str(e)[:200])
95
+ chk("readme_text_quality_section", "### OCR and text quality (batch mu_b1)" in rd and all(d["title"] in rd for d in S["degraded"]))
96
+ chk("readme_licence_paraphrase_and_url", "termofuse.aspx" in rd and "Solicitor General" in rd and "LexisNexis" in rd)
97
+ chk("readme_totals", f"{S['laws_rows']:,}" in rd and f"{S['articles_rows']:,}" in rd)
98
+ sr = P / "scrapers/mu_b1/README.md"
99
+ chk("scrapers_readme_how_to_run", sr.exists() and len(sr.read_text().splitlines()) >= 40 and "How to run" in sr.read_text() and "ipfs_mauritius_laws" in sr.read_text())
100
+ tip_files = set(S["tip_files"]); pack_files = {str(f.relative_to(P)) for f in P.rglob("*") if f.is_file() and "__pycache__" not in f.parts}
101
+ over = sorted(f for f in pack_files & tip_files if f.startswith("scrapers/"))
102
+ chk("no_published_scrapers_overwritten", not over, {"overwritten": over})
103
+ allowed_overwrite = {"data/laws.parquet", "data/articles.parquet", "README.md", "MANIFEST.md", "MANIFEST.json", "provenance/changes.json"}
104
+ chk("only_expected_tip_files_changed", (pack_files & tip_files) <= allowed_overwrite, sorted(pack_files & tip_files))
105
+ wsp = subprocess.run(["rg", "-l", "--no-messages", "/" + "workspace", str(P / "scrapers/mu_b1"), str(P / "scrapers/requirements.txt"), str(P / "manifests")], capture_output=True, text=True).stdout.split()
106
+ chk("no_hardcoded_workspace_paths_in_bundle", not wsp, {"files": wsp})
107
+ rq = (P / "scrapers/requirements.txt").read_text().splitlines()
108
+ chk("requirements_pinned", all("==" in l for l in rq if l.strip() and not l.startswith("#")) and any(l.startswith("pyarrow==") for l in rq) and any(l.startswith("requests==") for l in rq))
109
+ code = json.load(open(P / "manifests/mu_b1_code.json"))
110
+ chk("code_record_matches_bundle", all(hashlib.sha256((P / "scrapers/mu_b1" / n).read_bytes()).hexdigest() == h for n, h in code["files"].items())
111
+ and set(code["files"]) == {f.name for f in (P / "scrapers/mu_b1").iterdir() if f.is_file()})
112
+ imports = set()
113
+ for f in (P / "scrapers/mu_b1").glob("*.py"):
114
+ for m in re.finditer(r"(?m)^\s*(?:from|import)\s+([A-Za-z_][A-Za-z0-9_]*)", f.read_text()): imports.add(m.group(1))
115
+ local = {f.stem for f in (P / "scrapers/mu_b1").glob("*.py")}
116
+ std = {"argparse","html","json","os","re","sys","threading","time","hashlib","urllib","subprocess","unicodedata","collections","datetime","pathlib","shutil","__future__","typing","dataclasses","fnmatch","socket","ssl","random","math","io","glob","signal","contextlib","functools","itertools","tempfile","traceback","errno","statistics","string","copy","warnings","logging","base64","email","http","gzip","csv","struct","fcntl","queue","textwrap","uuid","inspect","codecs","types","enum","abc","platform","stat","operator","locale","resource","shlex","zlib","bisect","heapq","secrets","weakref","pprint","difflib"}
117
+ ext = {"requests","pyarrow","yaml","certifi","urllib3"}
118
+ unk = sorted(i for i in imports if i not in local | std | ext)
119
+ chk("bundle_self_contained_imports", not unk, {"unknown_imports": unk})
120
+ kg = json.load(open(P / "manifests/known_gaps.json"))
121
+ chk("known_gaps_complete", kg["whole_text_fallback_laws"]["count"] == S["whole_text_fallback"] and kg["heading_only_rows_dropped"]["count"] == S["heading_only_dropped"]
122
+ and kg["duplicate_drops"]["count"] == sum(v for k, v in S["drops"].items() if k.startswith("duplicate")))
123
+ wt = {r["id"] for r in new if json.loads(r["metadata_json"]).get("whole_text_fallback")}
124
+ chk("whole_text_laws_listed", wt == {i["law_id"] for i in kg["whole_text_fallback_laws"]["items"]})
125
+ sums = [l.split(" ", 1) for l in (P / "SHA256SUMS").read_text().splitlines()]
126
+ listed = {f for _, f in sums}; want = pack_files - {"SHA256SUMS"}
127
+ chk("sha256sums_valid_and_complete", all(hashlib.sha256((P / f).read_bytes()).hexdigest() == h for h, f in sums) and want <= listed, {"listed": len(listed), "missing": sorted(want - listed)})
128
+ for f in ("manifests/known_gaps.json", "manifests/changed_ids.json", "manifests/pii_scan_notes.md", "manifests/webmail_redactions.json", "manifests/mu_b1_code.json",
129
+ "manifests/mu_b1_summary.json", "manifests/mu_b1_drops.jsonl", "manifests/mu_b1_pii_scan.json", "scrapers/mu_b1/robots_guard.py", "scrapers/mu_b1/br_waiting.sh",
130
+ "scrapers/requirements.txt", "SHA256SUMS", "MANIFEST.md", "README.md"):
131
+ chk(f"present_{f}", (P / f).exists())
132
+ print(json.dumps(res, indent=1)); print("VERIFY", "PASS" if ok else "FAIL")
133
+ sys.exit(0 if ok else 1)
scrapers/mu_b1/webmail_mu.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Free-webmail redaction (from gh_fixb; mu_b1 adds a guard against prose like 'x at live'). Placeholder follows the GH lane convention: [redacted-webmail].
2
+ Matches standard, typo-domain, truncated, line-split, spaced and missing-'@' forms of free-webmail addresses.
3
+ Institutional/government addresses (any other domain) are left alone. Returns spans/categories only - never values."""
4
+ import re
5
+ PH='[redacted-webmail]'
6
+ S=r'[ \t]*' # spaces around '@' / '.'
7
+ WS=r'\s*' # allows a line break inside a split token
8
+ LOCAL=r'[A-Za-z0-9._%+\-]+'
9
+ STD=r'(?:gmail|googlemail|yahoo|ymail|hotmail|outlook|aol|icloud|live|msn)'
10
+ TYPO=r'(?:gmial|gmai|gamil|g\.mail|y\.mail|yaho0*o?|yahooo+|yaho0o|yhoo|hotmial|hotmai|hotmal)'
11
+ SPLIT=r'(?:g'+WS+r'mail|ya'+WS+r'hoo|hot'+WS+r'mail|y'+WS+r'mail)'
12
+ TLD=r'(?:'+S+r'\.'+S+r'(?:co'+WS+r'\.'+WS+r'uk|c'+WS+r'om\b|com\b|co\b|c\b|fr\b|de\b|ca\b|net\b))?'
13
+ AT=re.compile(r'(?<![A-Za-z0-9._%+\-])('+LOCAL+r')'+S+r'(?:@|\(at\)|\[at\]|\bat\b)'+S+r'('+STD+r'|'+TYPO+r'|'+SPLIT+r')(?![A-Za-z])('+TLD+r')',re.I)
14
+ DOT=re.compile(r'\b(?:at|dot)\b',re.I)
15
+ NOAT=re.compile(r'(?<![A-Za-z0-9._%+\-@])[A-Za-z0-9._%+\-]{3,}\.(?:gmail|yahoo|hotmail|ymail)\.(?:com|co\.uk)\b',re.I)
16
+ WORDY=re.compile(r'(?<![A-Za-z0-9._%+\-])'+LOCAL+r'\s+at\s+(?:gmail|yahoo|hotmail|ymail)\s+dot\s+(?:com|co\s+dot\s+uk)\b',re.I)
17
+ def classify(m):
18
+ s=m.group(0); dom=(m.group(2) or '').lower(); tld=m.group(3) or ''
19
+ if '\n' in s: return 'line_split'
20
+ if re.search(r'\s@|@\s',s): return 'spaced'
21
+ if not re.fullmatch(STD,dom,re.I): return 'typo_domain'
22
+ if not re.fullmatch(r'\.(?:com|co\.uk)',tld.replace(' ','') ,re.I): return 'truncated'
23
+ return 'standard'
24
+ def redact(text):
25
+ """-> (new_text, [ {category, start, end, new_start} ]) offsets refer to the input text / output text."""
26
+ spans=[]
27
+ for m in AT.finditer(text):
28
+ if "@" not in m.group(0) and not (m.group(3) or "").strip(): continue # mu_b1: bare 'x at live' prose is not an address
29
+ spans.append((m.start(),m.end(),classify(m)))
30
+ for rx,cat in ((NOAT,'missing_at'),(WORDY,'spaced_words')):
31
+ for m in rx.finditer(text):
32
+ if not any(a<m.end() and m.start()<b for a,b,_ in spans): spans.append((m.start(),m.end(),cat))
33
+ spans.sort(); out=[]; recs=[]; pos=0; shift=0
34
+ for a,b,c in spans:
35
+ out.append(text[pos:a]); ns=a+shift; out.append(PH); recs.append({'category':c,'start':a,'end':b,'new_start':ns,'new_end':ns+len(PH)})
36
+ shift+=len(PH)-(b-a); pos=b
37
+ out.append(text[pos:]); return ''.join(out),recs
38
+ WEBMAIL_CHECK=re.compile(r'[A-Za-z0-9._%+\-]+\s*@\s*(?:gmail|googlemail|yahoo|ymail|hotmail|outlook|live|msn|aol|icloud|gmx|protonmail|zoho|yandex)\b'
39
+ r'|[A-Za-z0-9._%+\-]+@(?:gmial|y\.mail|yaho0*o?|hotmial|ya\s*\n\s*hoo)\b',re.I)
scrapers/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Exact versions used to build mu_b1 (pip freeze of the libraries the scrapers import; Python 3.10+).
2
+ certifi==2026.7.22
3
+ pyarrow==25.0.1
4
+ PyYAML==6.0.3
5
+ requests==2.34.2
6
+ urllib3==2.8.0
7
+ # System tools (not pip): poppler-utils (pdftotext/pdfinfo/pdftoppm), tesseract 5 + eng tessdata, ripgrep (rg).