endomorphosis commited on
Commit
2f7ee80
·
verified ·
1 Parent(s): 9b601a4

Upload folder using huggingface_hub

Browse files
MANIFEST.md CHANGED
@@ -1,13 +1,13 @@
1
  # ipfs_philippines_laws manifest
2
 
3
- generated_utc: 2026-09-09T06:15:57Z
4
  cc: ph
5
  laws_rows: 10870
6
- articles_rows: 33589
7
- laws_bytes: 13157421
8
- articles_bytes: 9651096
9
- laws_sha256: c508d78e255d3378d44876f202d202b73c4cc4fdbb73f23d2de95e4d78afcca6
10
- articles_sha256: e11f165ec9f79cf6f40fbd6ca8da4e1e0cb4a0d6ec112934c974a61b55aa21c6
11
  laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_philippines_laws/data/laws.parquet
12
  articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_philippines_laws/data/articles.parquet
13
  compression: zstd
 
1
  # ipfs_philippines_laws manifest
2
 
3
+ generated_utc: 2026-09-16T21:52:12Z
4
  cc: ph
5
  laws_rows: 10870
6
+ articles_rows: 93180
7
+ laws_bytes: 13168648
8
+ articles_bytes: 15271881
9
+ laws_sha256: 8717484e0e634b94239dea2012ffe546a5ab3f9f847796cf480bd9fc948db7bd
10
+ articles_sha256: ab4b3ad31ff667c01e40a34b0a99501f5a404ed1fd192a3f05eab1e54463d5ea
11
  laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_philippines_laws/data/laws.parquet
12
  articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_philippines_laws/data/articles.parquet
13
  compression: zstd
README.md CHANGED
@@ -34,12 +34,12 @@ Research snapshot of official national legislation from **Official Gazette of th
34
 
35
  | Field | Value |
36
  | --- | --- |
37
- | Snapshot date | 2026-09-09 |
38
  | Coverage | interim |
39
  | Source | Official Gazette of the Republic of the Philippines + Senate LRB issuances library |
40
  | Collector | `scrapers/collect_ph.py` |
41
  | Laws / instruments | 10,870 |
42
- | Articles | 33,589 |
43
  | Language | en |
44
  | Jurisdiction | Philippines |
45
  | License | `ph-official-gazette-texts` |
 
34
 
35
  | Field | Value |
36
  | --- | --- |
37
+ | Snapshot date | 2026-09-16 |
38
  | Coverage | interim |
39
  | Source | Official Gazette of the Republic of the Philippines + Senate LRB issuances library |
40
  | Collector | `scrapers/collect_ph.py` |
41
  | Laws / instruments | 10,870 |
42
+ | Articles | 93,180 |
43
  | Language | en |
44
  | Jurisdiction | Philippines |
