endomorphosis commited on
Commit
ee26bc9
·
verified ·
1 Parent(s): 0dcb748

Singapore current Acts: 701 laws (SSO Wayback of official URLs; CloudFront 403)

Browse files
README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Singapore Current Acts (SSO AGC)
3
+ license: other
4
+ license_name: sg-sso-unofficial-reproduction
5
+ language:
6
+ - en
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - singapore
13
+ - sso
14
+ - agc
15
+ - official-texts
16
+ size_categories:
17
+ - 1K<n<10K
18
+ configs:
19
+ - config_name: laws
20
+ data_files: data/laws.parquet
21
+ default: true
22
+ - config_name: articles
23
+ data_files: data/articles.parquet
24
+ ---
25
+
26
+ # Singapore Current Acts (SSO AGC)
27
+
28
+ Research snapshot of **national legislation** from official sources listed below.
29
+
30
+ **Not legal advice.** The official gazette / authentic text of the jurisdiction
31
+ prevails over this corpus.
32
+
33
+ ## Snapshot
34
+
35
+ | Field | Value |
36
+ | --- | --- |
37
+ | Snapshot date | 2026-09-02 |
38
+ | Source | Singapore Statutes Online (AGC Legislation Division) |
39
+ | Collector | `scrapers/collect_sso_agc.py` |
40
+ | Laws / instruments | 701 |
41
+ | Articles | 5,029 |
42
+ | Language | en |
43
+ | License | `sg-sso-unofficial-reproduction` |
44
+
45
+ ## Contents
46
+
47
+ - `data/laws.parquet` — one row per instrument (zstd).
48
+ - `data/articles.parquet` — article/section rows for the same snapshot.
49
+ - `scrapers/collect_sso_agc.py` — research collector used to build this snapshot.
50
+
51
+ ## License / reuse
52
+
53
+ SSO is an unofficial reproduction; printed Gazette / AGC official text prevails. Not legal advice.
54
+
55
+ This dataset is **not legal advice**. The official gazette prevails.
56
+
57
+ ## Source
58
+
59
+ - https://sso.agc.gov.sg/
60
+ - https://sso.agc.gov.sg/Browse/Act/Current
61
+ - https://sso.agc.gov.sg/Act/CoA1967
62
+
63
+ ## Known gaps
64
+
65
+ - Current Acts from SSO. Subsidiary legislation not included.
66
+ - robots.txt Disallow:/search honoured — no search endpoint used.
67
+ - Live CloudFront blocked the collector UA (403); Wayback CDX of official sso.agc.gov.sg/Act/ URLs used (0 live / all archive).
68
+ - SSO HTML is unofficial; printed Gazette / AGC authentic text prevails.
69
+ - Catalog 704 CDX URLs vs live browse listing ~524; extras include older/repealed codes still at /Act/{code} and a few malformed keys.
70
+ - 3 failed after retries: AFVAA2000, BSMA2004, PWA202480.
71
+ - Many HTML snapshots only expose a subset of provisions (SSO lazy-loads); article rows under-count vs the full Act. The law text field is the captured page.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4966b184ea7668cc92caedfe2ec226298f349c56bb570a6c1b5db745fd8d54a7
3
+ size 1592419
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8d63fc8cfb4c2ef0c1544caa3de47a51f13ab113bb4bbd34926100bcd6eb7ff
3
+ size 1362023
scrapers/collect_sso_agc.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Singapore: current Acts from Singapore Statutes Online (AGC Legislation Division).
3
+
4
+ Official only:
5
+ https://sso.agc.gov.sg/
6
+ Browse: https://sso.agc.gov.sg/Browse/Act/Current
7
+ Act pages: https://sso.agc.gov.sg/Act/{code} e.g. /Act/CoA1967
8
+ PDF: https://sso.agc.gov.sg/Act/{code}?ViewType=Pdf
9
+
10
+ robots.txt: Disallow: /search ; crawl-delay: 6
11
+ This collector never hits /search. No Cloudflare browser rendering.
12
+ No WAF bypass (DEFAULT_UA only). Live CloudFront often 403s this UA.
13
+
14
+ Fallback: Wayback CDX of official sso.agc.gov.sg URLs only (letter prefixes
15
+ of /Act/{A-Z} with Historical/Act-Rev/query filters, plus exact Act and
16
+ ViewType=Pdf captures). Prefer official PDF snapshots, else HTML.
17
+ SSO is an unofficial reproduction; printed Gazette / AGC official text prevails.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ import re
24
+ import subprocess
25
+ import sys
26
+ import tempfile
27
+ import threading
28
+ import time
29
+ from concurrent.futures import ThreadPoolExecutor, as_completed
30
+ from pathlib import Path
31
+ from typing import Optional
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+ from common import *
35
+ import archive_fallbacks as af
36
+
37
+ CC = "sg"
38
+ COUNTRY = "Singapore"
39
+ SOURCE_TYPE = "sso_agc_html"
40
+ LICENSE = (
41
+ "Singapore Statutes Online (sso.agc.gov.sg) is an unofficial reproduction "
42
+ "published by the Legislation Division of the Attorney-General's Chambers. "
43
+ "The printed Gazette and AGC official text prevail. Research snapshot with "
44
+ "provenance. Not legal advice."
45
+ )
46
+ UA = DEFAULT_UA + " source=https://sso.agc.gov.sg/"
47
+ PORTAL = "https://sso.agc.gov.sg/"
48
+ BROWSE = "https://sso.agc.gov.sg/Browse/Act/Current"
49
+ ACT_RE = re.compile(
50
+ r"^https://sso\.agc\.gov\.sg/Act/([A-Za-z][A-Za-z0-9]{1,60}\d{4})$"
51
+ )
52
+ ACT_FROM_PATH = re.compile(
53
+ r"https?://sso\.agc\.gov\.sg/Act/([A-Za-z][A-Za-z0-9]{1,60}\d{4})(?:/|$|\?)",
54
+ re.I,
55
+ )
56
+ SG_SEC = re.compile(r"(?m)^(\d+[A-Za-z]{0,2})\.(?:—|\s+(?=[A-Z“\"'‘]))")
57
+ WORKERS = 2
58
+ SLEEP = 6.0
59
+ EXPECTED_ACTS = 524
60
+ log = logging.getLogger("sg")
61
+ _live_blocked = threading.Event()
62
+
63
+
64
+ def setup():
65
+ ensure_dirs(CC)
66
+ logging.basicConfig(
67
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
68
+ handlers=[
69
+ logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
70
+ logging.StreamHandler(sys.stdout),
71
+ ],
72
+ )
73
+
74
+
75
+ def normalize_act_url(url: str) -> Optional[str]:
76
+ if not url:
77
+ return None
78
+ raw = (url or "").split("?")[0].split("#")[0].rstrip("/")
79
+ raw = raw.replace("http://", "https://")
80
+ if "/Historical" in raw or "/Act-Rev" in raw or "/act-rev" in raw:
81
+ return None
82
+ if "/Repealed" in raw or "/Uncommenced" in raw:
83
+ return None
84
+ m = ACT_FROM_PATH.search(raw + "/")
85
+ if not m:
86
+ return None
87
+ return f"https://sso.agc.gov.sg/Act/{m.group(1)}"
88
+
89
+
90
+ def act_code_from_url(url: str) -> Optional[str]:
91
+ nu = normalize_act_url(url)
92
+ if not nu:
93
+ return None
94
+ m = ACT_RE.match(nu)
95
+ return m.group(1) if m else None
96
+
97
+
98
+ def live_get(url: str) -> Optional[str]:
99
+ if _live_blocked.is_set():
100
+ return None
101
+ try:
102
+ r = http_get(url, ua=UA, sleep=SLEEP, timeout=(20, 90), retries=1,
103
+ headers={"Accept": "text/html, */*"})
104
+ except Exception as exc:
105
+ log.info("live fail %s: %s", url, exc)
106
+ return None
107
+ if r.status_code in (403, 429) or af.is_challenge(r.text or "", r.status_code):
108
+ _live_blocked.set()
109
+ log.info("live blocked HTTP %s %s — skip further live fetches", r.status_code, url)
110
+ return None
111
+ if r.status_code != 200 or not r.text:
112
+ log.info("live HTTP %s %s", r.status_code, url)
113
+ return None
114
+ return r.text
115
+
116
+
117
+ def parse_act_links(html: str) -> list[str]:
118
+ urls = []
119
+ seen = set()
120
+ for href in re.findall(r'href=["\']([^"\']+)["\']', html or ""):
121
+ href = href.replace("&amp;", "&")
122
+ if href.startswith("/Act/"):
123
+ href = "https://sso.agc.gov.sg" + href
124
+ nu = normalize_act_url(href)
125
+ if nu and nu not in seen:
126
+ seen.add(nu)
127
+ urls.append(nu)
128
+ for code in re.findall(r"/Act/([A-Za-z][A-Za-z0-9]{1,60}\d{4})", html or ""):
129
+ nu = f"https://sso.agc.gov.sg/Act/{code}"
130
+ if nu not in seen:
131
+ seen.add(nu)
132
+ urls.append(nu)
133
+ return urls
134
+
135
+
136
+ def slim_cc_record(rec: dict) -> Optional[dict]:
137
+ fn = rec.get("filename") or rec.get("warc_filename")
138
+ if not fn:
139
+ return None
140
+ return {
141
+ "filename": fn,
142
+ "offset": rec.get("offset") or rec.get("warc_offset"),
143
+ "length": rec.get("length") or rec.get("warc_length"),
144
+ "timestamp": rec.get("timestamp"),
145
+ "url": rec.get("url") or rec.get("original"),
146
+ "original": rec.get("original") or rec.get("url"),
147
+ }
148
+
149
+
150
+ def add_item(items: list[dict], seen: dict, url: str, extra: dict) -> bool:
151
+ nu = normalize_act_url(url)
152
+ code = act_code_from_url(nu or "")
153
+ if not nu or not code:
154
+ return False
155
+ prev = seen.get(nu)
156
+ if prev is None:
157
+ row = {"code": code, "url": nu, **extra}
158
+ items.append(row)
159
+ seen[nu] = row
160
+ append_catalog(CC, {k: v for k, v in row.items() if k != "cc_record"})
161
+ return True
162
+ for k in ("cdx_ts", "pdf_ts", "pdf_url", "wayback_url", "cc_record"):
163
+ if extra.get(k) and not prev.get(k):
164
+ prev[k] = extra[k]
165
+ return False
166
+
167
+
168
+ def load_catalog() -> tuple[list[dict], dict]:
169
+ cat = ROOT / CC / "raw" / "catalog.jsonl"
170
+ items: list[dict] = []
171
+ seen: dict = {}
172
+ if not cat.exists() or cat.stat().st_size < 200:
173
+ return items, seen
174
+ with cat.open(encoding="utf-8") as f:
175
+ for line in f:
176
+ line = line.strip()
177
+ if not line:
178
+ continue
179
+ try:
180
+ row = json.loads(line)
181
+ except Exception:
182
+ continue
183
+ nu = normalize_act_url(row.get("url") or "")
184
+ code = row.get("code") or act_code_from_url(nu or "")
185
+ if not nu or not code or not re.search(r"\d{4}$", str(code)):
186
+ continue
187
+ if nu in seen:
188
+ prev = seen[nu]
189
+ for k in ("cdx_ts", "pdf_ts", "pdf_url", "wayback_url", "cc_record"):
190
+ if row.get(k) and not prev.get(k):
191
+ prev[k] = row[k]
192
+ continue
193
+ row["code"] = code
194
+ row["url"] = nu
195
+ items.append(row)
196
+ seen[nu] = row
197
+ return items, seen
198
+
199
+
200
+ def rewrite_catalog(items: list[dict]) -> None:
201
+ path = ROOT / CC / "raw" / "catalog.jsonl"
202
+ slim = []
203
+ for it in items:
204
+ row = {k: v for k, v in it.items() if k != "cc_record"}
205
+ cr = slim_cc_record(it.get("cc_record") or {})
206
+ if cr:
207
+ row["cc_record"] = cr
208
+ slim.append(row)
209
+ atomic_write(path, "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in slim))
210
+
211
+
212
+ def rec_len(rec: dict) -> int:
213
+ try:
214
+ return int(rec.get("length") or 0)
215
+ except Exception:
216
+ return 0
217
+
218
+
219
+ def pick_best(recs: list[dict], min_len: int = 8000) -> Optional[dict]:
220
+ usable = [r for r in recs if rec_len(r) >= min_len]
221
+ pool = usable or recs
222
+ if not pool:
223
+ return None
224
+ return max(pool, key=rec_len)
225
+
226
+
227
+ def cdx_search(url: str, **kwargs) -> list[dict]:
228
+ try:
229
+ return af.search_wayback_machine(url, **kwargs) or []
230
+ except Exception as exc:
231
+ log.warning("cdx fail %s: %s", url, exc)
232
+ time.sleep(4.0)
233
+ try:
234
+ return af.search_wayback_machine(url, **kwargs) or []
235
+ except Exception as exc2:
236
+ log.warning("cdx retry fail %s: %s", url, exc2)
237
+ return []
238
+
239
+
240
+ def wb_get(url: str, ts: Optional[str], tries: int = 3) -> dict:
241
+ last: dict = {}
242
+ for i in range(tries):
243
+ try:
244
+ res = af.get_wayback_content(url, timestamp=ts)
245
+ except Exception as exc:
246
+ res = {"status": "error", "error": str(exc)}
247
+ last = res or {}
248
+ if last.get("status") == "success" and (last.get("text") or last.get("content")):
249
+ return last
250
+ err = str(last.get("error") or "")
251
+ if last.get("http_status") in (403, 429) or "SSL" in err or "timeout" in err.lower() or "EOF" in err:
252
+ time.sleep(5.0 + i * 4.0)
253
+ continue
254
+ break
255
+ return last or {"status": "error", "error": "empty"}
256
+
257
+
258
+ def expand_catalog_letters(items: list[dict], seen: dict) -> None:
259
+ """Wayback CDX of official /Act/{A-Z} URLs only. Filter Historical/query junk."""
260
+ log.info("letter CDX expand unique=%s expected~%s", len(items), EXPECTED_ACTS)
261
+ extra = [
262
+ "!original:.*[?].*",
263
+ "!original:.*Historical.*",
264
+ "!original:.*Act-Rev.*",
265
+ "!original:.*act-rev.*",
266
+ "!original:.*Repealed.*",
267
+ "!original:.*Uncommenced.*",
268
+ "mimetype:text/html",
269
+ ]
270
+ for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
271
+ recs = cdx_search(
272
+ f"sso.agc.gov.sg/Act/{letter}",
273
+ match_type="prefix",
274
+ limit=250,
275
+ collapse="urlkey",
276
+ filter_status="200",
277
+ extra_filters=extra,
278
+ )
279
+ added = 0
280
+ for rec in recs:
281
+ extra_row = {
282
+ "source": "wayback_letter_cdx",
283
+ "cdx_ts": rec.get("timestamp"),
284
+ "wayback_url": rec.get("wayback_url"),
285
+ "cdx_length": rec.get("length"),
286
+ }
287
+ if add_item(items, seen, rec.get("original") or "", extra_row):
288
+ added += 1
289
+ log.info("letter %s cdx hits=%s new=%s total=%s", letter, len(recs), added, len(items))
290
+ time.sleep(1.5)
291
+ marker = ROOT / CC / "raw" / "letter_cdx_done.json"
292
+ marker.write_text(json.dumps({"n": len(items), "at": utcnow()}) + "\n", encoding="utf-8")
293
+
294
+
295
+ def harvest_browse_pages(items: list[dict], seen: dict) -> None:
296
+ log.info("harvest browse All/0-30 snapshots unique=%s", len(items))
297
+ for n in range(0, 31):
298
+ url = f"https://sso.agc.gov.sg/Browse/Act/Current/All/{n}"
299
+ recs = cdx_search(
300
+ url, match_type="exact", limit=8, collapse="", filter_status="200",
301
+ extra_filters=["mimetype:text/html"],
302
+ )
303
+ rec = pick_best(recs, min_len=4000)
304
+ if not rec:
305
+ continue
306
+ res = wb_get(rec.get("original") or url, rec.get("timestamp"))
307
+ html = res.get("text") or ""
308
+ if not html:
309
+ continue
310
+ newc = 0
311
+ for href in parse_act_links(html):
312
+ if add_item(items, seen, href, {
313
+ "source": "wayback_browse",
314
+ "browse_ts": rec.get("timestamp"),
315
+ }):
316
+ newc += 1
317
+ log.info("browse All/%s new=%s total=%s html=%s", n, newc, len(items), len(html))
318
+ if newc == 0 and n > 5 and n % 5 == 0:
319
+ # keep going; later pages may still have acts
320
+ pass
321
+
322
+
323
+ def discover() -> list[dict]:
324
+ items, seen = load_catalog()
325
+ if items:
326
+ log.info("resume catalog unique=%s", len(items))
327
+ else:
328
+ for page in range(0, 40):
329
+ url = f"https://sso.agc.gov.sg/Browse/Act/Current/All/{page}?PageSize=20"
330
+ html = live_get(url)
331
+ if not html:
332
+ if page == 0:
333
+ html = live_get(BROWSE)
334
+ if not html:
335
+ break
336
+ newc = 0
337
+ for href in parse_act_links(html):
338
+ if add_item(items, seen, href, {"source": "live_browse"}):
339
+ newc += 1
340
+ log.info("live browse page=%s new=%s total=%s", page, newc, len(items))
341
+ if newc == 0 and page > 0:
342
+ break
343
+
344
+ marker = ROOT / CC / "raw" / "letter_cdx_done.json"
345
+ if len(items) < EXPECTED_ACTS and not marker.exists():
346
+ expand_catalog_letters(items, seen)
347
+ rewrite_catalog(items)
348
+ elif len(items) < 400:
349
+ expand_catalog_letters(items, seen)
350
+ rewrite_catalog(items)
351
+
352
+ if len(items) < EXPECTED_ACTS:
353
+ harvest_browse_pages(items, seen)
354
+ rewrite_catalog(items)
355
+ log.info("catalog discovered %s", len(items))
356
+ return items
357
+
358
+
359
+ def pdf_to_text(raw: bytes) -> str:
360
+ if not raw or raw[:4] != b"%PDF":
361
+ return ""
362
+ try:
363
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
364
+ tmp.write(raw)
365
+ tmp.flush()
366
+ proc = subprocess.run(
367
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
368
+ check=False, capture_output=True, timeout=180,
369
+ )
370
+ if proc.returncode == 0 and proc.stdout:
371
+ return proc.stdout.decode("utf-8", "replace").strip()
372
+ except Exception as exc:
373
+ log.warning("pdftotext failed: %s", exc)
374
+ return ""
375
+
376
+
377
+ def split_sg(text: str, law_id: str, source_url: str, date: Optional[str]) -> list[dict]:
378
+ docs = split_articles(text, law_id, source_url, date)
379
+ if len(docs) >= 2:
380
+ return docs
381
+ matches = list(SG_SEC.finditer(text or ""))
382
+ if len(matches) < 2:
383
+ return []
384
+ docs = []
385
+ seen = set()
386
+ for i, m in enumerate(matches):
387
+ start = m.start()
388
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
389
+ chunk = text[start:end].strip()
390
+ if len(chunk) < 8:
391
+ continue
392
+ num = m.group(1)
393
+ aid = re.sub(r"[^a-z0-9]+", "-", f"s{num}").strip("-")
394
+ doc_id = f"{law_id}-{aid}"[:180]
395
+ if doc_id in seen:
396
+ doc_id = f"{doc_id}-{i+1}"[:180]
397
+ seen.add(doc_id)
398
+ docs.append({
399
+ "id": doc_id,
400
+ "title": chunk.split("\n", 1)[0][:200],
401
+ "text": chunk,
402
+ "date_filed": date,
403
+ "document_number": num,
404
+ "source_url": source_url,
405
+ "record_type": "article",
406
+ "article_number": num,
407
+ "law_identifier": law_id,
408
+ "metadata": {"text_extraction": {"source": "official", "backend": "sso_section"}},
409
+ })
410
+ if len(docs) >= 4000:
411
+ break
412
+ return docs
413
+
414
+
415
+ def extract_provisions(html: str, law_id: str, source_url: str, date: Optional[str]) -> tuple[str, list[dict], str]:
416
+ title = ""
417
+ m = re.search(r"<title>\s*([^<]+?)\s*-\s*Singapore Statutes Online", html, re.I)
418
+ if m:
419
+ title = re.sub(r"\s+", " ", m.group(1)).strip()
420
+ if not title:
421
+ m = re.search(r'class="legis-title"[^>]*>([^<]{3,200})', html, re.I)
422
+ if m:
423
+ title = re.sub(r"\s+", " ", m.group(1)).strip()
424
+ legis = ""
425
+ lm = re.search(r'id="legisContent"[^>]*>([\s\S]+?)</div>\s*<div[^>]*id="', html, re.I)
426
+ if not lm:
427
+ lm = re.search(r'id="colLegis"[^>]*>([\s\S]+)', html, re.I)
428
+ if lm:
429
+ legis = lm.group(1)
430
+ target = legis or html
431
+ docs = []
432
+ parts = []
433
+ blocks = re.findall(
434
+ r'(<div[^>]*class="[^"]*prov1[^"]*"[^>]*>[\s\S]*?)(?=<div[^>]*class="[^"]*prov1[^"]*"|$)',
435
+ target, re.I,
436
+ )
437
+ seen = set()
438
+ for i, block in enumerate(blocks):
439
+ hdr_m = re.search(r'class="[^"]*prov1Hdr[^"]*"[^>]*>([\s\S]*?)</div>', block, re.I)
440
+ hdr = html_to_text(hdr_m.group(1) if hdr_m else "")
441
+ body = html_to_text(block)
442
+ if not body or len(body) < 8:
443
+ continue
444
+ parts.append(body)
445
+ num = ""
446
+ nm = re.match(r"^\s*(\d+[A-Za-z]?)", hdr or body)
447
+ num = nm.group(1) if nm else str(i + 1)
448
+ heading = (hdr or body.split("\n", 1)[0])[:200]
449
+ aid = re.sub(r"[^a-z0-9]+", "-", f"s{num}").strip("-")
450
+ doc_id = f"{law_id}-{aid}"[:180]
451
+ if doc_id in seen:
452
+ doc_id = f"{doc_id}-{i+1}"[:180]
453
+ seen.add(doc_id)
454
+ docs.append({
455
+ "id": doc_id,
456
+ "title": heading,
457
+ "text": body,
458
+ "date_filed": date,
459
+ "document_number": num,
460
+ "source_url": source_url,
461
+ "record_type": "article",
462
+ "article_number": num,
463
+ "law_identifier": law_id,
464
+ "metadata": {"text_extraction": {"source": "official", "backend": "sso_prov1_html"}},
465
+ })
466
+ if len(docs) >= 4000:
467
+ break
468
+ text = "\n\n".join(parts)
469
+ full = html_to_text(target)
470
+ if not text or len(full) > len(text) * 1.2:
471
+ text = full
472
+ docs = split_sg(text, law_id, source_url, date)
473
+ if not text or len(text) < 80:
474
+ cleaned = re.sub(r"(?is)<nav\b.*?</nav>", " ", html)
475
+ cleaned = re.sub(r"(?is)<header\b.*?</header>", " ", cleaned)
476
+ cleaned = re.sub(r"(?is)<footer\b.*?</footer>", " ", cleaned)
477
+ text = html_to_text(cleaned)
478
+ docs = split_sg(text, law_id, source_url, date)
479
+ return text, docs, title
480
+
481
+
482
+ def fetch_one(it: dict, done: set[str]) -> str:
483
+ code = (it.get("code") or "").strip()
484
+ url = it.get("url") or f"https://sso.agc.gov.sg/Act/{code}"
485
+ url = normalize_act_url(url) or url
486
+ if not code:
487
+ code = act_code_from_url(url) or ""
488
+ if not code:
489
+ return "fail"
490
+ rid = slug_id(CC, code)
491
+ if rid in done:
492
+ return "skip"
493
+
494
+ html = live_get(url)
495
+ method = "live"
496
+ backend = "live"
497
+ wb_meta: dict = {}
498
+ text = ""
499
+ docs: list[dict] = []
500
+ title = ""
501
+
502
+ if html and not af.is_spa_shell(html, html_to_text(html or "")):
503
+ text, docs, title = extract_provisions(html, rid, url, None)
504
+
505
+ # Official PDF via Wayback CDX of ViewType=Pdf (complete Act body).
506
+ pdf_text = ""
507
+ pdf_url = it.get("pdf_url") or f"{url}?ViewType=Pdf"
508
+ pdf_ts = it.get("pdf_ts")
509
+ if not pdf_ts:
510
+ pdf_recs = cdx_search(
511
+ pdf_url,
512
+ match_type="prefix",
513
+ limit=12,
514
+ collapse="",
515
+ filter_status="200",
516
+ extra_filters=["mimetype:application/pdf"],
517
+ )
518
+ best_pdf = pick_best(pdf_recs, min_len=15000)
519
+ if best_pdf:
520
+ pdf_ts = best_pdf.get("timestamp")
521
+ pdf_url = best_pdf.get("original") or pdf_url
522
+ if pdf_ts:
523
+ pres = wb_get(pdf_url, pdf_ts)
524
+ raw = pres.get("content") or b""
525
+ if raw[:4] == b"%PDF":
526
+ pdf_text = pdf_to_text(raw)
527
+ if pdf_text and len(pdf_text) > 80:
528
+ wb_meta = {
529
+ "archive_backend": "wayback_pdf",
530
+ "wayback_url": pres.get("wayback_url"),
531
+ "capture_timestamp": pres.get("capture_timestamp") or pdf_ts,
532
+ "archive_url": pres.get("wayback_url"),
533
+ }
534
+ method = "archive-of-official"
535
+ backend = "wayback_pdf"
536
+ text = pdf_text
537
+ docs = split_sg(text, rid, url, None)
538
+ if not title:
539
+ tm = re.search(r"(?m)^([A-Z][A-Za-z0-9 ,.'()/-]{5,120})\s*$", text[:2000])
540
+ title = tm.group(1).strip() if tm else code
541
+
542
+ if not text or len(text) < 80:
543
+ ts = it.get("cdx_ts")
544
+ html_url = url
545
+ if not ts:
546
+ html_recs = cdx_search(
547
+ url,
548
+ match_type="exact",
549
+ limit=20,
550
+ collapse="",
551
+ filter_status="200",
552
+ extra_filters=["mimetype:text/html"],
553
+ )
554
+ best_h = pick_best(html_recs, min_len=12000)
555
+ if best_h:
556
+ ts = best_h.get("timestamp")
557
+ html_url = best_h.get("original") or url
558
+ if ts:
559
+ res = wb_get(html_url, ts)
560
+ html2 = res.get("text") or ""
561
+ if html2 and len(html2) >= 500:
562
+ t2, d2, title2 = extract_provisions(html2, rid, url, None)
563
+ if t2 and len(t2) > len(text or ""):
564
+ text, docs, title = t2, d2, title2 or title
565
+ method = "archive-of-official"
566
+ backend = "wayback_html"
567
+ wb_meta = {
568
+ "archive_backend": backend,
569
+ "wayback_url": res.get("wayback_url"),
570
+ "capture_timestamp": res.get("capture_timestamp") or ts,
571
+ "archive_url": res.get("wayback_url"),
572
+ }
573
+
574
+ if not text or len(text) < 40:
575
+ log_failure(CC, {
576
+ "identifier": code, "source_url": url, "status": "failed",
577
+ "reason": "empty_text_after_pdf_html",
578
+ })
579
+ return "fail"
580
+
581
+ title = title or code
582
+ rec = base_record(
583
+ cc=CC, country=COUNTRY, language="en", ident=code,
584
+ title=title, text=text, source_url=url, source_type=SOURCE_TYPE,
585
+ license_text=LICENSE, collector="sg-sso-agc",
586
+ eli=None, date=None, official_identifier=code,
587
+ document_type="statute", law_status="current", is_current=True,
588
+ documents=docs,
589
+ extra_meta={
590
+ "discovery": {
591
+ "method": it.get("source") or "mixed",
592
+ "catalog_identifier": code,
593
+ "seed_url": BROWSE,
594
+ "retrieval": method,
595
+ "archive_backend": backend,
596
+ **{k: v for k, v in wb_meta.items() if v},
597
+ },
598
+ "official_metadata": {
599
+ "act_code": code,
600
+ "sso_unofficial_reproduction": True,
601
+ },
602
+ "text_extraction": {
603
+ "source": "archive-of-official" if method != "live" else "official",
604
+ "backend": f"sso_{backend}",
605
+ },
606
+ },
607
+ extra_fields={
608
+ "canonical_title": title,
609
+ "citation": f"{title} ({code})",
610
+ "status_source": "sso_current_acts",
611
+ "status_confidence": "medium" if method != "live" else "high",
612
+ "status_note": (
613
+ "SSO is an unofficial reproduction. Printed Gazette / AGC official "
614
+ "text prevails. robots.txt Disallow /search honoured."
615
+ ),
616
+ },
617
+ )
618
+ rec["id"] = rid
619
+ rec["languages"] = ["en"]
620
+ write_instrument(CC, rec)
621
+ return "ok"
622
+
623
+
624
+ def main():
625
+ setup()
626
+ t0 = utcnow()
627
+ items = discover()
628
+ done = existing_ids(CC)
629
+ ok = skip = fail = 0
630
+ live_n = sum(1 for it in items if it.get("source") == "live_browse")
631
+ log.info("queue acts=%s already_done=%s live_listed=%s workers=%s",
632
+ len(items), len(done), live_n, WORKERS)
633
+ with ThreadPoolExecutor(max_workers=WORKERS) as ex:
634
+ futs = [ex.submit(fetch_one, it, done) for it in items]
635
+ n = 0
636
+ for fut in as_completed(futs):
637
+ n += 1
638
+ try:
639
+ st = fut.result()
640
+ except Exception as exc:
641
+ st = "fail"
642
+ log_failure(CC, {"status": "failed", "reason": repr(exc)})
643
+ ok += st == "ok"
644
+ skip += st == "skip"
645
+ fail += st == "fail"
646
+ if n % 10 == 0 or n == len(items):
647
+ log.info("progress %s/%s ok=%s skip=%s fail=%s", n, len(items), ok, skip, fail)
648
+ write_summary(
649
+ CC, country=COUNTRY,
650
+ source="Singapore Statutes Online (AGC Legislation Division)",
651
+ source_urls=[PORTAL, BROWSE],
652
+ license_text=LICENSE, discovered=len(items), fetched=ok,
653
+ skipped=skip, failed=fail, coverage="catalog-backed incomplete",
654
+ notes="Current Acts. No /search. Wayback CDX of official SSO URLs; PDF preferred.",
655
+ last_run=utcnow(),
656
+ )
657
+ coverage = "full" if fail == 0 and ok + skip >= len(items) and items else "catalog-backed incomplete"
658
+ notes = (
659
+ "Current Acts from SSO. robots.txt Disallow:/search honoured. "
660
+ "Live CloudFront 403 uses Wayback CDX of official sso.agc.gov.sg/Act/ "
661
+ "URLs (letter prefixes + ViewType=Pdf). No archive.is. "
662
+ f"Started {t0}."
663
+ )
664
+ write_summary(
665
+ CC, country=COUNTRY,
666
+ source="Singapore Statutes Online (AGC Legislation Division)",
667
+ source_urls=[PORTAL, BROWSE, "https://sso.agc.gov.sg/Act/CoA1967"],
668
+ license_text=LICENSE, discovered=len(items), fetched=ok,
669
+ skipped=skip, failed=fail, coverage=coverage, notes=notes,
670
+ last_run=utcnow(), extra=f"started {t0} live_listed={live_n}",
671
+ )
672
+ (ROOT / CC / "logs" / "DONE").write_text(json.dumps({
673
+ "ok": ok, "skip": skip, "fail": fail, "discovered": len(items),
674
+ "coverage": coverage, "live_listed": live_n,
675
+ }, indent=2) + "\n", encoding="utf-8")
676
+ log.info("done ok=%s skip=%s fail=%s coverage=%s", ok, skip, fail, coverage)
677
+
678
+
679
+ if __name__ == "__main__":
680
+ main()