Admin Wave3C additive (+326; never-thin)
Browse files- data/ipfs_state_admin_rules_wave3c_additive_20261106.parquet +3 -0
- metadata/wave3c_20261106/ipfs_state_admin_rules_README.md +30 -0
- metadata/wave3c_20261106/ipfs_state_admin_rules_manifest_upload_ready.json +174 -0
- scrapers_and_normalizers/wave3c_20261106/README.md +6 -0
- scrapers_and_normalizers/wave3c_20261106/federal_collector.py +293 -0
- scrapers_and_normalizers/wave3c_20261106/gap_queue.py +25 -0
- scrapers_and_normalizers/wave3c_20261106/io_zst.py +211 -0
- scrapers_and_normalizers/wave3c_20261106/municipal_collector.py +139 -0
- scrapers_and_normalizers/wave3c_20261106/normalizer.py +214 -0
- scrapers_and_normalizers/wave3c_20261106/schema.json +7 -0
- scrapers_and_normalizers/wave3c_20261106/seeds.py +101 -0
- scrapers_and_normalizers/wave3c_20261106/state_admin_collector.py +507 -0
- scrapers_and_normalizers/wave3c_20261106/unified_daemon.py +350 -0
data/ipfs_state_admin_rules_wave3c_additive_20261106.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25976d116f7b9274508652835cdbcdbb89cf62c9b4a672e0c6c6ea8751379577
|
| 3 |
+
size 856553
|
metadata/wave3c_20261106/ipfs_state_admin_rules_README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
task_categories:
|
| 4 |
+
- text-classification
|
| 5 |
+
tags:
|
| 6 |
+
- legal
|
| 7 |
+
- administrative-law
|
| 8 |
+
- united-states
|
| 9 |
+
pretty_name: "justicedao/ipfs_state_admin_rules Wave3C additive"
|
| 10 |
+
size_categories:
|
| 11 |
+
- n<1K
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# justicedao/ipfs_state_admin_rules — Wave 3C additive shard (2026-11-06)
|
| 15 |
+
|
| 16 |
+
Net-new US administrative / EO / eCFR / Federal Register records staged **after** Wave 3B tip
|
| 17 |
+
`99ac39102c9194ca4a81ead19d4059e537cdcf41`.
|
| 18 |
+
|
| 19 |
+
## Provenance
|
| 20 |
+
- Sources: official US eCFR / Federal Register / state admin portals / governor EO pages
|
| 21 |
+
(keyless HTTPS; Wayback only on WAF with `archive_source=wayback`).
|
| 22 |
+
- Scraper bundle: `scrapers_and_normalizers/` (from `/workspace/legal-corpora/admin_scrapers_bundle/us`).
|
| 23 |
+
- Deduped against Wave 3B Parquet IDs/content_hashes and prior `admin_parquet` shards.
|
| 24 |
+
|
| 25 |
+
## Schema
|
| 26 |
+
Parquet columns match the Wave 3B normalized record schema (`id`, `gap_target_id`, `document_type`,
|
| 27 |
+
`title`, `text`, `source_url`, `content_hash`, …).
|
| 28 |
+
|
| 29 |
+
## Attribution
|
| 30 |
+
Public-domain / government works where applicable. Dataset packaging by JusticeDAO / endomorphosis corpus pipeline.
|
metadata/wave3c_20261106/ipfs_state_admin_rules_manifest_upload_ready.json
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo_id": "justicedao/ipfs_state_admin_rules",
|
| 3 |
+
"repo_slug": "ipfs_state_admin_rules",
|
| 4 |
+
"live_tip_inspected": "99ac39102c9194ca4a81ead19d4059e537cdcf41",
|
| 5 |
+
"wave3b_commits_excluded": {
|
| 6 |
+
"ipfs_state_admin_rules": "99ac39102c9194ca4a81ead19d4059e537cdcf41",
|
| 7 |
+
"ipfs_us_executive_orders": "80118e209648101a69712788b7ad47ab5883b590",
|
| 8 |
+
"ipfs_federal_register": "908b452051beeb727c7dd8fe0ee15aa7146383f8"
|
| 9 |
+
},
|
| 10 |
+
"upload_mode": "additive_parquet_shard",
|
| 11 |
+
"built_at_pt": "2026-11-06T09:06:59.368941-08:00",
|
| 12 |
+
"row_count": 326,
|
| 13 |
+
"document_type_counts": {
|
| 14 |
+
"admin_rule": 308,
|
| 15 |
+
"admin_portal_snapshot": 18
|
| 16 |
+
},
|
| 17 |
+
"files": [
|
| 18 |
+
{
|
| 19 |
+
"path": "README.md",
|
| 20 |
+
"bytes": 1081,
|
| 21 |
+
"sha256": "bf802dc3df45774088d5835c7e4cdc61ff2a1328a0499e078bd0335cad79f4e3"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"path": "data/ipfs_state_admin_rules_wave3c_additive_20261106.parquet",
|
| 25 |
+
"bytes": 856553,
|
| 26 |
+
"sha256": "25976d116f7b9274508652835cdbcdbb89cf62c9b4a672e0c6c6ea8751379577"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"path": "manifest_upload_ready.json",
|
| 30 |
+
"bytes": 5298,
|
| 31 |
+
"sha256": "40476dca9bb1dba0b76ac509826fd668f246b563c3559b47197b3f8ce4d9d36a"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"path": "scrapers_and_normalizers/README.md",
|
| 35 |
+
"bytes": 407,
|
| 36 |
+
"sha256": "9c6d8a91b36c193717f477b8cf3399bd5285bbf403fc99407685baa96d682f86"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"path": "scrapers_and_normalizers/federal_collector.py",
|
| 40 |
+
"bytes": 10505,
|
| 41 |
+
"sha256": "3a8276b4ef8f0aeb3f2832a85c746f4e4a9d71271ae2e97e00a8330a452932c5"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"path": "scrapers_and_normalizers/gap_queue.py",
|
| 45 |
+
"bytes": 959,
|
| 46 |
+
"sha256": "8afbe08ce3caf91ae6842060d1b5ef2ea469e9005fba5a7c0564f2749db45f31"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"path": "scrapers_and_normalizers/io_zst.py",
|
| 50 |
+
"bytes": 6658,
|
| 51 |
+
"sha256": "ca6f729eb2ebff1c92a363af1c1b458fe22cd86a3f5f48e5cdea97a3c4c8d22a"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"path": "scrapers_and_normalizers/municipal_collector.py",
|
| 55 |
+
"bytes": 6161,
|
| 56 |
+
"sha256": "312080292afe69a15442f57317edf87dc580910190c21ca06cc6951150e4832d"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"path": "scrapers_and_normalizers/normalizer.py",
|
| 60 |
+
"bytes": 7725,
|
| 61 |
+
"sha256": "41b3125cbe339342cbe681348ba8a0130ba0063a3e29335b0e171b372ab592e3"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"path": "scrapers_and_normalizers/schema.json",
|
| 65 |
+
"bytes": 547,
|
| 66 |
+
"sha256": "72276816aa2f9bc36fc60e2853da324b96a735a9c0c98c5bbca743cfca3b4ab6"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"path": "scrapers_and_normalizers/seeds.py",
|
| 70 |
+
"bytes": 3447,
|
| 71 |
+
"sha256": "833818d5d9ad628fdda25950b10cd65baa11fdd8d53a54efa8f5d30b498563cb"
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"path": "scrapers_and_normalizers/state_admin_collector.py",
|
| 75 |
+
"bytes": 20088,
|
| 76 |
+
"sha256": "69972fd4472d1073798c98b895fd8e529fd9b2622e577e1cde01e9f55c824718"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"path": "scrapers_and_normalizers/unified_daemon.py",
|
| 80 |
+
"bytes": 14293,
|
| 81 |
+
"sha256": "21da894a8625fea99b4b00beecc3c1a4b1da5bbb2437079ba5561a1cd38047e5"
|
| 82 |
+
}
|
| 83 |
+
],
|
| 84 |
+
"CommitOperationAdd": [
|
| 85 |
+
{
|
| 86 |
+
"op": "CommitOperationAdd",
|
| 87 |
+
"path_in_repo": "README.md",
|
| 88 |
+
"local": "README.md"
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"op": "CommitOperationAdd",
|
| 92 |
+
"path_in_repo": "data/ipfs_state_admin_rules_wave3c_additive_20261106.parquet",
|
| 93 |
+
"local": "data/ipfs_state_admin_rules_wave3c_additive_20261106.parquet"
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"op": "CommitOperationAdd",
|
| 97 |
+
"path_in_repo": "scrapers_and_normalizers/README.md",
|
| 98 |
+
"local": "scrapers_and_normalizers/README.md"
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"op": "CommitOperationAdd",
|
| 102 |
+
"path_in_repo": "scrapers_and_normalizers/federal_collector.py",
|
| 103 |
+
"local": "scrapers_and_normalizers/federal_collector.py"
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"op": "CommitOperationAdd",
|
| 107 |
+
"path_in_repo": "scrapers_and_normalizers/gap_queue.py",
|
| 108 |
+
"local": "scrapers_and_normalizers/gap_queue.py"
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"op": "CommitOperationAdd",
|
| 112 |
+
"path_in_repo": "scrapers_and_normalizers/io_zst.py",
|
| 113 |
+
"local": "scrapers_and_normalizers/io_zst.py"
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"op": "CommitOperationAdd",
|
| 117 |
+
"path_in_repo": "scrapers_and_normalizers/municipal_collector.py",
|
| 118 |
+
"local": "scrapers_and_normalizers/municipal_collector.py"
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"op": "CommitOperationAdd",
|
| 122 |
+
"path_in_repo": "scrapers_and_normalizers/normalizer.py",
|
| 123 |
+
"local": "scrapers_and_normalizers/normalizer.py"
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"op": "CommitOperationAdd",
|
| 127 |
+
"path_in_repo": "scrapers_and_normalizers/schema.json",
|
| 128 |
+
"local": "scrapers_and_normalizers/schema.json"
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"op": "CommitOperationAdd",
|
| 132 |
+
"path_in_repo": "scrapers_and_normalizers/seeds.py",
|
| 133 |
+
"local": "scrapers_and_normalizers/seeds.py"
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"op": "CommitOperationAdd",
|
| 137 |
+
"path_in_repo": "scrapers_and_normalizers/state_admin_collector.py",
|
| 138 |
+
"local": "scrapers_and_normalizers/state_admin_collector.py"
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"op": "CommitOperationAdd",
|
| 142 |
+
"path_in_repo": "scrapers_and_normalizers/unified_daemon.py",
|
| 143 |
+
"local": "scrapers_and_normalizers/unified_daemon.py"
|
| 144 |
+
}
|
| 145 |
+
],
|
| 146 |
+
"scrub_and_ast_check": {
|
| 147 |
+
"secret_or_uuid_hits": 0,
|
| 148 |
+
"ast_parse_clean": true
|
| 149 |
+
},
|
| 150 |
+
"parquet_columns": [
|
| 151 |
+
"agency",
|
| 152 |
+
"archive_source",
|
| 153 |
+
"citation",
|
| 154 |
+
"content_hash",
|
| 155 |
+
"country",
|
| 156 |
+
"document_type",
|
| 157 |
+
"effective_date",
|
| 158 |
+
"extra",
|
| 159 |
+
"gap_target_id",
|
| 160 |
+
"id",
|
| 161 |
+
"jurisdiction",
|
| 162 |
+
"locality",
|
| 163 |
+
"published_date",
|
| 164 |
+
"schema_version",
|
| 165 |
+
"scraped_at",
|
| 166 |
+
"source_url",
|
| 167 |
+
"state_or_province",
|
| 168 |
+
"subdivision_level",
|
| 169 |
+
"target_hf_repo",
|
| 170 |
+
"text",
|
| 171 |
+
"title",
|
| 172 |
+
"transport"
|
| 173 |
+
]
|
| 174 |
+
}
|
scrapers_and_normalizers/wave3c_20261106/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# US Admin Rules & EO (seed-driven, pause-capable)
|
| 2 |
+
|
| 3 |
+
- Seeds: `/workspace/coverage/world_admin_eo_seeds_20261105.jsonl`
|
| 4 |
+
- Live official URLs primary for IN/NH/TN/WY; Wayback only on failure (`archive_source`)
|
| 5 |
+
- Deep frontier crawl per state (multi-record), Governor EOs → `us_executive_orders_20261105`
|
| 6 |
+
- Memguard: pause/hibernate below 4.2 GiB, resume at 4.35 GiB; disk exit; RSS re-exec at 500 MiB
|
scrapers_and_normalizers/wave3c_20261106/federal_collector.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stream B targets: ARE-US-ECFR, ARE-US-FR, ARE-US-EO — keyless official APIs."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import io
|
| 5 |
+
import time
|
| 6 |
+
import xml.etree.ElementTree as ET
|
| 7 |
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple
|
| 8 |
+
|
| 9 |
+
import socket
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
from normalizer import from_ecfr_section, from_federal_register_doc, xml_to_text, strip_html
|
| 13 |
+
|
| 14 |
+
socket.setdefaulttimeout(25)
|
| 15 |
+
|
| 16 |
+
UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
|
| 17 |
+
FR_API = "https://www.federalregister.gov/api/v1/documents.json"
|
| 18 |
+
ECFR_TITLES = "https://www.ecfr.gov/api/versioner/v1/titles.json"
|
| 19 |
+
FR_FIELDS = [
|
| 20 |
+
"document_number", "title", "type", "subtype", "presidential_document_number",
|
| 21 |
+
"executive_order_number", "publication_date", "html_url", "abstract",
|
| 22 |
+
"body_html_url", "full_text_xml_url", "raw_text_url", "agencies", "citation",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PoliteSession:
|
| 27 |
+
def __init__(self, delay: float = 0.75):
|
| 28 |
+
self.s = requests.Session()
|
| 29 |
+
self.s.headers["User-Agent"] = UA
|
| 30 |
+
self.s.verify = True
|
| 31 |
+
self.delay = delay
|
| 32 |
+
self._last = 0.0
|
| 33 |
+
self.n = 0
|
| 34 |
+
|
| 35 |
+
def get(self, url: str, **kwargs) -> Optional[requests.Response]:
|
| 36 |
+
wait = self.delay - (time.time() - self._last)
|
| 37 |
+
if wait > 0:
|
| 38 |
+
time.sleep(wait)
|
| 39 |
+
for attempt in range(3):
|
| 40 |
+
try:
|
| 41 |
+
r = self.s.get(url, timeout=(10, 25), verify=True, **kwargs)
|
| 42 |
+
self._last = time.time()
|
| 43 |
+
self.n += 1
|
| 44 |
+
if r.status_code == 429:
|
| 45 |
+
ra = float(r.headers.get("Retry-After") or (5 * (attempt + 1)))
|
| 46 |
+
time.sleep(min(ra, 90))
|
| 47 |
+
continue
|
| 48 |
+
return r
|
| 49 |
+
except requests.RequestException:
|
| 50 |
+
time.sleep(5 * (attempt + 1))
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def ecfr_as_of(sess: PoliteSession) -> Tuple[str, List[Dict[str, Any]]]:
|
| 55 |
+
r = sess.get(ECFR_TITLES)
|
| 56 |
+
if not r or r.status_code != 200:
|
| 57 |
+
return "2026-11-04", []
|
| 58 |
+
titles = list((r.json() or {}).get("titles") or [])
|
| 59 |
+
date = titles[0].get("up_to_date_as_of") if titles else "2026-11-04"
|
| 60 |
+
return date, titles
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def iter_structure_parts(node: Dict[str, Any]) -> Iterable[str]:
|
| 64 |
+
if not isinstance(node, dict):
|
| 65 |
+
return
|
| 66 |
+
if (node.get("type") or "").lower() == "part":
|
| 67 |
+
ident = str(node.get("identifier") or "")
|
| 68 |
+
if ident:
|
| 69 |
+
yield ident
|
| 70 |
+
for c in node.get("children") or []:
|
| 71 |
+
yield from iter_structure_parts(c)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def list_parts_for_title(sess: PoliteSession, date: str, title_num: int) -> List[str]:
|
| 75 |
+
r = sess.get(f"https://www.ecfr.gov/api/versioner/v1/structure/{date}/title-{title_num}.json")
|
| 76 |
+
if not r or r.status_code != 200:
|
| 77 |
+
return []
|
| 78 |
+
return list(dict.fromkeys(iter_structure_parts(r.json())))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _section_text_from_elem(elem: ET.Element) -> Tuple[str, str]:
|
| 82 |
+
head = ""
|
| 83 |
+
chunks: List[str] = []
|
| 84 |
+
for el in elem.iter():
|
| 85 |
+
tag = (el.tag or "").split("}")[-1].upper()
|
| 86 |
+
if tag == "HEAD" and el.text and not head:
|
| 87 |
+
head = (el.text or "").strip()
|
| 88 |
+
if el.text and el.text.strip():
|
| 89 |
+
chunks.append(el.text.strip())
|
| 90 |
+
if el.tail and el.tail.strip():
|
| 91 |
+
chunks.append(el.tail.strip())
|
| 92 |
+
text = " ".join(chunks)
|
| 93 |
+
text = " ".join(text.split())
|
| 94 |
+
return head, text
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def parse_part_xml_sections(xml_bytes: bytes, title_num: int, part: str, date: str) -> List[Dict[str, Any]]:
|
| 98 |
+
"""Parse a single-part eCFR XML payload (small) into section records via iterparse."""
|
| 99 |
+
out: List[Dict[str, Any]] = []
|
| 100 |
+
source_url = f"https://www.ecfr.gov/current/title-{title_num}/part-{part}"
|
| 101 |
+
try:
|
| 102 |
+
# wrap if needed
|
| 103 |
+
raw = xml_bytes
|
| 104 |
+
if b"<ECFR" not in raw[:200] and b"<DIV" in raw[:200]:
|
| 105 |
+
raw = b"<WRAP>" + raw + b"</WRAP>"
|
| 106 |
+
context = ET.iterparse(io.BytesIO(raw), events=("end",))
|
| 107 |
+
for event, elem in context:
|
| 108 |
+
tag = (elem.tag or "").split("}")[-1].upper()
|
| 109 |
+
typ = (elem.attrib.get("TYPE") or "").upper()
|
| 110 |
+
if tag.startswith("DIV") and typ == "SECTION":
|
| 111 |
+
sec = elem.attrib.get("N") or ""
|
| 112 |
+
head, text = _section_text_from_elem(elem)
|
| 113 |
+
if text and len(text) > 20:
|
| 114 |
+
out.append(
|
| 115 |
+
from_ecfr_section(
|
| 116 |
+
title_num=title_num, part=part, section=sec,
|
| 117 |
+
head=head, text=text, source_url=f"{source_url}/section-{sec}", date=date,
|
| 118 |
+
)
|
| 119 |
+
)
|
| 120 |
+
elem.clear()
|
| 121 |
+
elif tag.startswith("DIV") and typ == "PART":
|
| 122 |
+
# if no sections emitted, keep part-level text
|
| 123 |
+
pass
|
| 124 |
+
except ET.ParseError:
|
| 125 |
+
text = xml_to_text(xml_bytes)
|
| 126 |
+
if text:
|
| 127 |
+
out.append(
|
| 128 |
+
from_ecfr_section(
|
| 129 |
+
title_num=title_num, part=part, section="",
|
| 130 |
+
head=f"Part {part}", text=text[:50000], source_url=source_url, date=date,
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
if not out:
|
| 134 |
+
text = xml_to_text(xml_bytes)
|
| 135 |
+
if text:
|
| 136 |
+
out.append(
|
| 137 |
+
from_ecfr_section(
|
| 138 |
+
title_num=title_num, part=part, section="",
|
| 139 |
+
head=f"Part {part}", text=text[:50000], source_url=source_url, date=date,
|
| 140 |
+
)
|
| 141 |
+
)
|
| 142 |
+
return out
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def collect_ecfr_title_parts(
|
| 146 |
+
sess: PoliteSession,
|
| 147 |
+
title_num: int,
|
| 148 |
+
date: str,
|
| 149 |
+
*,
|
| 150 |
+
seen_add: Callable[[str], bool],
|
| 151 |
+
max_parts: Optional[int] = None,
|
| 152 |
+
max_records: int = 200,
|
| 153 |
+
should_continue: Optional[Callable[[], bool]] = None,
|
| 154 |
+
) -> List[Dict[str, Any]]:
|
| 155 |
+
parts = list_parts_for_title(sess, date, title_num)
|
| 156 |
+
out: List[Dict[str, Any]] = []
|
| 157 |
+
for i, part in enumerate(parts):
|
| 158 |
+
if max_parts is not None and i >= max_parts:
|
| 159 |
+
break
|
| 160 |
+
if should_continue and not should_continue():
|
| 161 |
+
break
|
| 162 |
+
if len(out) >= max_records:
|
| 163 |
+
break
|
| 164 |
+
r = sess.get(
|
| 165 |
+
f"https://www.ecfr.gov/api/versioner/v1/full/{date}/title-{title_num}.xml",
|
| 166 |
+
params={"part": part},
|
| 167 |
+
)
|
| 168 |
+
if not r or r.status_code != 200 or not r.content:
|
| 169 |
+
# fallback HTML/xml current
|
| 170 |
+
r2 = sess.get(f"https://www.ecfr.gov/current/title-{title_num}/part-{part}.xml")
|
| 171 |
+
if not r2 or r2.status_code != 200:
|
| 172 |
+
continue
|
| 173 |
+
payload = r2.content
|
| 174 |
+
else:
|
| 175 |
+
payload = r.content
|
| 176 |
+
# refuse huge single payloads
|
| 177 |
+
if len(payload) > 8_000_000:
|
| 178 |
+
continue
|
| 179 |
+
for rec in parse_part_xml_sections(payload, title_num, part, date):
|
| 180 |
+
if seen_add(rec["id"]):
|
| 181 |
+
out.append(rec)
|
| 182 |
+
if len(out) >= max_records:
|
| 183 |
+
break
|
| 184 |
+
if should_continue and not should_continue():
|
| 185 |
+
break
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def iter_fr_documents(
|
| 190 |
+
sess: PoliteSession,
|
| 191 |
+
conditions: List[Tuple[str, str]],
|
| 192 |
+
*,
|
| 193 |
+
per_page: int = 100,
|
| 194 |
+
max_pages: int = 10,
|
| 195 |
+
publication_date_gte: Optional[str] = None,
|
| 196 |
+
) -> Iterable[Dict[str, Any]]:
|
| 197 |
+
for page in range(1, max_pages + 1):
|
| 198 |
+
params: List[Tuple[str, Any]] = [
|
| 199 |
+
("per_page", per_page), ("page", page), ("order", "newest"),
|
| 200 |
+
]
|
| 201 |
+
params.extend(conditions)
|
| 202 |
+
if publication_date_gte:
|
| 203 |
+
params.append(("conditions[publication_date][gte]", publication_date_gte))
|
| 204 |
+
for f in FR_FIELDS:
|
| 205 |
+
params.append(("fields[]", f))
|
| 206 |
+
r = sess.get(FR_API, params=params)
|
| 207 |
+
if not r or r.status_code != 200:
|
| 208 |
+
break
|
| 209 |
+
data = r.json() or {}
|
| 210 |
+
results = data.get("results") or []
|
| 211 |
+
if not results:
|
| 212 |
+
break
|
| 213 |
+
for doc in results:
|
| 214 |
+
yield doc
|
| 215 |
+
if page >= int(data.get("total_pages") or page):
|
| 216 |
+
break
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def fetch_doc_text(sess: PoliteSession, doc: Dict[str, Any]) -> str:
|
| 220 |
+
xml_url = doc.get("full_text_xml_url")
|
| 221 |
+
if xml_url:
|
| 222 |
+
r = sess.get(xml_url)
|
| 223 |
+
if r and r.status_code == 200 and r.content and len(r.content) < 5_000_000:
|
| 224 |
+
return xml_to_text(r.content)
|
| 225 |
+
raw = doc.get("raw_text_url")
|
| 226 |
+
if raw:
|
| 227 |
+
r = sess.get(raw)
|
| 228 |
+
if r and r.status_code == 200 and r.text and len(r.content) < 5_000_000:
|
| 229 |
+
return r.text.strip()
|
| 230 |
+
body = doc.get("body_html_url")
|
| 231 |
+
if body:
|
| 232 |
+
r = sess.get(body)
|
| 233 |
+
if r and r.status_code == 200 and r.text and len(r.content) < 5_000_000:
|
| 234 |
+
return strip_html(r.text)
|
| 235 |
+
return doc.get("abstract") or ""
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def collect_eo(
|
| 239 |
+
sess: PoliteSession,
|
| 240 |
+
seen_add: Callable[[str], bool],
|
| 241 |
+
*,
|
| 242 |
+
max_docs: int = 40,
|
| 243 |
+
kinds: Optional[List[str]] = None,
|
| 244 |
+
) -> List[Dict[str, Any]]:
|
| 245 |
+
kinds = kinds or ["executive_order", "proclamation", "determination", "memorandum", "notice"]
|
| 246 |
+
out: List[Dict[str, Any]] = []
|
| 247 |
+
for kind in kinds:
|
| 248 |
+
if len(out) >= max_docs:
|
| 249 |
+
break
|
| 250 |
+
for doc in iter_fr_documents(
|
| 251 |
+
sess,
|
| 252 |
+
[("conditions[type][]", "PRESDOCU"), ("conditions[presidential_document_type][]", kind)],
|
| 253 |
+
per_page=min(100, max_docs - len(out)),
|
| 254 |
+
max_pages=3,
|
| 255 |
+
):
|
| 256 |
+
text = fetch_doc_text(sess, doc)
|
| 257 |
+
rec = from_federal_register_doc(doc, text, gap_target_id="ARE-US-EO",
|
| 258 |
+
target_hf_repo="justicedao/ipfs_us_executive_orders")
|
| 259 |
+
if seen_add(rec["id"]):
|
| 260 |
+
out.append(rec)
|
| 261 |
+
if len(out) >= max_docs:
|
| 262 |
+
break
|
| 263 |
+
return out
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def collect_fr_after(
|
| 267 |
+
sess: PoliteSession,
|
| 268 |
+
seen_add: Callable[[str], bool],
|
| 269 |
+
*,
|
| 270 |
+
gte: str = "2026-07-01",
|
| 271 |
+
max_docs: int = 40,
|
| 272 |
+
types: Optional[List[str]] = None,
|
| 273 |
+
) -> List[Dict[str, Any]]:
|
| 274 |
+
types = types or ["RULE", "PRORULE", "NOTICE"]
|
| 275 |
+
out: List[Dict[str, Any]] = []
|
| 276 |
+
for t in types:
|
| 277 |
+
if len(out) >= max_docs:
|
| 278 |
+
break
|
| 279 |
+
for doc in iter_fr_documents(
|
| 280 |
+
sess,
|
| 281 |
+
[("conditions[type][]", t)],
|
| 282 |
+
per_page=min(100, max_docs - len(out)),
|
| 283 |
+
max_pages=2,
|
| 284 |
+
publication_date_gte=gte,
|
| 285 |
+
):
|
| 286 |
+
text = fetch_doc_text(sess, doc)
|
| 287 |
+
rec = from_federal_register_doc(doc, text, gap_target_id="ARE-US-FR",
|
| 288 |
+
target_hf_repo="justicedao/ipfs_federal_register")
|
| 289 |
+
if seen_add(rec["id"]):
|
| 290 |
+
out.append(rec)
|
| 291 |
+
if len(out) >= max_docs:
|
| 292 |
+
break
|
| 293 |
+
return out
|
scrapers_and_normalizers/wave3c_20261106/gap_queue.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load US items from world_complete_gap_matrix bot_work_queues.admin_rules_eo_scraper."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, List
|
| 7 |
+
|
| 8 |
+
MATRIX = Path("/workspace/world_complete_gap_matrix_20261105.json")
|
| 9 |
+
US_LANES = {"us_federal_admin_eo", "us_state_admin_and_eo", "us_local_admin_and_eo"}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_us_queue() -> List[Dict[str, Any]]:
|
| 13 |
+
data = json.loads(MATRIX.read_text(encoding="utf-8"))
|
| 14 |
+
q = data["bot_work_queues"]["admin_rules_eo_scraper"]
|
| 15 |
+
us = [it for it in q if it.get("lane") in US_LANES or str(it.get("target_id", "")).startswith("ARE-US-")]
|
| 16 |
+
us.sort(key=lambda x: int(x.get("priority_rank") or 9999))
|
| 17 |
+
return us
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def state_code_from_target(target_id: str) -> str | None:
|
| 21 |
+
# ARE-US-OH-ADMIN-EO -> OH
|
| 22 |
+
parts = target_id.split("-")
|
| 23 |
+
if len(parts) >= 4 and parts[0] == "ARE" and parts[1] == "US" and parts[-2] == "ADMIN":
|
| 24 |
+
return parts[2]
|
| 25 |
+
return None
|
scrapers_and_normalizers/wave3c_20261106/io_zst.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Append-only .jsonl.zst writer + SeenIds + pause-capable memguard."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import gc
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Optional, Set
|
| 10 |
+
|
| 11 |
+
import zstandard as zstd
|
| 12 |
+
|
| 13 |
+
from normalizer import dumps_line
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class JsonlZstWriter:
|
| 17 |
+
def __init__(self, path: str | Path, level: int = 3):
|
| 18 |
+
self.path = Path(path)
|
| 19 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
self._fh = open(self.path, "ab")
|
| 21 |
+
self._cctx = zstd.ZstdCompressor(level=level)
|
| 22 |
+
self.count = 0
|
| 23 |
+
|
| 24 |
+
def write(self, rec: dict) -> None:
|
| 25 |
+
line = (dumps_line(rec) + "\n").encode("utf-8")
|
| 26 |
+
self._fh.write(self._cctx.compress(line))
|
| 27 |
+
self.count += 1
|
| 28 |
+
if self.count % 20 == 0:
|
| 29 |
+
self._fh.flush()
|
| 30 |
+
|
| 31 |
+
def flush(self) -> None:
|
| 32 |
+
self._fh.flush()
|
| 33 |
+
|
| 34 |
+
def close(self) -> None:
|
| 35 |
+
try:
|
| 36 |
+
self._fh.flush()
|
| 37 |
+
finally:
|
| 38 |
+
self._fh.close()
|
| 39 |
+
|
| 40 |
+
def __enter__(self):
|
| 41 |
+
return self
|
| 42 |
+
|
| 43 |
+
def __exit__(self, *exc):
|
| 44 |
+
self.close()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def write_json(path: str | Path, obj: Any) -> None:
|
| 48 |
+
p = Path(path)
|
| 49 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
tmp = p.with_suffix(p.suffix + ".tmp")
|
| 51 |
+
tmp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 52 |
+
os.replace(tmp, p)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def load_json(path: str | Path, default: Any = None) -> Any:
|
| 56 |
+
p = Path(path)
|
| 57 |
+
if not p.exists():
|
| 58 |
+
return default
|
| 59 |
+
return json.loads(p.read_text(encoding="utf-8"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def mem_available_bytes() -> int:
|
| 63 |
+
with open("/proc/meminfo") as f:
|
| 64 |
+
for line in f:
|
| 65 |
+
if line.startswith("MemAvailable:"):
|
| 66 |
+
return int(line.split()[1]) * 1024
|
| 67 |
+
return 0
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def process_rss_bytes() -> int:
|
| 71 |
+
with open("/proc/self/status") as f:
|
| 72 |
+
for line in f:
|
| 73 |
+
if line.startswith("VmRSS:"):
|
| 74 |
+
return int(line.split()[1]) * 1024
|
| 75 |
+
return 0
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def disk_free_bytes(path: str = "/workspace") -> int:
|
| 79 |
+
st = os.statvfs(path)
|
| 80 |
+
return st.f_bavail * st.f_frsize
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class MemGuard:
|
| 84 |
+
MEM_FLOOR = 4_509_715_660 # 4.2 GiB — pause below
|
| 85 |
+
MEM_RESUME = 4_670_881_382 # 4.35 GiB — resume at/above
|
| 86 |
+
DISK_FLOOR = 10 * 1024 ** 3
|
| 87 |
+
RSS_REEXEC = 500 * 1024 ** 2 # re-exec above 500 MiB
|
| 88 |
+
RSS_CEILING = 550 * 1024 ** 2
|
| 89 |
+
|
| 90 |
+
def __init__(self, check_every_items: int = 5, check_every_seconds: float = 10.0):
|
| 91 |
+
self.check_every_items = check_every_items
|
| 92 |
+
self.check_every_seconds = check_every_seconds
|
| 93 |
+
self._n = 0
|
| 94 |
+
self._last = 0.0
|
| 95 |
+
self.stop_reason: Optional[str] = None
|
| 96 |
+
self.need_pause = False
|
| 97 |
+
self.need_reexec = False
|
| 98 |
+
self.need_exit = False
|
| 99 |
+
|
| 100 |
+
def evaluate(self) -> str:
|
| 101 |
+
"""Return 'ok' | 'pause' | 'reexec' | 'exit_disk'."""
|
| 102 |
+
mem = mem_available_bytes()
|
| 103 |
+
disk = disk_free_bytes()
|
| 104 |
+
rss = process_rss_bytes()
|
| 105 |
+
if disk < self.DISK_FLOOR:
|
| 106 |
+
self.need_exit = True
|
| 107 |
+
self.stop_reason = f"disk_stop free={disk} < {self.DISK_FLOOR}"
|
| 108 |
+
return "exit_disk"
|
| 109 |
+
if rss > self.RSS_REEXEC:
|
| 110 |
+
self.need_reexec = True
|
| 111 |
+
self.stop_reason = f"rss_reexec rss={rss} > {self.RSS_REEXEC}"
|
| 112 |
+
return "reexec"
|
| 113 |
+
if mem < self.MEM_FLOOR:
|
| 114 |
+
self.need_pause = True
|
| 115 |
+
self.stop_reason = f"paused_low_mem MemAvailable={mem} < {self.MEM_FLOOR}"
|
| 116 |
+
return "pause"
|
| 117 |
+
self.need_pause = False
|
| 118 |
+
return "ok"
|
| 119 |
+
|
| 120 |
+
def tick(self, items: int = 1) -> str:
|
| 121 |
+
self._n += items
|
| 122 |
+
now = time.time()
|
| 123 |
+
if self._n < self.check_every_items and (now - self._last) < self.check_every_seconds:
|
| 124 |
+
return "ok"
|
| 125 |
+
self._n = 0
|
| 126 |
+
self._last = now
|
| 127 |
+
return self.evaluate()
|
| 128 |
+
|
| 129 |
+
@classmethod
|
| 130 |
+
def wait_until_resume(cls, log_fn=None, status_fn=None, stop_flag=None) -> bool:
|
| 131 |
+
"""Sleep in low-RSS loop until MemAvailable >= MEM_RESUME or stop. Return True if resumed."""
|
| 132 |
+
while True:
|
| 133 |
+
if stop_flag and stop_flag():
|
| 134 |
+
return False
|
| 135 |
+
mem = mem_available_bytes()
|
| 136 |
+
disk = disk_free_bytes()
|
| 137 |
+
if disk < cls.DISK_FLOOR:
|
| 138 |
+
if log_fn:
|
| 139 |
+
log_fn(f"DISK_EXIT during pause free={disk}")
|
| 140 |
+
return False
|
| 141 |
+
if mem >= cls.MEM_RESUME:
|
| 142 |
+
gc.collect()
|
| 143 |
+
if log_fn:
|
| 144 |
+
log_fn(f"RESUME MemAvailable={mem} >= {cls.MEM_RESUME}")
|
| 145 |
+
return True
|
| 146 |
+
if status_fn:
|
| 147 |
+
status_fn(state="paused_low_mem", mem_available_bytes=mem)
|
| 148 |
+
if log_fn:
|
| 149 |
+
log_fn(f"HIBERNATE MemAvailable={mem} < {cls.MEM_RESUME}; sleep 30s")
|
| 150 |
+
gc.collect()
|
| 151 |
+
time.sleep(30)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class SeenIds:
|
| 155 |
+
def __init__(self, path: str | Path, max_keep: int = 500_000):
|
| 156 |
+
self.path = Path(path)
|
| 157 |
+
self.max_keep = max_keep
|
| 158 |
+
self.ids: Set[str] = set()
|
| 159 |
+
self._dirty = 0
|
| 160 |
+
if self.path.exists():
|
| 161 |
+
try:
|
| 162 |
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
| 163 |
+
self.ids = set(data.get("ids") or [])
|
| 164 |
+
except Exception:
|
| 165 |
+
for line in self.path.read_text(encoding="utf-8", errors="replace").splitlines():
|
| 166 |
+
line = line.strip()
|
| 167 |
+
if line and not line.startswith("{"):
|
| 168 |
+
self.ids.add(line)
|
| 169 |
+
|
| 170 |
+
def __contains__(self, rid: str) -> bool:
|
| 171 |
+
return rid in self.ids
|
| 172 |
+
|
| 173 |
+
def add(self, rid: str) -> bool:
|
| 174 |
+
if rid in self.ids:
|
| 175 |
+
return False
|
| 176 |
+
self.ids.add(rid)
|
| 177 |
+
self._dirty += 1
|
| 178 |
+
if self._dirty >= 40:
|
| 179 |
+
self.flush()
|
| 180 |
+
return True
|
| 181 |
+
|
| 182 |
+
def flush(self) -> None:
|
| 183 |
+
ids = sorted(self.ids)
|
| 184 |
+
if len(ids) > self.max_keep:
|
| 185 |
+
ids = ids[-self.max_keep :]
|
| 186 |
+
self.ids = set(ids)
|
| 187 |
+
write_json(self.path, {"ids": ids, "count": len(ids), "updated_at": time.time()})
|
| 188 |
+
self._dirty = 0
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def load_ids_from_zst(path: Path, seen: SeenIds) -> int:
|
| 192 |
+
if not path.exists():
|
| 193 |
+
return 0
|
| 194 |
+
n = 0
|
| 195 |
+
try:
|
| 196 |
+
with zstd.ZstdDecompressor().stream_reader(open(path, "rb")) as r:
|
| 197 |
+
text = r.read().decode("utf-8", errors="replace")
|
| 198 |
+
for line in text.splitlines():
|
| 199 |
+
if not line.strip():
|
| 200 |
+
continue
|
| 201 |
+
try:
|
| 202 |
+
o = json.loads(line)
|
| 203 |
+
except Exception:
|
| 204 |
+
continue
|
| 205 |
+
rid = o.get("id")
|
| 206 |
+
if rid and rid not in seen.ids:
|
| 207 |
+
seen.ids.add(rid)
|
| 208 |
+
n += 1
|
| 209 |
+
except Exception:
|
| 210 |
+
return n
|
| 211 |
+
return n
|
scrapers_and_normalizers/wave3c_20261106/municipal_collector.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ARE-US-COUNTY-MUNICIPAL-ADMIN-EO — keyless municipal/county admin rules & mayoral EOs."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import time
|
| 5 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import socket
|
| 8 |
+
import requests
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
|
| 11 |
+
from normalizer import base_record, strip_html
|
| 12 |
+
|
| 13 |
+
socket.setdefaulttimeout(25)
|
| 14 |
+
|
| 15 |
+
UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
|
| 16 |
+
TARGET = "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO"
|
| 17 |
+
HF = "justicedao/ipfs_us_executive_orders"
|
| 18 |
+
|
| 19 |
+
PORTALS = [
|
| 20 |
+
{"locality": "New York City", "state": "NY", "url": "https://rules.cityofnewyork.us/", "kind": "admin_rules"},
|
| 21 |
+
{"locality": "New York City", "state": "NY",
|
| 22 |
+
"url": "https://www.nyc.gov/office-of-the-mayor/news/executive-orders.page", "kind": "mayoral_eo"},
|
| 23 |
+
{"locality": "San Francisco", "state": "CA",
|
| 24 |
+
"url": "https://sf.gov/resource/2022/mayoral-executive-directives", "kind": "mayoral_eo"},
|
| 25 |
+
{"locality": "Chicago", "state": "IL",
|
| 26 |
+
"url": "https://www.chicago.gov/city/en/depts/mayor/press_room/executive-orders.html", "kind": "mayoral_eo"},
|
| 27 |
+
{"locality": "Los Angeles", "state": "CA",
|
| 28 |
+
"url": "https://mayor.lacity.gov/executive-directives", "kind": "mayoral_eo"},
|
| 29 |
+
{"locality": "Philadelphia", "state": "PA",
|
| 30 |
+
"url": "https://www.phila.gov/departments/mayor/executive-orders/", "kind": "mayoral_eo"},
|
| 31 |
+
{"locality": "Washington", "state": "DC",
|
| 32 |
+
"url": "https://mayor.dc.gov/mayor-orders", "kind": "mayoral_eo"},
|
| 33 |
+
{"locality": "King County", "state": "WA",
|
| 34 |
+
"url": "https://kingcounty.gov/en/legacy/council/legislation/kc_code.aspx", "kind": "county_code"},
|
| 35 |
+
{"locality": "Cook County", "state": "IL",
|
| 36 |
+
"url": "https://www.cookcountyil.gov/agency/board-commissioners", "kind": "county"},
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class PoliteSession:
|
| 41 |
+
def __init__(self, delay: float = 1.0):
|
| 42 |
+
self.s = requests.Session()
|
| 43 |
+
self.s.headers["User-Agent"] = UA
|
| 44 |
+
self.s.verify = True
|
| 45 |
+
self.delay = delay
|
| 46 |
+
self._last = 0.0
|
| 47 |
+
|
| 48 |
+
def get(self, url: str) -> Tuple[Optional[requests.Response], Optional[str]]:
|
| 49 |
+
wait = self.delay - (time.time() - self._last)
|
| 50 |
+
if wait > 0:
|
| 51 |
+
time.sleep(wait)
|
| 52 |
+
try:
|
| 53 |
+
r = self.s.get(url, timeout=(10, 25), verify=True)
|
| 54 |
+
except requests.RequestException as e:
|
| 55 |
+
self._last = time.time()
|
| 56 |
+
return None, f"net_error:{e.__class__.__name__}"
|
| 57 |
+
self._last = time.time()
|
| 58 |
+
low = (r.text or "")[:4000].lower()
|
| 59 |
+
if r.status_code in (403, 429, 503) or "just a moment" in low or "captcha" in low:
|
| 60 |
+
return r, "blocked_waf"
|
| 61 |
+
if r.status_code != 200:
|
| 62 |
+
return r, f"http_{r.status_code}"
|
| 63 |
+
return r, None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def collect_municipal(
|
| 67 |
+
sess: PoliteSession,
|
| 68 |
+
seen_add: Callable[[str], bool],
|
| 69 |
+
*,
|
| 70 |
+
max_records: int = 30,
|
| 71 |
+
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 72 |
+
out: List[Dict[str, Any]] = []
|
| 73 |
+
manifest: List[Dict[str, Any]] = []
|
| 74 |
+
for p in PORTALS:
|
| 75 |
+
if len(out) >= max_records:
|
| 76 |
+
break
|
| 77 |
+
r, flag = sess.get(p["url"])
|
| 78 |
+
entry = {**p, "status": flag or ("ok" if r else "fetch_failed"),
|
| 79 |
+
"http_status": getattr(r, "status_code", None)}
|
| 80 |
+
manifest.append(entry)
|
| 81 |
+
if not r or flag:
|
| 82 |
+
# status stub
|
| 83 |
+
rec = base_record(
|
| 84 |
+
gap_target_id=TARGET, jurisdiction=f"US-{p['state']}-{p['locality'][:12]}",
|
| 85 |
+
subdivision_level="municipal" if "County" not in p["locality"] else "county",
|
| 86 |
+
document_type="portal_status", title=f"{p['locality']} portal {entry['status']}",
|
| 87 |
+
text=f"status={entry['status']} url={p['url']}", source_url=p["url"],
|
| 88 |
+
state_or_province=p["state"], locality=p["locality"],
|
| 89 |
+
target_hf_repo=HF, extra={"portal_kind": p["kind"], "portal_status": entry["status"]},
|
| 90 |
+
)
|
| 91 |
+
if seen_add(rec["id"]):
|
| 92 |
+
out.append(rec)
|
| 93 |
+
continue
|
| 94 |
+
soup = BeautifulSoup(r.text, "html.parser")
|
| 95 |
+
title = soup.title.get_text(" ", strip=True) if soup.title else p["locality"]
|
| 96 |
+
text = soup.get_text("\n", strip=True)[:10000]
|
| 97 |
+
dtype = "mayoral_eo" if p["kind"] == "mayoral_eo" else "municipal_admin_rules"
|
| 98 |
+
rec = base_record(
|
| 99 |
+
gap_target_id=TARGET, jurisdiction=f"US-{p['state']}",
|
| 100 |
+
subdivision_level="municipal" if "County" not in p["locality"] else "county",
|
| 101 |
+
document_type=dtype, title=title, text=text, source_url=p["url"],
|
| 102 |
+
state_or_province=p["state"], locality=p["locality"],
|
| 103 |
+
target_hf_repo=HF, extra={"portal_kind": p["kind"]},
|
| 104 |
+
)
|
| 105 |
+
if seen_add(rec["id"]):
|
| 106 |
+
out.append(rec)
|
| 107 |
+
# follow a few same-host links that look like EO/order docs
|
| 108 |
+
host = p["url"].split("/")[2]
|
| 109 |
+
followed = 0
|
| 110 |
+
for a in soup.select("a[href]"):
|
| 111 |
+
if followed >= 3 or len(out) >= max_records:
|
| 112 |
+
break
|
| 113 |
+
href = a.get("href") or ""
|
| 114 |
+
if href.startswith("/"):
|
| 115 |
+
href = p["url"].rstrip("/") + "/" + href.lstrip("/") if "://" not in href else href
|
| 116 |
+
# fix double
|
| 117 |
+
if href.startswith("/"):
|
| 118 |
+
href = "https://" + host + href
|
| 119 |
+
if host not in href:
|
| 120 |
+
continue
|
| 121 |
+
low = href.lower()
|
| 122 |
+
if not any(k in low for k in ("executive", "order", "eo-", "directive", "rule")):
|
| 123 |
+
continue
|
| 124 |
+
r2, f2 = sess.get(href)
|
| 125 |
+
if not r2 or f2:
|
| 126 |
+
continue
|
| 127 |
+
t2 = strip_html(r2.text)[:12000]
|
| 128 |
+
if len(t2) < 80:
|
| 129 |
+
continue
|
| 130 |
+
rec2 = base_record(
|
| 131 |
+
gap_target_id=TARGET, jurisdiction=f"US-{p['state']}",
|
| 132 |
+
subdivision_level="municipal", document_type=dtype,
|
| 133 |
+
title=(a.get_text(" ", strip=True) or href)[:200], text=t2, source_url=href,
|
| 134 |
+
state_or_province=p["state"], locality=p["locality"], target_hf_repo=HF,
|
| 135 |
+
)
|
| 136 |
+
if seen_add(rec2["id"]):
|
| 137 |
+
out.append(rec2)
|
| 138 |
+
followed += 1
|
| 139 |
+
return out, manifest
|
scrapers_and_normalizers/wave3c_20261106/normalizer.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalize US admin-rule / EO / FR / eCFR rows into a shared schema with gap_target_id."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from typing import Any, Dict, Optional
|
| 9 |
+
from xml.etree import ElementTree as ET
|
| 10 |
+
|
| 11 |
+
SCHEMA_VERSION = "us_admin_rules_eo_normalized_v2"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def utc_now() -> str:
|
| 15 |
+
return datetime.now(timezone.utc).isoformat()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def sha256_text(text: str) -> str:
|
| 19 |
+
return hashlib.sha256((text or "").encode("utf-8", errors="replace")).hexdigest()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def make_id(*parts: str) -> str:
|
| 23 |
+
return sha256_text("|".join(p or "" for p in parts))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def strip_html(html: str) -> str:
|
| 27 |
+
if not html:
|
| 28 |
+
return ""
|
| 29 |
+
text = re.sub(r"(?is)<script[^>]*>.*?</script>", " ", html)
|
| 30 |
+
text = re.sub(r"(?is)<style[^>]*>.*?</style>", " ", text)
|
| 31 |
+
text = re.sub(r"(?s)<[^>]+>", " ", text)
|
| 32 |
+
text = re.sub(r" ", " ", text)
|
| 33 |
+
text = re.sub(r"&", "&", text)
|
| 34 |
+
text = re.sub(r"<", "<", text)
|
| 35 |
+
text = re.sub(r">", ">", text)
|
| 36 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def xml_to_text(xml_bytes: bytes | str) -> str:
|
| 40 |
+
if isinstance(xml_bytes, bytes):
|
| 41 |
+
raw = xml_bytes.decode("utf-8", errors="replace")
|
| 42 |
+
else:
|
| 43 |
+
raw = xml_bytes
|
| 44 |
+
try:
|
| 45 |
+
root = ET.fromstring(raw)
|
| 46 |
+
except ET.ParseError:
|
| 47 |
+
return strip_html(raw)
|
| 48 |
+
chunks: list[str] = []
|
| 49 |
+
for el in root.iter():
|
| 50 |
+
if el.text and el.text.strip():
|
| 51 |
+
chunks.append(el.text.strip())
|
| 52 |
+
if el.tail and el.tail.strip():
|
| 53 |
+
chunks.append(el.tail.strip())
|
| 54 |
+
return re.sub(r"\s+", " ", " ".join(chunks)).strip()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def base_record(
|
| 58 |
+
*,
|
| 59 |
+
gap_target_id: str,
|
| 60 |
+
jurisdiction: str,
|
| 61 |
+
subdivision_level: str,
|
| 62 |
+
document_type: str,
|
| 63 |
+
title: str,
|
| 64 |
+
text: str,
|
| 65 |
+
source_url: str,
|
| 66 |
+
citation: Optional[str] = None,
|
| 67 |
+
agency: Optional[str] = None,
|
| 68 |
+
state_or_province: Optional[str] = None,
|
| 69 |
+
locality: Optional[str] = None,
|
| 70 |
+
effective_date: Optional[str] = None,
|
| 71 |
+
published_date: Optional[str] = None,
|
| 72 |
+
transport: str = "https",
|
| 73 |
+
archive_source: Optional[str] = None,
|
| 74 |
+
scraped_at: Optional[str] = None,
|
| 75 |
+
extra: Optional[Dict[str, Any]] = None,
|
| 76 |
+
target_hf_repo: Optional[str] = None,
|
| 77 |
+
) -> Dict[str, Any]:
|
| 78 |
+
text = (text or "").strip()
|
| 79 |
+
content_hash = sha256_text(text)
|
| 80 |
+
rid = make_id(gap_target_id, jurisdiction, document_type, citation or "", source_url, content_hash[:16])
|
| 81 |
+
return {
|
| 82 |
+
"id": rid,
|
| 83 |
+
"gap_target_id": gap_target_id,
|
| 84 |
+
"schema_version": SCHEMA_VERSION,
|
| 85 |
+
"jurisdiction": jurisdiction,
|
| 86 |
+
"subdivision_level": subdivision_level,
|
| 87 |
+
"country": "US",
|
| 88 |
+
"state_or_province": state_or_province,
|
| 89 |
+
"locality": locality,
|
| 90 |
+
"document_type": document_type,
|
| 91 |
+
"agency": agency,
|
| 92 |
+
"citation": citation,
|
| 93 |
+
"title": title,
|
| 94 |
+
"text": text,
|
| 95 |
+
"effective_date": effective_date,
|
| 96 |
+
"published_date": published_date,
|
| 97 |
+
"source_url": source_url,
|
| 98 |
+
"transport": transport,
|
| 99 |
+
"archive_source": archive_source,
|
| 100 |
+
"scraped_at": scraped_at or utc_now(),
|
| 101 |
+
"content_hash": content_hash,
|
| 102 |
+
"target_hf_repo": target_hf_repo,
|
| 103 |
+
"extra": extra or {},
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def from_oh_official_row(row: Dict[str, Any], gap_target_id: str = "ARE-US-OH-ADMIN-EO",
|
| 108 |
+
target_hf_repo: str = "justicedao/ipfs_state_admin_rules") -> Dict[str, Any]:
|
| 109 |
+
return base_record(
|
| 110 |
+
gap_target_id=gap_target_id,
|
| 111 |
+
jurisdiction=f"US-{row.get('state') or 'OH'}",
|
| 112 |
+
subdivision_level="state",
|
| 113 |
+
document_type="admin_rule",
|
| 114 |
+
title=row.get("title") or "",
|
| 115 |
+
text=row.get("text") or "",
|
| 116 |
+
source_url=row.get("source_url") or "",
|
| 117 |
+
citation=row.get("citation"),
|
| 118 |
+
state_or_province=row.get("state") or "OH",
|
| 119 |
+
transport=row.get("transport") or "https",
|
| 120 |
+
scraped_at=row.get("fetched_at"),
|
| 121 |
+
target_hf_repo=target_hf_repo,
|
| 122 |
+
extra={"legacy_sha256": row.get("sha256")},
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def from_federal_register_doc(doc: Dict[str, Any], text: str, gap_target_id: str,
|
| 127 |
+
target_hf_repo: Optional[str] = None) -> Dict[str, Any]:
|
| 128 |
+
subtype = (doc.get("subtype") or "").strip()
|
| 129 |
+
ptype = (doc.get("type") or "").strip()
|
| 130 |
+
if gap_target_id == "ARE-US-EO" or subtype.lower() == "executive order" or doc.get("executive_order_number"):
|
| 131 |
+
if "proclamation" in subtype.lower():
|
| 132 |
+
document_type = "proclamation"
|
| 133 |
+
elif "determination" in subtype.lower():
|
| 134 |
+
document_type = "determination"
|
| 135 |
+
elif "memorandum" in subtype.lower():
|
| 136 |
+
document_type = "memorandum"
|
| 137 |
+
elif "administrative" in subtype.lower():
|
| 138 |
+
document_type = "administrative_order"
|
| 139 |
+
elif gap_target_id == "ARE-US-EO" and subtype:
|
| 140 |
+
document_type = subtype.lower().replace(" ", "_")
|
| 141 |
+
else:
|
| 142 |
+
document_type = "executive_order"
|
| 143 |
+
elif ptype == "Rule":
|
| 144 |
+
document_type = "rule"
|
| 145 |
+
elif ptype == "Proposed Rule":
|
| 146 |
+
document_type = "proposed_rule"
|
| 147 |
+
elif ptype == "Notice":
|
| 148 |
+
document_type = "register_notice"
|
| 149 |
+
else:
|
| 150 |
+
document_type = (ptype or "register_document").lower().replace(" ", "_")
|
| 151 |
+
|
| 152 |
+
agencies = doc.get("agencies") or []
|
| 153 |
+
agency = None
|
| 154 |
+
if agencies and isinstance(agencies[0], dict):
|
| 155 |
+
agency = agencies[0].get("name") or agencies[0].get("raw_name")
|
| 156 |
+
elif agencies and isinstance(agencies[0], str):
|
| 157 |
+
agency = agencies[0]
|
| 158 |
+
|
| 159 |
+
citation = doc.get("citation")
|
| 160 |
+
if document_type == "executive_order" and doc.get("executive_order_number"):
|
| 161 |
+
citation = citation or f"E.O. {doc['executive_order_number']}"
|
| 162 |
+
|
| 163 |
+
if not target_hf_repo:
|
| 164 |
+
target_hf_repo = (
|
| 165 |
+
"justicedao/ipfs_us_executive_orders" if gap_target_id == "ARE-US-EO"
|
| 166 |
+
else "justicedao/ipfs_federal_register"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
return base_record(
|
| 170 |
+
gap_target_id=gap_target_id,
|
| 171 |
+
jurisdiction="US-FEDERAL",
|
| 172 |
+
subdivision_level="federal",
|
| 173 |
+
document_type=document_type,
|
| 174 |
+
title=doc.get("title") or "",
|
| 175 |
+
text=text or (doc.get("abstract") or ""),
|
| 176 |
+
source_url=doc.get("html_url") or doc.get("body_html_url") or "",
|
| 177 |
+
citation=citation,
|
| 178 |
+
agency=agency,
|
| 179 |
+
published_date=doc.get("publication_date"),
|
| 180 |
+
transport="https",
|
| 181 |
+
target_hf_repo=target_hf_repo,
|
| 182 |
+
extra={
|
| 183 |
+
"document_number": doc.get("document_number"),
|
| 184 |
+
"presidential_document_number": doc.get("presidential_document_number"),
|
| 185 |
+
"executive_order_number": doc.get("executive_order_number"),
|
| 186 |
+
"subtype": subtype,
|
| 187 |
+
"full_text_xml_url": doc.get("full_text_xml_url"),
|
| 188 |
+
"body_html_url": doc.get("body_html_url"),
|
| 189 |
+
"raw_text_url": doc.get("raw_text_url"),
|
| 190 |
+
},
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def from_ecfr_section(*, title_num: int, part: str, section: str, head: str, text: str,
|
| 195 |
+
source_url: str, date: str) -> Dict[str, Any]:
|
| 196 |
+
citation = f"{title_num} CFR § {section}" if section else f"{title_num} CFR Part {part}"
|
| 197 |
+
return base_record(
|
| 198 |
+
gap_target_id="ARE-US-ECFR",
|
| 199 |
+
jurisdiction="US-FEDERAL",
|
| 200 |
+
subdivision_level="federal",
|
| 201 |
+
document_type="ecfr_section" if section else "ecfr_part",
|
| 202 |
+
title=head or citation,
|
| 203 |
+
text=text,
|
| 204 |
+
source_url=source_url,
|
| 205 |
+
citation=citation,
|
| 206 |
+
published_date=date,
|
| 207 |
+
transport="https",
|
| 208 |
+
target_hf_repo="justicedao/ipfs_us_cfr",
|
| 209 |
+
extra={"ecfr_title": title_num, "ecfr_part": part, "ecfr_section": section, "as_of": date},
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def dumps_line(rec: Dict[str, Any]) -> str:
|
| 214 |
+
return json.dumps(rec, ensure_ascii=False, separators=(",", ":"))
|
scrapers_and_normalizers/wave3c_20261106/schema.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "us_admin_rules_eo_normalized_v2",
|
| 3 |
+
"required_fields": ["id", "gap_target_id", "jurisdiction", "subdivision_level", "country", "document_type", "title", "text", "source_url", "transport", "scraped_at", "content_hash"],
|
| 4 |
+
"gap_target_ids": ["ARE-US-ECFR", "ARE-US-FR", "ARE-US-EO", "ARE-US-*-ADMIN-EO", "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO"],
|
| 5 |
+
"dedupe": "persistent SeenIds checkpoint; skip emitted id on restart",
|
| 6 |
+
"memguard": {"MemAvailable_floor_bytes": 4509715660, "disk_floor_bytes": 10737418240, "rss_ceiling_bytes": 576716800}
|
| 7 |
+
}
|
scrapers_and_normalizers/wave3c_20261106/seeds.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load verified US seeds from world_admin_eo_seeds_20261105.jsonl."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
SEEDS_PATH = Path("/workspace/coverage/world_admin_eo_seeds_20261105.jsonl")
|
| 11 |
+
WAYBACK_RE = re.compile(r"^https?://web\.archive\.org/web/\d+(?:id_)?/(https?://.*)$", re.I)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def unwrap_wayback(url: str) -> Tuple[str, bool]:
|
| 15 |
+
"""Return (live_or_original_url, was_wayback)."""
|
| 16 |
+
m = WAYBACK_RE.match(url or "")
|
| 17 |
+
if m:
|
| 18 |
+
return m.group(1), True
|
| 19 |
+
return url, False
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_us_seeds() -> List[Dict[str, Any]]:
|
| 23 |
+
rows = []
|
| 24 |
+
for line in SEEDS_PATH.read_text(encoding="utf-8").splitlines():
|
| 25 |
+
if not line.strip():
|
| 26 |
+
continue
|
| 27 |
+
o = json.loads(line)
|
| 28 |
+
if str(o.get("target_id", "")).startswith("ARE-US-"):
|
| 29 |
+
rows.append(o)
|
| 30 |
+
# preserve file order (matches gap matrix priority)
|
| 31 |
+
return rows
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def seed_urls_by_role(seed: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
|
| 35 |
+
out: Dict[str, List[Dict[str, Any]]] = {}
|
| 36 |
+
for u in seed.get("urls") or []:
|
| 37 |
+
role = u.get("role") or "unknown"
|
| 38 |
+
out.setdefault(role, []).append(u)
|
| 39 |
+
return out
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def preferred_fetch_urls(seed: Dict[str, Any], role: str) -> List[Tuple[str, Optional[str]]]:
|
| 43 |
+
"""Return ordered (url, archive_source) pairs: live first, then wayback fallbacks.
|
| 44 |
+
|
| 45 |
+
archive_source is None for live official; 'wayback' for archive.org URLs.
|
| 46 |
+
"""
|
| 47 |
+
roles = seed_urls_by_role(seed)
|
| 48 |
+
entries = roles.get(role) or []
|
| 49 |
+
live: List[Tuple[str, Optional[str]]] = []
|
| 50 |
+
wb: List[Tuple[str, Optional[str]]] = []
|
| 51 |
+
seen = set()
|
| 52 |
+
for e in entries:
|
| 53 |
+
raw = e.get("url") or ""
|
| 54 |
+
orig, was_wb = unwrap_wayback(raw)
|
| 55 |
+
if orig not in seen:
|
| 56 |
+
live.append((orig, None))
|
| 57 |
+
seen.add(orig)
|
| 58 |
+
if was_wb and raw not in seen:
|
| 59 |
+
wb.append((raw, "wayback"))
|
| 60 |
+
seen.add(raw)
|
| 61 |
+
elif not was_wb:
|
| 62 |
+
# also keep raw if somehow different
|
| 63 |
+
pass
|
| 64 |
+
# Extra live candidates for hard states
|
| 65 |
+
tid = seed.get("target_id") or ""
|
| 66 |
+
extras = {
|
| 67 |
+
"ARE-US-IN-ADMIN-EO": [
|
| 68 |
+
"https://iga.in.gov/laws/iac",
|
| 69 |
+
"https://iar.iga.in.gov/iac/irtoc.htm",
|
| 70 |
+
"https://iar.iga.in.gov/code/current",
|
| 71 |
+
],
|
| 72 |
+
"ARE-US-NH-ADMIN-EO": [
|
| 73 |
+
"https://gc.nh.gov/rules/",
|
| 74 |
+
"https://gc.nh.gov/rules/about_rules/listagencies.aspx",
|
| 75 |
+
"https://www.gencourt.state.nh.us/rules/",
|
| 76 |
+
],
|
| 77 |
+
"ARE-US-TN-ADMIN-EO": [
|
| 78 |
+
"https://publications.tnsosfiles.com/rules/",
|
| 79 |
+
"https://sos.tn.gov/publications/services/effective-rules-and-regulations-of-the-state-of-tennessee",
|
| 80 |
+
],
|
| 81 |
+
"ARE-US-WY-ADMIN-EO": [
|
| 82 |
+
"https://rules.wyo.gov/",
|
| 83 |
+
"https://rules.wyo.gov/Search.aspx",
|
| 84 |
+
"https://rules.wyo.gov/Search.aspx?mode=7",
|
| 85 |
+
],
|
| 86 |
+
}
|
| 87 |
+
if role == "admin_code":
|
| 88 |
+
pref=[]
|
| 89 |
+
for u in extras.get(tid, []):
|
| 90 |
+
if u not in seen:
|
| 91 |
+
pref.append((u, None))
|
| 92 |
+
seen.add(u)
|
| 93 |
+
live = pref + live
|
| 94 |
+
return live + wb
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def state_code_from_target(target_id: str) -> Optional[str]:
|
| 98 |
+
parts = target_id.split("-")
|
| 99 |
+
if len(parts) >= 4 and parts[0] == "ARE" and parts[1] == "US" and parts[-2] == "ADMIN":
|
| 100 |
+
return parts[2]
|
| 101 |
+
return None
|
scrapers_and_normalizers/wave3c_20261106/state_admin_collector.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deep US state/territory admin-code + governor EO crawler (seed-driven).
|
| 2 |
+
|
| 3 |
+
Uses /workspace/coverage/world_admin_eo_seeds_20261105.jsonl verified portals.
|
| 4 |
+
Live official URLs first; Wayback only if live fails (archive_source=wayback).
|
| 5 |
+
Extracts multiple substantive rule/EO pages per cycle via URL frontier checkpoints.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import time
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
| 16 |
+
from urllib.parse import urljoin, urlparse
|
| 17 |
+
|
| 18 |
+
import socket
|
| 19 |
+
import requests
|
| 20 |
+
from bs4 import BeautifulSoup
|
| 21 |
+
|
| 22 |
+
from normalizer import base_record, from_oh_official_row, strip_html
|
| 23 |
+
from seeds import preferred_fetch_urls, state_code_from_target, unwrap_wayback
|
| 24 |
+
|
| 25 |
+
socket.setdefaulttimeout(25)
|
| 26 |
+
|
| 27 |
+
UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
|
| 28 |
+
OH_BASE = "https://codes.ohio.gov"
|
| 29 |
+
OH_ROWS = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/OH.official/rows.jsonl")
|
| 30 |
+
OH_CURSOR = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/_collector/oh_agency_cursor.json")
|
| 31 |
+
FRONTIER_DIR = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/_collector/frontiers")
|
| 32 |
+
STATE_ROOT = Path("/workspace/legal-corpora/us_state_admin_rules_20261104")
|
| 33 |
+
EO_ROOT = Path("/workspace/legal-corpora/us_executive_orders_20261105")
|
| 34 |
+
|
| 35 |
+
RULE_HINTS = re.compile(
|
| 36 |
+
r"(rule|rules|regulation|admin.?code|chapter|title|section|csr|nac|wac|oac|iac|kar|njac|comar|tar)",
|
| 37 |
+
re.I,
|
| 38 |
+
)
|
| 39 |
+
EO_HINTS = re.compile(r"(executive.?order|exec.?order|\beo\b|proclamation|directive|governor)", re.I)
|
| 40 |
+
NAV_NOISE = re.compile(r"(login|signin|cart|facebook|twitter|linkedin|instagram|javascript:|#)$", re.I)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PoliteSession:
|
| 44 |
+
def __init__(self, delay: float = 0.9):
|
| 45 |
+
self.s = requests.Session()
|
| 46 |
+
self.s.headers["User-Agent"] = UA
|
| 47 |
+
self.s.verify = True
|
| 48 |
+
self.delay = delay
|
| 49 |
+
self._last = 0.0
|
| 50 |
+
self.n = 0
|
| 51 |
+
|
| 52 |
+
def get(self, url: str) -> Tuple[Optional[requests.Response], Optional[str]]:
|
| 53 |
+
wait = self.delay - (time.time() - self._last)
|
| 54 |
+
if wait > 0:
|
| 55 |
+
time.sleep(wait)
|
| 56 |
+
try:
|
| 57 |
+
r = self.s.get(url, timeout=(10, 25), verify=True, allow_redirects=True)
|
| 58 |
+
except requests.RequestException as e:
|
| 59 |
+
self._last = time.time()
|
| 60 |
+
return None, f"net_error:{e.__class__.__name__}"
|
| 61 |
+
self._last = time.time()
|
| 62 |
+
self.n += 1
|
| 63 |
+
low = (r.text or "")[:5000].lower()
|
| 64 |
+
if r.status_code in (403, 429, 503) or "cf-challenge" in low or "just a moment" in low or "captcha" in low:
|
| 65 |
+
return r, "blocked_waf"
|
| 66 |
+
if r.status_code != 200:
|
| 67 |
+
return r, f"http_{r.status_code}"
|
| 68 |
+
return r, None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def wayback_closest(sess: PoliteSession, url: str) -> Tuple[Optional[str], Optional[requests.Response]]:
|
| 72 |
+
api = f"https://archive.org/wayback/available?url={url}"
|
| 73 |
+
r, flag = sess.get(api)
|
| 74 |
+
if not r or flag:
|
| 75 |
+
return None, None
|
| 76 |
+
try:
|
| 77 |
+
snap = (((r.json() or {}).get("archived_snapshots") or {}).get("closest") or {})
|
| 78 |
+
wu = snap.get("url")
|
| 79 |
+
except Exception:
|
| 80 |
+
return None, None
|
| 81 |
+
if not wu:
|
| 82 |
+
return None, None
|
| 83 |
+
r2, flag2 = sess.get(wu)
|
| 84 |
+
if not r2 or flag2:
|
| 85 |
+
return wu, None
|
| 86 |
+
return wu, r2
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def fetch_with_fallback(
|
| 90 |
+
sess: PoliteSession, candidates: List[Tuple[str, Optional[str]]]
|
| 91 |
+
) -> Tuple[Optional[requests.Response], str, Optional[str], Optional[str]]:
|
| 92 |
+
"""Try live URLs then wayback. Returns (resp, final_url, archive_source, status)."""
|
| 93 |
+
last_status = "no_candidates"
|
| 94 |
+
for url, arch in candidates:
|
| 95 |
+
r, flag = sess.get(url)
|
| 96 |
+
if r and not flag:
|
| 97 |
+
return r, url, arch, "ok"
|
| 98 |
+
last_status = flag or "fetch_failed"
|
| 99 |
+
if flag == "blocked_waf" or (r and r.status_code in (403, 401, 404, 500)):
|
| 100 |
+
# try wayback of the live URL
|
| 101 |
+
live, _ = unwrap_wayback(url)
|
| 102 |
+
wu, wr = wayback_closest(sess, live)
|
| 103 |
+
if wr:
|
| 104 |
+
return wr, wu or url, "wayback", "ok_wayback"
|
| 105 |
+
return None, "", None, last_status
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _same_site(base: str, href: str) -> bool:
|
| 109 |
+
try:
|
| 110 |
+
b = urlparse(base).netloc.lower().lstrip("www.")
|
| 111 |
+
h = urlparse(href).netloc.lower().lstrip("www.")
|
| 112 |
+
return bool(h) and (h == b or h.endswith("." + b) or b.endswith("." + h))
|
| 113 |
+
except Exception:
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def extract_links(base_url: str, html: str, kind: str) -> List[str]:
|
| 118 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 119 |
+
out: List[str] = []
|
| 120 |
+
for a in soup.select("a[href]"):
|
| 121 |
+
href = (a.get("href") or "").strip()
|
| 122 |
+
if not href or href.startswith("mailto:") or NAV_NOISE.search(href):
|
| 123 |
+
continue
|
| 124 |
+
full = urljoin(base_url, href)
|
| 125 |
+
if full.startswith("//"):
|
| 126 |
+
full = "https:" + full
|
| 127 |
+
if not full.startswith("http"):
|
| 128 |
+
continue
|
| 129 |
+
if not _same_site(base_url, full):
|
| 130 |
+
continue
|
| 131 |
+
text = (a.get_text(" ", strip=True) or "") + " " + full
|
| 132 |
+
if kind == "admin" and not RULE_HINTS.search(text) and not RULE_HINTS.search(full):
|
| 133 |
+
# still allow .pdf/.htm rule-ish paths
|
| 134 |
+
if not re.search(r"\.(pdf|html?|aspx?)$", full, re.I):
|
| 135 |
+
continue
|
| 136 |
+
if kind == "eo" and not EO_HINTS.search(text) and not EO_HINTS.search(full):
|
| 137 |
+
if not re.search(r"\.(pdf|html?|aspx?)$", full, re.I):
|
| 138 |
+
continue
|
| 139 |
+
out.append(full.split("#")[0])
|
| 140 |
+
# dedupe preserve order
|
| 141 |
+
return list(dict.fromkeys(out))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def is_substantive(text: str, title: str = "") -> bool:
|
| 145 |
+
t = (text or "").strip()
|
| 146 |
+
if len(t) < 400:
|
| 147 |
+
return False
|
| 148 |
+
# reject thin nav shells
|
| 149 |
+
low = t.lower()
|
| 150 |
+
nav_marks = sum(1 for k in ("home", "contact us", "privacy", "accessibility", "skip to") if k in low[:800])
|
| 151 |
+
if nav_marks >= 3 and len(t) < 1200:
|
| 152 |
+
return False
|
| 153 |
+
return True
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def frontier_path(target_id: str) -> Path:
|
| 157 |
+
FRONTIER_DIR.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
safe = re.sub(r"[^A-Za-z0-9_\-]", "_", target_id)
|
| 159 |
+
return FRONTIER_DIR / f"{safe}.json"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def load_frontier(target_id: str) -> Dict[str, Any]:
|
| 163 |
+
p = frontier_path(target_id)
|
| 164 |
+
if p.exists():
|
| 165 |
+
try:
|
| 166 |
+
return json.loads(p.read_text(encoding="utf-8"))
|
| 167 |
+
except Exception:
|
| 168 |
+
pass
|
| 169 |
+
return {"queue": [], "visited": [], "cursor": 0}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def save_frontier(target_id: str, fr: Dict[str, Any]) -> None:
|
| 173 |
+
# cap visited
|
| 174 |
+
visited = list(dict.fromkeys(fr.get("visited") or []))[-4000:]
|
| 175 |
+
queue = list(dict.fromkeys(fr.get("queue") or []))[:2000]
|
| 176 |
+
fr = {"queue": queue, "visited": visited, "cursor": int(fr.get("cursor") or 0),
|
| 177 |
+
"updated_at": datetime.now(timezone.utc).isoformat()}
|
| 178 |
+
p = frontier_path(target_id)
|
| 179 |
+
tmp = p.with_suffix(".tmp")
|
| 180 |
+
tmp.write_text(json.dumps(fr), encoding="utf-8")
|
| 181 |
+
tmp.replace(p)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def make_doc_record(
|
| 185 |
+
*,
|
| 186 |
+
gap_target_id: str,
|
| 187 |
+
state: str,
|
| 188 |
+
title: str,
|
| 189 |
+
text: str,
|
| 190 |
+
source_url: str,
|
| 191 |
+
document_type: str,
|
| 192 |
+
archive_source: Optional[str],
|
| 193 |
+
target_hf_repo: str,
|
| 194 |
+
locality: Optional[str] = None,
|
| 195 |
+
) -> Dict[str, Any]:
|
| 196 |
+
level = "territorial" if state in ("PR", "GU", "VI", "AS", "MP", "DC") and locality is None else "state"
|
| 197 |
+
if state == "DC":
|
| 198 |
+
level = "state"
|
| 199 |
+
if locality:
|
| 200 |
+
level = "municipal"
|
| 201 |
+
return base_record(
|
| 202 |
+
gap_target_id=gap_target_id,
|
| 203 |
+
jurisdiction=f"US-{state}",
|
| 204 |
+
subdivision_level=level,
|
| 205 |
+
document_type=document_type,
|
| 206 |
+
title=title[:300],
|
| 207 |
+
text=text[:60000],
|
| 208 |
+
source_url=source_url,
|
| 209 |
+
citation=title[:200] if title else None,
|
| 210 |
+
state_or_province=state,
|
| 211 |
+
locality=locality,
|
| 212 |
+
transport="https" if source_url.startswith("https") else "http",
|
| 213 |
+
archive_source=archive_source,
|
| 214 |
+
target_hf_repo=target_hf_repo,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ---- OH deep resume (unchanged approach) ----
|
| 219 |
+
def load_oh_done_urls() -> Set[str]:
|
| 220 |
+
done: Set[str] = set()
|
| 221 |
+
if OH_ROWS.exists():
|
| 222 |
+
with open(OH_ROWS, encoding="utf-8") as f:
|
| 223 |
+
for line in f:
|
| 224 |
+
try:
|
| 225 |
+
done.add(json.loads(line)["source_url"])
|
| 226 |
+
except Exception:
|
| 227 |
+
continue
|
| 228 |
+
return done
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def load_oh_cursor() -> Dict[str, Any]:
|
| 232 |
+
if OH_CURSOR.exists():
|
| 233 |
+
try:
|
| 234 |
+
return json.loads(OH_CURSOR.read_text(encoding="utf-8"))
|
| 235 |
+
except Exception:
|
| 236 |
+
pass
|
| 237 |
+
return {"completed_agencies": [], "skip_until_agency": "/ohio-administrative-code/122"}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def save_oh_cursor(cur: Dict[str, Any]) -> None:
|
| 241 |
+
OH_CURSOR.parent.mkdir(parents=True, exist_ok=True)
|
| 242 |
+
tmp = OH_CURSOR.with_suffix(".tmp")
|
| 243 |
+
tmp.write_text(json.dumps(cur, indent=2) + "\n", encoding="utf-8")
|
| 244 |
+
tmp.replace(OH_CURSOR)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def append_oh_legacy_row(cit: str, title: str, text: str, url: str) -> Dict[str, Any]:
|
| 248 |
+
OH_ROWS.parent.mkdir(parents=True, exist_ok=True)
|
| 249 |
+
row = {
|
| 250 |
+
"state": "OH", "citation": cit, "title": title, "text": text, "source_url": url,
|
| 251 |
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
| 252 |
+
"sha256": hashlib.sha256(text.encode()).hexdigest(), "transport": "https",
|
| 253 |
+
}
|
| 254 |
+
with open(OH_ROWS, "a", encoding="utf-8") as f:
|
| 255 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 256 |
+
return row
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def resume_ohio(sess: PoliteSession, done: Set[str], seen_add: Callable[[str], bool], *, max_new: int = 25):
|
| 260 |
+
manifest: Dict[str, Any] = {"portal": OH_BASE + "/ohio-administrative-code", "status": "ok"}
|
| 261 |
+
out: List[Dict[str, Any]] = []
|
| 262 |
+
cur = load_oh_cursor()
|
| 263 |
+
completed: Set[str] = set(cur.get("completed_agencies") or [])
|
| 264 |
+
skip_until = cur.get("skip_until_agency")
|
| 265 |
+
r, flag = sess.get(OH_BASE + "/ohio-administrative-code")
|
| 266 |
+
if flag or not r:
|
| 267 |
+
manifest["status"] = flag or "fetch_failed"
|
| 268 |
+
return out, manifest
|
| 269 |
+
top = BeautifulSoup(r.text, "html.parser")
|
| 270 |
+
ags = sorted({
|
| 271 |
+
a["href"] for a in top.select("a[href]")
|
| 272 |
+
if re.fullmatch(r"/ohio-administrative-code/[0-9a-z:\-]+", a.get("href") or "")
|
| 273 |
+
and "chapter" not in a["href"] and "rule" not in a["href"]
|
| 274 |
+
})
|
| 275 |
+
started = not skip_until
|
| 276 |
+
for ag in ags:
|
| 277 |
+
if len(out) >= max_new:
|
| 278 |
+
break
|
| 279 |
+
if not started:
|
| 280 |
+
if ag < skip_until:
|
| 281 |
+
continue
|
| 282 |
+
started = True
|
| 283 |
+
cur["skip_until_agency"] = None
|
| 284 |
+
save_oh_cursor({**cur, "completed_agencies": sorted(completed)})
|
| 285 |
+
if ag in completed:
|
| 286 |
+
continue
|
| 287 |
+
r, flag = sess.get(OH_BASE + ag)
|
| 288 |
+
if flag == "blocked_waf" or not r:
|
| 289 |
+
if flag == "blocked_waf":
|
| 290 |
+
manifest["status"] = "blocked_waf"
|
| 291 |
+
break
|
| 292 |
+
continue
|
| 293 |
+
chs = list(dict.fromkeys(
|
| 294 |
+
a["href"] for a in BeautifulSoup(r.text, "html.parser").select(
|
| 295 |
+
'a[href^="/ohio-administrative-code/chapter-"]'
|
| 296 |
+
)
|
| 297 |
+
))
|
| 298 |
+
agency_new = 0
|
| 299 |
+
agency_seen = 0
|
| 300 |
+
all_done = True
|
| 301 |
+
for ch in chs:
|
| 302 |
+
if len(out) >= max_new:
|
| 303 |
+
break
|
| 304 |
+
r, flag = sess.get(OH_BASE + ch)
|
| 305 |
+
if flag == "blocked_waf" or not r:
|
| 306 |
+
if flag == "blocked_waf":
|
| 307 |
+
manifest["status"] = "blocked_waf"
|
| 308 |
+
return out, manifest
|
| 309 |
+
continue
|
| 310 |
+
rules = list(dict.fromkeys(
|
| 311 |
+
a["href"] for a in BeautifulSoup(r.text, "html.parser").select(
|
| 312 |
+
'a[href^="/ohio-administrative-code/rule-"]'
|
| 313 |
+
)
|
| 314 |
+
))
|
| 315 |
+
for ru in rules:
|
| 316 |
+
agency_seen += 1
|
| 317 |
+
u = OH_BASE + ru
|
| 318 |
+
if u in done:
|
| 319 |
+
continue
|
| 320 |
+
all_done = False
|
| 321 |
+
if len(out) >= max_new:
|
| 322 |
+
break
|
| 323 |
+
r, flag = sess.get(u)
|
| 324 |
+
if flag or not r:
|
| 325 |
+
if flag == "blocked_waf":
|
| 326 |
+
manifest["status"] = "blocked_waf"
|
| 327 |
+
return out, manifest
|
| 328 |
+
continue
|
| 329 |
+
b = BeautifulSoup(r.text, "html.parser")
|
| 330 |
+
h = b.select_one("section.laws-header h1")
|
| 331 |
+
body = b.select_one("section.laws-body")
|
| 332 |
+
if not h or not body:
|
| 333 |
+
continue
|
| 334 |
+
ht = h.get_text(" ", strip=True)
|
| 335 |
+
cit, _, title = ht.partition("|")
|
| 336 |
+
text = body.get_text("\n", strip=True)
|
| 337 |
+
legacy = append_oh_legacy_row(cit.strip(), title.strip(), text, u)
|
| 338 |
+
rec = from_oh_official_row(legacy)
|
| 339 |
+
if seen_add(rec["id"]):
|
| 340 |
+
out.append(rec)
|
| 341 |
+
done.add(u)
|
| 342 |
+
agency_new += 1
|
| 343 |
+
if agency_seen > 0 and all_done and agency_new == 0 and len(out) < max_new:
|
| 344 |
+
completed.add(ag)
|
| 345 |
+
save_oh_cursor({"completed_agencies": sorted(completed), "last_agency": ag})
|
| 346 |
+
elif agency_new > 0:
|
| 347 |
+
save_oh_cursor({"completed_agencies": sorted(completed), "last_agency": ag})
|
| 348 |
+
manifest["new"] = len(out)
|
| 349 |
+
return out, manifest
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def deep_collect_state(
|
| 353 |
+
sess: PoliteSession,
|
| 354 |
+
seed: Dict[str, Any],
|
| 355 |
+
seen_add: Callable[[str], bool],
|
| 356 |
+
*,
|
| 357 |
+
max_admin: int = 12,
|
| 358 |
+
max_eo: int = 8,
|
| 359 |
+
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], Dict[str, Any]]:
|
| 360 |
+
"""Return (admin_records, eo_records, manifest)."""
|
| 361 |
+
tid = seed["target_id"]
|
| 362 |
+
st = state_code_from_target(tid) or "XX"
|
| 363 |
+
hf_admin = seed.get("target_hf_repo") or "justicedao/ipfs_state_admin_rules"
|
| 364 |
+
hf_eo = "justicedao/ipfs_us_executive_orders"
|
| 365 |
+
admin_out: List[Dict[str, Any]] = []
|
| 366 |
+
eo_out: List[Dict[str, Any]] = []
|
| 367 |
+
man: Dict[str, Any] = {"target_id": tid, "state": st, "admin_status": None, "eo_status": None}
|
| 368 |
+
|
| 369 |
+
if st == "OH":
|
| 370 |
+
done = load_oh_done_urls()
|
| 371 |
+
recs, m = resume_ohio(sess, done, seen_add, max_new=max_admin)
|
| 372 |
+
admin_out.extend(recs)
|
| 373 |
+
man["admin_status"] = m
|
| 374 |
+
# also governor EO if present in seeds
|
| 375 |
+
else:
|
| 376 |
+
fr = load_frontier(tid)
|
| 377 |
+
visited = set(fr.get("visited") or [])
|
| 378 |
+
queue = list(fr.get("queue") or [])
|
| 379 |
+
|
| 380 |
+
# seed admin_code
|
| 381 |
+
admin_cands = preferred_fetch_urls(seed, "admin_code")
|
| 382 |
+
if admin_cands and not queue:
|
| 383 |
+
queue.extend([u for u, _ in admin_cands[:5]])
|
| 384 |
+
|
| 385 |
+
# ensure we fetch at least one admin seed page to expand frontier
|
| 386 |
+
if admin_cands:
|
| 387 |
+
r, final_url, arch, status = fetch_with_fallback(sess, admin_cands)
|
| 388 |
+
man["admin_status"] = status
|
| 389 |
+
man["admin_url"] = final_url
|
| 390 |
+
if r:
|
| 391 |
+
visited.add(final_url)
|
| 392 |
+
links = extract_links(final_url, r.text, "admin")
|
| 393 |
+
for L in links[:80]:
|
| 394 |
+
if L not in visited and L not in queue:
|
| 395 |
+
queue.append(L)
|
| 396 |
+
# if seed page itself is substantive, keep it
|
| 397 |
+
title = BeautifulSoup(r.text, "html.parser").title
|
| 398 |
+
title_s = title.get_text(" ", strip=True) if title else f"{st} admin"
|
| 399 |
+
text = BeautifulSoup(r.text, "html.parser").get_text("\n", strip=True)
|
| 400 |
+
if is_substantive(text, title_s):
|
| 401 |
+
rec = make_doc_record(
|
| 402 |
+
gap_target_id=tid, state=st, title=title_s, text=text,
|
| 403 |
+
source_url=final_url, document_type="admin_rule",
|
| 404 |
+
archive_source=arch, target_hf_repo=hf_admin,
|
| 405 |
+
)
|
| 406 |
+
if seen_add(rec["id"]):
|
| 407 |
+
admin_out.append(rec)
|
| 408 |
+
|
| 409 |
+
# crawl frontier for admin docs
|
| 410 |
+
while queue and len(admin_out) < max_admin:
|
| 411 |
+
url = queue.pop(0)
|
| 412 |
+
if url in visited:
|
| 413 |
+
continue
|
| 414 |
+
visited.add(url)
|
| 415 |
+
r, flag = sess.get(url)
|
| 416 |
+
arch = "wayback" if "web.archive.org" in url else None
|
| 417 |
+
if flag or not r:
|
| 418 |
+
if flag == "blocked_waf":
|
| 419 |
+
live, _ = unwrap_wayback(url)
|
| 420 |
+
wu, wr = wayback_closest(sess, live)
|
| 421 |
+
if wr:
|
| 422 |
+
r, url, arch, flag = wr, wu or url, "wayback", None
|
| 423 |
+
else:
|
| 424 |
+
continue
|
| 425 |
+
else:
|
| 426 |
+
continue
|
| 427 |
+
soup = BeautifulSoup(r.text, "html.parser")
|
| 428 |
+
title = soup.title.get_text(" ", strip=True) if soup.title else url
|
| 429 |
+
# prefer PDF binary skip — only text/html
|
| 430 |
+
ctype = (r.headers.get("content-type") or "").lower()
|
| 431 |
+
if "pdf" in ctype:
|
| 432 |
+
# store short PDF meta stub only if substantive headers
|
| 433 |
+
text = f"[PDF content-type] bytes={len(r.content)} url={url}"
|
| 434 |
+
if len(r.content) > 5000:
|
| 435 |
+
rec = make_doc_record(
|
| 436 |
+
gap_target_id=tid, state=st, title=title or Path(urlparse(url).path).name,
|
| 437 |
+
text=text, source_url=url, document_type="admin_rule_pdf_meta",
|
| 438 |
+
archive_source=arch, target_hf_repo=hf_admin,
|
| 439 |
+
)
|
| 440 |
+
if seen_add(rec["id"]):
|
| 441 |
+
admin_out.append(rec)
|
| 442 |
+
continue
|
| 443 |
+
text = soup.get_text("\n", strip=True)
|
| 444 |
+
if is_substantive(text, title):
|
| 445 |
+
rec = make_doc_record(
|
| 446 |
+
gap_target_id=tid, state=st, title=title, text=text,
|
| 447 |
+
source_url=url, document_type="admin_rule",
|
| 448 |
+
archive_source=arch, target_hf_repo=hf_admin,
|
| 449 |
+
)
|
| 450 |
+
if seen_add(rec["id"]):
|
| 451 |
+
admin_out.append(rec)
|
| 452 |
+
# expand a bit
|
| 453 |
+
if len(visited) < 120:
|
| 454 |
+
for L in extract_links(url, r.text, "admin")[:20]:
|
| 455 |
+
if L not in visited and L not in queue:
|
| 456 |
+
queue.append(L)
|
| 457 |
+
|
| 458 |
+
fr["queue"] = queue
|
| 459 |
+
fr["visited"] = list(visited)
|
| 460 |
+
save_frontier(tid, fr)
|
| 461 |
+
|
| 462 |
+
# Governor EO role
|
| 463 |
+
eo_cands = preferred_fetch_urls(seed, "governor_eo")
|
| 464 |
+
if eo_cands:
|
| 465 |
+
r, final_url, arch, status = fetch_with_fallback(sess, eo_cands)
|
| 466 |
+
man["eo_status"] = status
|
| 467 |
+
man["eo_url"] = final_url
|
| 468 |
+
if r:
|
| 469 |
+
links = extract_links(final_url, r.text, "eo")
|
| 470 |
+
# include landing if substantive
|
| 471 |
+
soup = BeautifulSoup(r.text, "html.parser")
|
| 472 |
+
title = soup.title.get_text(" ", strip=True) if soup.title else f"{st} Governor EOs"
|
| 473 |
+
text = soup.get_text("\n", strip=True)
|
| 474 |
+
candidates = [(final_url, r, arch, title)]
|
| 475 |
+
for L in links[: max_eo * 3]:
|
| 476 |
+
if len(candidates) >= max_eo + 1:
|
| 477 |
+
break
|
| 478 |
+
r2, f2 = sess.get(L)
|
| 479 |
+
a2 = "wayback" if "web.archive.org" in L else None
|
| 480 |
+
if f2 or not r2:
|
| 481 |
+
continue
|
| 482 |
+
s2 = BeautifulSoup(r2.text, "html.parser")
|
| 483 |
+
t2 = s2.title.get_text(" ", strip=True) if s2.title else L
|
| 484 |
+
candidates.append((L, r2, a2, t2))
|
| 485 |
+
for url, resp, a, title in candidates:
|
| 486 |
+
if len(eo_out) >= max_eo:
|
| 487 |
+
break
|
| 488 |
+
ctype = (resp.headers.get("content-type") or "").lower()
|
| 489 |
+
if "pdf" in ctype:
|
| 490 |
+
text = f"[PDF] bytes={len(resp.content)} url={url}"
|
| 491 |
+
if len(resp.content) < 3000:
|
| 492 |
+
continue
|
| 493 |
+
else:
|
| 494 |
+
text = BeautifulSoup(resp.text, "html.parser").get_text("\n", strip=True)
|
| 495 |
+
if not is_substantive(text, title) and "pdf" not in ctype:
|
| 496 |
+
continue
|
| 497 |
+
rec = make_doc_record(
|
| 498 |
+
gap_target_id=tid, state=st, title=title, text=text,
|
| 499 |
+
source_url=url, document_type="governor_eo",
|
| 500 |
+
archive_source=a, target_hf_repo=hf_eo,
|
| 501 |
+
)
|
| 502 |
+
if seen_add(rec["id"]):
|
| 503 |
+
eo_out.append(rec)
|
| 504 |
+
|
| 505 |
+
man["admin_written"] = len(admin_out)
|
| 506 |
+
man["eo_written"] = len(eo_out)
|
| 507 |
+
return admin_out, eo_out, man
|
scrapers_and_normalizers/wave3c_20261106/unified_daemon.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Seed-driven US Admin Rules & EO daemon with pause/hibernate memguard.
|
| 3 |
+
|
| 4 |
+
Queue: /workspace/coverage/world_admin_eo_seeds_20261105.jsonl (US ARE-US-* rows).
|
| 5 |
+
MemAvailable < 4.2 GiB -> flush, gc, status=paused_low_mem, sleep until >= 4.35 GiB.
|
| 6 |
+
Disk < 10 GiB -> exit. RSS > 500 MiB -> flush + os.execv self.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import gc
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import socket
|
| 14 |
+
import signal
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
import traceback
|
| 18 |
+
from datetime import datetime, timezone
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
socket.setdefaulttimeout(25)
|
| 22 |
+
|
| 23 |
+
BUNDLE = Path(__file__).resolve().parent
|
| 24 |
+
sys.path.insert(0, str(BUNDLE))
|
| 25 |
+
IPFS = Path("/workspace/ipfs_datasets_py_latest")
|
| 26 |
+
if IPFS.exists():
|
| 27 |
+
sys.path.insert(0, str(IPFS))
|
| 28 |
+
|
| 29 |
+
from io_zst import (
|
| 30 |
+
JsonlZstWriter, MemGuard, SeenIds, load_ids_from_zst, load_json, write_json,
|
| 31 |
+
mem_available_bytes, disk_free_bytes, process_rss_bytes,
|
| 32 |
+
)
|
| 33 |
+
from seeds import load_us_seeds, state_code_from_target
|
| 34 |
+
from federal_collector import (
|
| 35 |
+
PoliteSession as FedSession, ecfr_as_of, collect_ecfr_title_parts, collect_eo, collect_fr_after,
|
| 36 |
+
)
|
| 37 |
+
from state_admin_collector import PoliteSession as StateSession, deep_collect_state
|
| 38 |
+
from municipal_collector import PoliteSession as MuniSession, collect_municipal
|
| 39 |
+
|
| 40 |
+
FED_ROOT = Path("/workspace/legal-corpora/us_federal_admin_eo_20261105")
|
| 41 |
+
STATE_ROOT = Path("/workspace/legal-corpora/us_state_admin_rules_20261104")
|
| 42 |
+
EO_ROOT = Path("/workspace/legal-corpora/us_executive_orders_20261105")
|
| 43 |
+
STATE_SHARDS = STATE_ROOT / "shards"
|
| 44 |
+
COLLECTOR = STATE_ROOT / "_collector"
|
| 45 |
+
STATUS_STATE = COLLECTOR / "status.json"
|
| 46 |
+
STATUS_FED = FED_ROOT / "status.json"
|
| 47 |
+
STATUS_EO = EO_ROOT / "status.json"
|
| 48 |
+
CKPT = COLLECTOR / "checkpoint_gap.json"
|
| 49 |
+
SEEN_PATH = COLLECTOR / "seen_ids.json"
|
| 50 |
+
LOG = Path("/workspace/logs/us_admin_eo_gap_daemon_20261105.log")
|
| 51 |
+
SEEDS_PATH = "/workspace/coverage/world_admin_eo_seeds_20261105.jsonl"
|
| 52 |
+
|
| 53 |
+
STOP = False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def log(msg: str) -> None:
|
| 57 |
+
LOG.parent.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
line = f"{datetime.now().isoformat(timespec='seconds')} {msg}"
|
| 59 |
+
with open(LOG, "a", encoding="utf-8") as f:
|
| 60 |
+
f.write(line + "\n")
|
| 61 |
+
print(line, flush=True)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _sig(signum, frame):
|
| 65 |
+
global STOP
|
| 66 |
+
STOP = True
|
| 67 |
+
log(f"SIGNAL {signum} -> graceful stop")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
signal.signal(signal.SIGTERM, _sig)
|
| 71 |
+
signal.signal(signal.SIGINT, _sig)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def dual_status(**kwargs):
|
| 75 |
+
payload = dict(kwargs)
|
| 76 |
+
payload.update({
|
| 77 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 78 |
+
"pid": os.getpid(),
|
| 79 |
+
"mem_available_bytes": mem_available_bytes(),
|
| 80 |
+
"disk_free_bytes": disk_free_bytes(),
|
| 81 |
+
"rss_bytes": process_rss_bytes(),
|
| 82 |
+
"mem_floor_bytes": MemGuard.MEM_FLOOR,
|
| 83 |
+
"mem_resume_bytes": MemGuard.MEM_RESUME,
|
| 84 |
+
"disk_floor_bytes": MemGuard.DISK_FLOOR,
|
| 85 |
+
"rss_reexec_bytes": MemGuard.RSS_REEXEC,
|
| 86 |
+
"seeds": SEEDS_PATH,
|
| 87 |
+
"log": str(LOG),
|
| 88 |
+
"seen_ids_path": str(SEEN_PATH),
|
| 89 |
+
})
|
| 90 |
+
for path in (STATUS_STATE, STATUS_FED, STATUS_EO):
|
| 91 |
+
prev = load_json(path, default={}) or {}
|
| 92 |
+
prev.update(payload)
|
| 93 |
+
write_json(path, prev)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def shard_path(root: Path, prefix: str) -> Path:
|
| 97 |
+
(root / "shards").mkdir(parents=True, exist_ok=True)
|
| 98 |
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 99 |
+
return root / "shards" / f"{prefix}_{ts}.jsonl.zst"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def write_batch(path: Path, records: list, seen: SeenIds) -> int:
|
| 103 |
+
if not records:
|
| 104 |
+
return 0
|
| 105 |
+
with JsonlZstWriter(path) as w:
|
| 106 |
+
for rec in records:
|
| 107 |
+
w.write(rec)
|
| 108 |
+
w.flush()
|
| 109 |
+
seen.flush()
|
| 110 |
+
return len(records)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def seed_seen(seen: SeenIds) -> int:
|
| 114 |
+
n = 0
|
| 115 |
+
for root in [FED_ROOT / "shards", STATE_SHARDS, STATE_ROOT / "OH.official" / "shards", EO_ROOT / "shards"]:
|
| 116 |
+
if not root.exists():
|
| 117 |
+
continue
|
| 118 |
+
for p in root.glob("*.jsonl.zst"):
|
| 119 |
+
n += load_ids_from_zst(p, seen)
|
| 120 |
+
for p in root.glob("**/*.jsonl.zst"):
|
| 121 |
+
n += load_ids_from_zst(p, seen)
|
| 122 |
+
# also per-state .gap
|
| 123 |
+
for p in STATE_ROOT.glob("*.gap/shards/*.jsonl.zst"):
|
| 124 |
+
n += load_ids_from_zst(p, seen)
|
| 125 |
+
seen.flush()
|
| 126 |
+
return n
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def handle_guard(action: str, guard: MemGuard, seen: SeenIds, ckpt: dict) -> bool:
|
| 130 |
+
"""Return False if caller should exit; True to continue (possibly after pause/reexec)."""
|
| 131 |
+
if action == "ok":
|
| 132 |
+
return True
|
| 133 |
+
seen.flush()
|
| 134 |
+
write_json(CKPT, ckpt)
|
| 135 |
+
gc.collect()
|
| 136 |
+
if action == "exit_disk":
|
| 137 |
+
dual_status(state="exited", stop_reason=guard.stop_reason, totals=ckpt.get("totals"))
|
| 138 |
+
log(f"EXIT_DISK {guard.stop_reason}")
|
| 139 |
+
return False
|
| 140 |
+
if action == "reexec":
|
| 141 |
+
dual_status(state="reexec_rss", stop_reason=guard.stop_reason, totals=ckpt.get("totals"))
|
| 142 |
+
log(f"REEXEC {guard.stop_reason}")
|
| 143 |
+
os.execv(sys.executable, [sys.executable, "-u", str(Path(__file__).resolve())] + sys.argv[1:])
|
| 144 |
+
return False # unreachable
|
| 145 |
+
if action == "pause":
|
| 146 |
+
dual_status(state="paused_low_mem", stop_reason=guard.stop_reason, totals=ckpt.get("totals"),
|
| 147 |
+
queue_index=ckpt.get("queue_index"), ecfr_title_index=ckpt.get("ecfr_title_index"),
|
| 148 |
+
current_target="(paused)")
|
| 149 |
+
log(f"PAUSE {guard.stop_reason}")
|
| 150 |
+
ok = MemGuard.wait_until_resume(
|
| 151 |
+
log_fn=log,
|
| 152 |
+
status_fn=lambda **kw: dual_status(totals=ckpt.get("totals"),
|
| 153 |
+
queue_index=ckpt.get("queue_index"),
|
| 154 |
+
ecfr_title_index=ckpt.get("ecfr_title_index"),
|
| 155 |
+
current_target="(paused)", **kw),
|
| 156 |
+
stop_flag=lambda: STOP,
|
| 157 |
+
)
|
| 158 |
+
if not ok:
|
| 159 |
+
dual_status(state="exited", stop_reason="stop_during_pause_or_disk", totals=ckpt.get("totals"))
|
| 160 |
+
return False
|
| 161 |
+
dual_status(state="running", stop_reason=None, totals=ckpt.get("totals"))
|
| 162 |
+
return True
|
| 163 |
+
return True
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def main() -> int:
|
| 167 |
+
for d in [FED_ROOT / "shards", STATE_SHARDS, EO_ROOT / "shards", COLLECTOR,
|
| 168 |
+
STATE_ROOT / "OH.official" / "shards"]:
|
| 169 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
|
| 171 |
+
guard = MemGuard()
|
| 172 |
+
seen = SeenIds(SEEN_PATH)
|
| 173 |
+
seeded = seed_seen(seen)
|
| 174 |
+
log(f"START pid={os.getpid()} seeded_seen={seeded} total_seen={len(seen.ids)} mem={mem_available_bytes()}")
|
| 175 |
+
|
| 176 |
+
# Immediate pause if already below floor
|
| 177 |
+
action = guard.evaluate()
|
| 178 |
+
ckpt = load_json(CKPT, default={}) or {}
|
| 179 |
+
if action != "ok":
|
| 180 |
+
if not handle_guard(action, guard, seen, ckpt):
|
| 181 |
+
return 0
|
| 182 |
+
|
| 183 |
+
queue = load_us_seeds()
|
| 184 |
+
queue_index = int(ckpt.get("queue_index") or 0)
|
| 185 |
+
ecfr_title_index = int(ckpt.get("ecfr_title_index") or 0)
|
| 186 |
+
totals = ckpt.get("totals") or {"written": 0, "skipped_dup": 0, "by_target": {}}
|
| 187 |
+
|
| 188 |
+
def seen_add(rid: str) -> bool:
|
| 189 |
+
ok = seen.add(rid)
|
| 190 |
+
if not ok:
|
| 191 |
+
totals["skipped_dup"] = totals.get("skipped_dup", 0) + 1
|
| 192 |
+
return ok
|
| 193 |
+
|
| 194 |
+
fed = FedSession(delay=0.7)
|
| 195 |
+
state = StateSession(delay=0.9)
|
| 196 |
+
muni = MuniSession(delay=1.0)
|
| 197 |
+
|
| 198 |
+
dual_status(state="starting", stream="seeds_us", queue_len=len(queue), queue_index=queue_index, totals=totals)
|
| 199 |
+
date, titles = ecfr_as_of(fed)
|
| 200 |
+
title_nums = [int(t["number"]) for t in titles if not t.get("reserved")] or list(range(1, 51))
|
| 201 |
+
log(f"seeds={len(queue)} eCFR as_of={date} titles={len(title_nums)}")
|
| 202 |
+
|
| 203 |
+
while not STOP:
|
| 204 |
+
action = guard.tick()
|
| 205 |
+
ckpt = {
|
| 206 |
+
"queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
|
| 207 |
+
"totals": totals, "saved_at": datetime.now(timezone.utc).isoformat(),
|
| 208 |
+
}
|
| 209 |
+
if not handle_guard(action, guard, seen, ckpt):
|
| 210 |
+
return 0
|
| 211 |
+
|
| 212 |
+
if queue_index >= len(queue):
|
| 213 |
+
# wrap: continue ECFR titles if needed else restart from FR/EO/state deepen
|
| 214 |
+
if ecfr_title_index < len(title_nums):
|
| 215 |
+
queue_index = 0
|
| 216 |
+
log(f"WRAP to ECFR title_index={ecfr_title_index}")
|
| 217 |
+
else:
|
| 218 |
+
queue_index = 0
|
| 219 |
+
log("FULL WRAP deepen cycle")
|
| 220 |
+
|
| 221 |
+
seed = queue[queue_index]
|
| 222 |
+
tid = seed["target_id"]
|
| 223 |
+
lane = seed.get("lane")
|
| 224 |
+
hf = seed.get("target_hf_repo")
|
| 225 |
+
dual_status(state="running", current_target=tid, queue_index=queue_index, lane=lane,
|
| 226 |
+
target_hf_repo=hf, totals=totals, ecfr_title_index=ecfr_title_index)
|
| 227 |
+
log(f"TARGET {queue_index+1}/{len(queue)} {tid} lane={lane} hf={hf}")
|
| 228 |
+
|
| 229 |
+
try:
|
| 230 |
+
if tid == "ARE-US-ECFR":
|
| 231 |
+
wrote_any = 0
|
| 232 |
+
for _ in range(2):
|
| 233 |
+
if ecfr_title_index >= len(title_nums) or STOP:
|
| 234 |
+
break
|
| 235 |
+
action = guard.tick()
|
| 236 |
+
if action != "ok":
|
| 237 |
+
ckpt = {"queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
|
| 238 |
+
"totals": totals, "saved_at": datetime.now(timezone.utc).isoformat()}
|
| 239 |
+
if not handle_guard(action, guard, seen, ckpt):
|
| 240 |
+
return 0
|
| 241 |
+
break
|
| 242 |
+
tnum = title_nums[ecfr_title_index]
|
| 243 |
+
recs = collect_ecfr_title_parts(
|
| 244 |
+
fed, tnum, date, seen_add=seen_add, max_parts=10, max_records=60,
|
| 245 |
+
should_continue=lambda: (not STOP) and guard.evaluate() == "ok",
|
| 246 |
+
)
|
| 247 |
+
if recs:
|
| 248 |
+
path = shard_path(FED_ROOT, f"ARE-US-ECFR_title{tnum}")
|
| 249 |
+
n = write_batch(path, recs, seen)
|
| 250 |
+
wrote_any += n
|
| 251 |
+
totals["written"] = totals.get("written", 0) + n
|
| 252 |
+
totals.setdefault("by_target", {})
|
| 253 |
+
totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
|
| 254 |
+
log(f"ECFR title {tnum} wrote {n}")
|
| 255 |
+
ecfr_title_index += 1
|
| 256 |
+
queue_index += 1
|
| 257 |
+
|
| 258 |
+
elif tid == "ARE-US-EO":
|
| 259 |
+
recs = collect_eo(fed, seen_add, max_docs=25)
|
| 260 |
+
path = shard_path(EO_ROOT, "ARE-US-EO")
|
| 261 |
+
# also keep federal staging copy for continuity
|
| 262 |
+
n = write_batch(path, recs, seen)
|
| 263 |
+
if recs:
|
| 264 |
+
write_batch(shard_path(FED_ROOT, "ARE-US-EO"), recs, seen)
|
| 265 |
+
totals["written"] = totals.get("written", 0) + n
|
| 266 |
+
totals.setdefault("by_target", {})
|
| 267 |
+
totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
|
| 268 |
+
log(f"EO wrote {n}")
|
| 269 |
+
queue_index += 1
|
| 270 |
+
|
| 271 |
+
elif tid == "ARE-US-FR":
|
| 272 |
+
recs = collect_fr_after(fed, seen_add, gte="2026-07-01", max_docs=30)
|
| 273 |
+
path = shard_path(FED_ROOT, "ARE-US-FR")
|
| 274 |
+
n = write_batch(path, recs, seen)
|
| 275 |
+
totals["written"] = totals.get("written", 0) + n
|
| 276 |
+
totals.setdefault("by_target", {})
|
| 277 |
+
totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
|
| 278 |
+
log(f"FR wrote {n}")
|
| 279 |
+
queue_index += 1
|
| 280 |
+
|
| 281 |
+
elif tid == "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO":
|
| 282 |
+
recs, man = collect_municipal(muni, seen_add, max_records=20)
|
| 283 |
+
path = shard_path(EO_ROOT, "ARE-US-COUNTY-MUNICIPAL")
|
| 284 |
+
n = write_batch(path, recs, seen)
|
| 285 |
+
write_json(COLLECTOR / "municipal_manifest.json", man)
|
| 286 |
+
totals["written"] = totals.get("written", 0) + n
|
| 287 |
+
totals.setdefault("by_target", {})
|
| 288 |
+
totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
|
| 289 |
+
log(f"MUNICIPAL wrote {n}")
|
| 290 |
+
queue_index += 1
|
| 291 |
+
|
| 292 |
+
elif tid.endswith("-ADMIN-EO"):
|
| 293 |
+
admin_recs, eo_recs, man = deep_collect_state(
|
| 294 |
+
state, seed, seen_add, max_admin=12, max_eo=8,
|
| 295 |
+
)
|
| 296 |
+
st = state_code_from_target(tid) or "XX"
|
| 297 |
+
n_admin = n_eo = 0
|
| 298 |
+
if admin_recs:
|
| 299 |
+
# per-state + aggregate state shards
|
| 300 |
+
out_dir = STATE_ROOT / f"{st}.gap" / "shards"
|
| 301 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 302 |
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 303 |
+
p1 = out_dir / f"{tid}_{ts}.jsonl.zst"
|
| 304 |
+
n_admin = write_batch(p1, admin_recs, seen)
|
| 305 |
+
write_batch(STATE_SHARDS / f"{tid}_{ts}.jsonl.zst", admin_recs, seen)
|
| 306 |
+
if eo_recs:
|
| 307 |
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 308 |
+
n_eo = write_batch(shard_path(EO_ROOT, f"{tid}_gov_eo"), eo_recs, seen)
|
| 309 |
+
with open(COLLECTOR / "portal_manifest.jsonl", "a", encoding="utf-8") as mf:
|
| 310 |
+
mf.write(json.dumps(man) + "\n")
|
| 311 |
+
n = n_admin + n_eo
|
| 312 |
+
totals["written"] = totals.get("written", 0) + n
|
| 313 |
+
totals.setdefault("by_target", {})
|
| 314 |
+
totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
|
| 315 |
+
log(f"{tid} wrote admin={n_admin} eo={n_eo} status={man.get('admin_status')}/{man.get('eo_status')}")
|
| 316 |
+
queue_index += 1
|
| 317 |
+
else:
|
| 318 |
+
log(f"SKIP {tid}")
|
| 319 |
+
queue_index += 1
|
| 320 |
+
|
| 321 |
+
except Exception as e:
|
| 322 |
+
log(f"ERR {tid} {e!r}\n{traceback.format_exc()}")
|
| 323 |
+
queue_index += 1
|
| 324 |
+
|
| 325 |
+
ckpt = {
|
| 326 |
+
"queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
|
| 327 |
+
"totals": totals, "saved_at": datetime.now(timezone.utc).isoformat(),
|
| 328 |
+
}
|
| 329 |
+
write_json(CKPT, ckpt)
|
| 330 |
+
seen.flush()
|
| 331 |
+
dual_status(state="running", queue_index=queue_index, ecfr_title_index=ecfr_title_index,
|
| 332 |
+
totals=totals, current_target=tid)
|
| 333 |
+
gc.collect()
|
| 334 |
+
|
| 335 |
+
seen.flush()
|
| 336 |
+
dual_status(state="exited", totals=totals, queue_index=queue_index, stop_reason="signal")
|
| 337 |
+
log(f"EXIT signal totals={totals}")
|
| 338 |
+
return 0
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
try:
|
| 343 |
+
sys.exit(main() or 0)
|
| 344 |
+
except Exception as e:
|
| 345 |
+
log(f"FATAL {e!r}\n{traceback.format_exc()}")
|
| 346 |
+
try:
|
| 347 |
+
dual_status(state="fatal", error=repr(e))
|
| 348 |
+
except Exception:
|
| 349 |
+
pass
|
| 350 |
+
sys.exit(1)
|