45
  | License | `ph-official-gazette-texts` |
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e11f165ec9f79cf6f40fbd6ca8da4e1e0cb4a0d6ec112934c974a61b55aa21c6
3
- size 9651096
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab4b3ad31ff667c01e40a34b0a99501f5a404ed1fd192a3f05eab1e54463d5ea
3
+ size 15271881
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c508d78e255d3378d44876f202d202b73c4cc4fdbb73f23d2de95e4d78afcca6
3
- size 13157421
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8717484e0e634b94239dea2012ffe546a5ab3f9f847796cf480bd9fc948db7bd
3
+ size 13168648
scrapers/_ph_densify_articles.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PH Cap/Section densify on existing instruments (offline, no re-fetch / no WARC).
3
+
4
+ Senate LRB / Official Gazette Republic Acts — Commonwealth SECTION/SEC./Section/
5
+ Article/CHAPTER Cap. Many Senate LRB bodies jam SEC. markers mid-line; jam-normalize
6
+ inserts newlines before Cap markers, then prefer_enacting_body skips chrome after
7
+ "Be it enacted … assembled:". LEAN Cap: write only when article count rises.
8
+ Official pack text only.
9
+ TAG: ph_cap_section_v1
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
19
+ from common import ROOT, INDEX_FIELDS, atomic_write
20
+ from world_lib import split_custom
21
+
22
+ # Insert newline before Cap markers jammed after non-newline (Senate LRB HTML→text).
23
+ JAM = re.compile(
24
+ r"(?<=[^\n])(?=(?:SECTION|SEC\.|Section|Sec\.|ARTICLE|Article|Art\.|"
25
+ r"CHAPTER|Chapter)\s+[IVXLCDM0-9]+[A-Za-z]?\b)"
26
+ )
27
+
28
+ ART = re.compile(
29
+ r"(?im)^\s*((?:ARTICLE|Article|Art\.|SECTION|Section|SEC\.|Sec\.)\s+[IVXLCDM0-9]+[A-Za-z]?\b|"
30
+ r"(?:CHAPTER|Chapter|PART|Part)\s+[IVXLCDM0-9]+)"
31
+ )
32
+ ART_STRICT = re.compile(
33
+ r"(?im)^\s*((?:SECTION|Section|SEC\.|Sec\.|ARTICLE|Article)\s+[IVXLCDM0-9]+[A-Za-z]?\b|"
34
+ r"(?:CHAPTER|Chapter)\s+[IVXLCDM0-9]+)"
35
+ )
36
+ TAG = "ph_cap_section_v1"
37
+
38
+
39
+ def jam_normalize(text: str) -> str:
40
+ if not text:
41
+ return text
42
+ return JAM.sub("\n", text)
43
+
44
+
45
+ def prefer_enacting_body(text: str) -> str:
46
+ """Skip OG/Senate chrome; start after Be it enacted … assembled: or last Sec. 1."""
47
+ if not text:
48
+ return text
49
+ m = re.search(r"(?is)Be it enacted.{0,500}?assembled\s*:", text)
50
+ if m and m.end() < len(text) - 80:
51
+ rest = text[m.end() :]
52
+ if len(rest) > len(text) * 0.12:
53
+ return rest
54
+ m = re.search(r"(?is)BE IT ENACTED.{0,400}?:", text)
55
+ if m and m.end() < len(text) - 80:
56
+ rest = text[m.end() :]
57
+ if len(rest) > len(text) * 0.12:
58
+ return rest
59
+ secs = list(re.finditer(r"(?im)^\s*(?:SECTION|Section|SEC\.|Sec\.)\s+1\b", text))
60
+ if len(secs) >= 2:
61
+ return text[secs[-1].start() :]
62
+ if len(secs) == 1 and secs[0].start() > 120:
63
+ return text[secs[0].start() :]
64
+ return text
65
+
66
+
67
+ def pick_docs(text: str, rid: str, url: str, date):
68
+ norm = jam_normalize(text)
69
+ body = prefer_enacting_body(norm)
70
+ d_lean = split_custom(body, rid, url, date, ART)
71
+ d_strict = split_custom(body, rid, url, date, ART_STRICT)
72
+ if len(body) < len(norm) * 0.35:
73
+ d_lean_f = split_custom(norm, rid, url, date, ART)
74
+ d_strict_f = split_custom(norm, rid, url, date, ART_STRICT)
75
+ if len(d_lean_f) >= len(d_lean):
76
+ d_lean = d_lean_f
77
+ if len(d_strict_f) >= len(d_strict):
78
+ d_strict = d_strict_f
79
+ # fallback: no jam (already newline-friendly texts)
80
+ body0 = prefer_enacting_body(text)
81
+ d_raw = split_custom(body0, rid, url, date, ART)
82
+ best, mode = d_lean, "lean"
83
+ if len(d_strict) > len(best):
84
+ best, mode = d_strict, "strict"
85
+ if len(d_raw) > len(best):
86
+ best, mode = d_raw, "raw"
87
+ return best, mode
88
+
89
+
90
+ def rebuild_index() -> tuple[int, int]:
91
+ inst = ROOT / "ph" / "instruments"
92
+ index = ROOT / "ph" / "index.jsonl"
93
+ rows = []
94
+ arts = 0
95
+ for p in sorted(inst.glob("*.json")):
96
+ try:
97
+ rec = json.loads(p.read_text(encoding="utf-8"))
98
+ except Exception:
99
+ continue
100
+ n = int(rec.get("article_count") or len(rec.get("documents") or []) or 0)
101
+ arts += n
102
+ line = {k: rec.get(k) for k in INDEX_FIELDS if k not in ("path", "bytes", "article_count")}
103
+ line["path"] = f"instruments/{p.name}"
104
+ line["article_count"] = n
105
+ line["bytes"] = p.stat().st_size
106
+ line["id"] = rec.get("id") or p.stem
107
+ rows.append(line)
108
+ atomic_write(index, "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
109
+ return len(rows), arts
110
+
111
+
112
+ def main():
113
+ dry = "--dry-run" in sys.argv
114
+ root = ROOT / "ph" / "instruments"
115
+ old_sum = new_sum = changed = zero_fixed = 0
116
+ modes: dict[str, int] = {}
117
+ shellish = 0
118
+ sample_shell: list[dict] = []
119
+ for path in sorted(root.glob("*.json")):
120
+ try:
121
+ rec = json.loads(path.read_text(encoding="utf-8"))
122
+ except Exception:
123
+ continue
124
+ text = rec.get("text") or ""
125
+ old = int(rec.get("article_count") or len(rec.get("documents") or []) or 0)
126
+ if len(text) < 80:
127
+ old_sum += old
128
+ new_sum += old
129
+ continue
130
+ rid = rec.get("id") or path.stem
131
+ url = rec.get("source_url") or ""
132
+ date = rec.get("date")
133
+ docs, mode = pick_docs(text, rid, url, date)
134
+ new = len(docs)
135
+ modes[mode] = modes.get(mode, 0) + 1
136
+ if new <= old:
137
+ old_sum += old
138
+ new_sum += old
139
+ continue
140
+ if new < 2 and old >= new:
141
+ old_sum += old
142
+ new_sum += old
143
+ continue
144
+ is_shell = False
145
+ if docs:
146
+ avg = sum(len(d.get("text") or "") for d in docs) / len(docs)
147
+ if avg < 80 or len(text) < 400:
148
+ is_shell = True
149
+ shellish += 1
150
+ if len(sample_shell) < 8:
151
+ sample_shell.append({
152
+ "id": rid,
153
+ "new": new,
154
+ "avg_chunk": round(avg, 1),
155
+ "text_len": len(text),
156
+ "title0": (docs[0].get("title") or "")[:80],
157
+ })
158
+ if dry:
159
+ changed += 1
160
+ if old == 0 and new > 0:
161
+ zero_fixed += 1
162
+ old_sum += old
163
+ new_sum += new
164
+ continue
165
+ if is_shell:
166
+ old_sum += old
167
+ new_sum += old
168
+ continue
169
+ rec["documents"] = docs
170
+ rec["article_count"] = new
171
+ rec["article_extraction_status"] = "ok" if new >= 2 else ("missing" if not new else "partial")
172
+ meta = rec.get("metadata") or {}
173
+ meta["article_re"] = TAG
174
+ meta["article_re_mode"] = mode
175
+ meta["article_reprocess"] = "collect_ph.py-cap-sections"
176
+ meta["article_split"] = "commonwealth-cap"
177
+ rec["metadata"] = meta
178
+ atomic_write(path, json.dumps(rec, ensure_ascii=False, indent=2) + "\n")
179
+ changed += 1
180
+ if old == 0 and new > 0:
181
+ zero_fixed += 1
182
+ old_sum += old
183
+ new_sum += new
184
+ laws, arts = (0, 0)
185
+ if not dry:
186
+ laws, arts = rebuild_index()
187
+ report = {
188
+ "cc": "ph",
189
+ "tag": TAG,
190
+ "dry_run": dry,
191
+ "changed": changed,
192
+ "old_articles_sum": old_sum,
193
+ "new_articles_sum": new_sum,
194
+ "delta": new_sum - old_sum,
195
+ "zero_fixed": zero_fixed,
196
+ "shellish_skipped": shellish,
197
+ "hub_tip_articles": 33589,
198
+ "laws": laws,
199
+ "articles": arts,
200
+ "modes": modes,
201
+ "sample_shellish": sample_shell,
202
+ }
203
+ out = ROOT / "ph" / "raw" / "densify_articles_report.json"
204
+ if not dry:
205
+ out.parent.mkdir(parents=True, exist_ok=True)
206
+ atomic_write(out, json.dumps(report, indent=2) + "\n")
207
+ print(json.dumps(report), flush=True)
208
+
209
+
210
+ if __name__ == "__main__":
211
+ main()
scrapers/archive_fallbacks.py CHANGED
@@ -288,10 +288,13 @@ def search_wayback_machine(
288
  return out[:target]
289
 
290
 
 
291
  def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
292
  """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
293
 
294
  Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).
 
 
295
  """
296
  import subprocess
297
 
@@ -305,15 +308,19 @@ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
305
  ctype = ""
306
  final_url = target
307
  status = 0
308
- for attempt in range(1, 4):
309
- _sleep_wayback(0.8 if attempt == 1 else min(8.0, 1.8 * attempt))
 
 
 
 
310
  try:
311
  # Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
312
  proc = subprocess.run(
313
  [
314
- "curl", "-fsS", "--max-time", "90",
315
  "-A", UA,
316
- "-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}",
317
  "--output", "-",
318
  target,
319
  ],
@@ -321,55 +328,95 @@ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
321
  timeout=100,
322
  )
323
  raw = proc.stdout or b""
324
- # Trailer is text appended after body when -w is used with --output -
325
- # With --output -, -w goes to stdout after body. Split on trailer markers.
326
  marker = b"\n__HTTP_STATUS__"
 
327
  if marker in raw:
328
  body, rest = raw.rsplit(marker, 1)
329
  trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
330
  mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
331
  mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
332
  murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
 
333
  status = int(mstat.group(1)) if mstat else 0
334
  ctype = (mctype.group(1) if mctype else "") or ""
335
  final_url = (murl.group(1) if murl else target) or target
 
336
  else:
337
  body = raw
338
  status = 200 if proc.returncode == 0 and raw else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  if proc.returncode != 0 and not body:
340
  last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
341
  log.info("wayback replay curl fail %s: %s", url, last_err)
 
342
  continue
343
- if status in (403, 429, 503, 502, 504) and attempt < 3:
344
- log.info("wayback replay HTTP %s %s attempt=%s", status, url, attempt)
 
345
  continue
346
  break
347
  except Exception as exc:
348
  last_err = str(exc)
349
  log.info("wayback replay fail %s: %s", url, exc)
 
350
  continue
351
  else:
352
  # fallback: requests without following redirects to https
353
  try:
354
- r = session().get(target, timeout=(20, 90), allow_redirects=False)
355
- status = r.status_code
356
- body = r.content or b""
357
- ctype = r.headers.get("content-type") or ""
358
- final_url = r.url or target
359
- if status in (301, 302, 303, 307, 308):
360
- loc = r.headers.get("Location") or ""
 
 
 
 
 
361
  if loc.startswith("https://web.archive.org/"):
362
  loc = "http://" + loc[len("https://"):]
363
- if loc.startswith("http://web.archive.org/"):
364
- r2 = session().get(loc, timeout=(20, 90), allow_redirects=False)
365
- status = r2.status_code
366
- body = r2.content or b""
367
- ctype = r2.headers.get("content-type") or ""
368
- final_url = r2.url or loc
369
  except requests.RequestException as exc:
370
  return {"status": "error", "error": last_err or str(exc), "url": url}
371
 
372
- if not body and status != 200:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  return {"status": "error", "error": last_err or f"http_{status}", "url": url}
374
  cap_ts = timestamp or ""
375
  m = re.search(r"/web/(\d{14})", final_url or "")
 
288
  return out[:target]
289
 
290
 
291
+
292
  def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
293
  """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search.
294
 
295
  Prefer HTTP Wayback via curl (requests follows http→https and SSL-EOFs here).
296
+ Follow 3xx Location only after rewriting https://web.archive.org → http://.
297
+ Redirect hops do not consume the HTTP retry budget.
298
  """
299
  import subprocess
300
 
 
308
  ctype = ""
309
  final_url = target
310
  status = 0
311
+ redirects_left = 8
312
+ attempts_left = 5
313
+ first = True
314
+ while attempts_left > 0:
315
+ _sleep_wayback(0.35 if not first and redirects_left < 8 else (0.8 if first else min(8.0, 1.8 * (6 - attempts_left))))
316
+ first = False
317
  try:
318
  # Stay on HTTP: no -L (redirects flip to https and SSLEOF on this host)
319
  proc = subprocess.run(
320
  [
321
+ "curl", "-sS", "--max-time", "90",
322
  "-A", UA,
323
+ "-w", "\n__HTTP_STATUS__%{http_code}\n__CONTENT_TYPE__%{content_type}\n__URL_EFFECTIVE__%{url_effective}\n__REDIRECT_URL__%{redirect_url}",
324
  "--output", "-",
325
  target,
326
  ],
 
328
  timeout=100,
329
  )
330
  raw = proc.stdout or b""
 
 
331
  marker = b"\n__HTTP_STATUS__"
332
+ redirect_url = ""
333
  if marker in raw:
334
  body, rest = raw.rsplit(marker, 1)
335
  trailer = (b"__HTTP_STATUS__" + rest).decode("utf-8", "replace")
336
  mstat = re.search(r"__HTTP_STATUS__(\d+)", trailer)
337
  mctype = re.search(r"__CONTENT_TYPE__([^\n]*)", trailer)
338
  murl = re.search(r"__URL_EFFECTIVE__([^\n]*)", trailer)
339
+ mredir = re.search(r"__REDIRECT_URL__([^\n]*)", trailer)
340
  status = int(mstat.group(1)) if mstat else 0
341
  ctype = (mctype.group(1) if mctype else "") or ""
342
  final_url = (murl.group(1) if murl else target) or target
343
+ redirect_url = (mredir.group(1) if mredir else "") or ""
344
  else:
345
  body = raw
346
  status = 200 if proc.returncode == 0 and raw else 0
347
+ if status in (301, 302, 303, 307, 308):
348
+ loc = (redirect_url or "").strip()
349
+ if loc.startswith("/"):
350
+ loc = "http://web.archive.org" + loc
351
+ if loc.startswith("https://web.archive.org/"):
352
+ loc = "http://" + loc[len("https://"):]
353
+ if loc.startswith("http://web.archive.org/") and redirects_left > 0:
354
+ log.info("wayback replay follow HTTP redirect %s -> %s", status, loc[:120])
355
+ target = loc
356
+ final_url = loc
357
+ redirects_left -= 1
358
+ continue # redirect hop: do not consume attempts_left
359
+ last_err = f"http_{status}_bad_redirect"
360
+ log.info("wayback replay HTTP %s bad redirect %s", status, (loc or "")[:160])
361
+ attempts_left -= 1
362
+ continue
363
  if proc.returncode != 0 and not body:
364
  last_err = (proc.stderr or b"").decode("utf-8", "replace")[:300] or f"curl_rc_{proc.returncode}"
365
  log.info("wayback replay curl fail %s: %s", url, last_err)
366
+ attempts_left -= 1
367
  continue
368
+ if status in (403, 429, 503, 502, 504) and attempts_left > 1:
369
+ log.info("wayback replay HTTP %s %s attempts_left=%s", status, url, attempts_left)
370
+ attempts_left -= 1
371
  continue
372
  break
373
  except Exception as exc:
374
  last_err = str(exc)
375
  log.info("wayback replay fail %s: %s", url, exc)
376
+ attempts_left -= 1
377
  continue
378
  else:
379
  # fallback: requests without following redirects to https
380
  try:
381
+ hops = 0
382
+ while hops < 8:
383
+ r = session().get(target, timeout=(20, 90), allow_redirects=False)
384
+ status = r.status_code
385
+ body = r.content or b""
386
+ ctype = r.headers.get("content-type") or ""
387
+ final_url = r.url or target
388
+ if status not in (301, 302, 303, 307, 308):
389
+ break
390
+ loc = (r.headers.get("Location") or "").strip()
391
+ if loc.startswith("/"):
392
+ loc = "http://web.archive.org" + loc
393
  if loc.startswith("https://web.archive.org/"):
394
  loc = "http://" + loc[len("https://"):]
395
+ if not loc.startswith("http://web.archive.org/"):
396
+ last_err = f"http_{status}_bad_redirect"
397
+ break
398
+ target = loc
399
+ final_url = loc
400
+ hops += 1
401
  except requests.RequestException as exc:
402
  return {"status": "error", "error": last_err or str(exc), "url": url}
403
 
404
+ if (not body and status != 200) or status == 404:
405
+ # /2id_/ sometimes lands on a missing capture; pick an explicit CDX 200 snapshot.
406
+ if not timestamp:
407
+ try:
408
+ hits = search_wayback_machine(url, limit=5, filter_status="200", collapse="digest")
409
+ for hit in hits:
410
+ ts = hit.get("timestamp") or ""
411
+ orig = hit.get("original") or url
412
+ if not ts:
413
+ continue
414
+ alt = get_wayback_content(orig, timestamp=ts)
415
+ if alt.get("status") == "success" and (alt.get("content") or b""):
416
+ return alt
417
+ # also try original host/path casing from CDX
418
+ except Exception as exc:
419
+ log.info("wayback cdx retry after http_%s: %s", status, exc)
420
  return {"status": "error", "error": last_err or f"http_{status}", "url": url}
421
  cap_ts = timestamp or ""
422
  m = re.search(r"/web/(\d{14})", final_url or "")
scrapers/world_lib.py CHANGED
@@ -217,15 +217,28 @@ def fetch_official(
217
  text=text,
218
  content=pdf_bytes,
219
  method="wayback_pdf",
220
- source_url=w.get("url") or url,
221
  content_type="application/pdf",
222
  )
223
  return out
 
 
 
 
 
 
 
224
  out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
225
  return out
226
  if not raw_t and isinstance(raw_b, bytes):
227
  raw_t = raw_b.decode("utf-8", "replace")
228
  if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
 
 
 
 
 
 
229
  out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
230
  return out
231
  text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
 
217
  text=text,
218
  content=pdf_bytes,
219
  method="wayback_pdf",
220
+ source_url=w.get("wayback_url") or w.get("url") or url,
221
  content_type="application/pdf",
222
  )
223
  return out
224
+ # Keep PDF bytes so caller can OCR (image-only / bad text layer)
225
+ out.update(
226
+ content=pdf_bytes,
227
+ content_type="application/pdf",
228
+ method="wayback_pdf_bytes",
229
+ source_url=w.get("wayback_url") or w.get("url") or url,
230
+ )
231
  out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
232
  return out
233
  if not raw_t and isinstance(raw_b, bytes):
234
  raw_t = raw_b.decode("utf-8", "replace")
235
  if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
236
+ # Treat as PDF bytes for OCR upstream
237
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) else raw_t.encode("latin-1", "replace")
238
+ if isinstance(pdf_bytes, bytes) and b"%PDF" in pdf_bytes[:8192]:
239
+ if pdf_bytes[:4] != b"%PDF":
240
+ pdf_bytes = pdf_bytes[pdf_bytes.find(b"%PDF"):]
241
+ out.update(content=pdf_bytes, content_type="application/pdf", method="wayback_pdf_bytes")
242
  out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
243
  return out
244
  text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t