rain1024 commited on
Commit
007dd4d
·
1 Parent(s): 07490a0

fix(scraper): validate fetched content matches requested law (issue #1035)

Browse files

search_law_url no longer returns the first /van-ban/ link on the page (which
grabbed the site 'van ban moi' widget and stored unrelated text under correct
headers); it now only returns a result whose context contains the requested so
hieu. The download loop verifies the requested document number appears on the
fetched page before saving, recording misses to download_failures.json instead
of corrupting the corpus. Adds a 'verify' command to detect existing
number/type mismatches in downloaded files.

Files changed (1) hide show
  1. scripts/downloader.py +168 -36
scripts/downloader.py CHANGED
@@ -61,6 +61,32 @@ def slugify(text: str) -> str:
61
  return text.strip('-')
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def create_front_matter(metadata: dict) -> str:
65
  """Create YAML front matter for markdown file."""
66
  lines = ["---"]
@@ -77,46 +103,62 @@ def create_front_matter(metadata: dict) -> str:
77
 
78
 
79
  def search_law_url(client: httpx.Client, name_vi: str, doc_number: str | None = None) -> str | None:
80
- """Search for a law on thuvienphapluat.vn and return its URL."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  try:
82
- # Search by document number first if available
83
- keyword = doc_number if doc_number else name_vi
84
- params = {
85
- "keyword": keyword,
86
- "type": "0",
87
- "match": "True",
88
- "area": "0",
89
- "status": "0",
90
- "signer": "0",
91
- "sort": "0",
92
- "page": "1",
93
- }
94
-
95
  response = client.get(SEARCH_URL, params=params, follow_redirects=True)
96
  response.raise_for_status()
97
-
98
- soup = BeautifulSoup(response.text, "lxml")
99
-
100
- # Find first matching result
101
- for item in soup.select(".nqDoc, .doc-item, .search-result-item, [class*='item']"):
102
- link = item.select_one("a[href*='/van-ban/']")
103
- if link:
104
- href = link.get("href", "")
105
- if href:
106
- return urljoin(BASE_URL, href)
107
-
108
- # Try alternative selectors
109
- for link in soup.select("a[href*='/van-ban/']"):
110
- href = link.get("href", "")
111
- if href and "/van-ban/" in href:
112
- return urljoin(BASE_URL, href)
113
-
114
- return None
115
-
116
  except Exception as e:
117
  console.print(f"[yellow]Search failed for {name_vi}: {e}[/yellow]")
118
  return None
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  def fetch_law_content(client: httpx.Client, url: str) -> dict | None:
122
  """Fetch law content from thuvienphapluat.vn."""
@@ -157,8 +199,11 @@ def fetch_law_content(client: httpx.Client, url: str) -> dict | None:
157
  if issuer:
158
  metadata["issuing_body"] = issuer.get_text(strip=True)
159
 
160
- # Main content
161
- content_elem = soup.select_one(".doc-content, .noi-dung, .content, article")
 
 
 
162
  if content_elem:
163
  # Remove scripts and styles
164
  for tag in content_elem.select("script, style"):
@@ -174,6 +219,10 @@ def fetch_law_content(client: httpx.Client, url: str) -> dict | None:
174
  tag.decompose()
175
  metadata["content"] = body.get_text(separator="\n", strip=True)
176
 
 
 
 
 
177
  return metadata
178
 
179
  except Exception as e:
@@ -341,6 +390,8 @@ def download(fetch_content: bool, delay: float, limit: int):
341
  console.print(f"Output directory: [cyan]{DATA_DIR}[/cyan]")
342
  console.print()
343
 
 
 
344
  with Progress(
345
  SpinnerColumn(),
346
  TextColumn("[progress.description]{task.description}"),
@@ -375,8 +426,28 @@ def download(fetch_content: bool, delay: float, limit: int):
375
  law["url"] = url
376
  data = fetch_law_content(client, url)
377
  if data:
378
- content = data.get("content")
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  time.sleep(delay)
 
 
 
 
 
 
 
380
 
381
  filepath = save_law_file(law, content)
382
  progress.advance(task)
@@ -387,6 +458,21 @@ def download(fetch_content: bool, delay: float, limit: int):
387
  console.print()
388
  console.print(f"[green]Done![/green] Files saved to [cyan]{DATA_DIR}[/cyan]")
389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
391
  @cli.command()
392
  def stats():
@@ -435,6 +521,52 @@ def list_files():
435
  console.print(f" ... and {len(files) - 20} more")
436
 
437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
  def main():
439
  cli()
440
 
 
61
  return text.strip('-')
62
 
63
 
64
+ DOC_CODE_RE = re.compile(r"\d+\s*/\s*\d{4}\s*/\s*(?:QH|UBTVQH|PL-UBTVQH|NQ)\d*", re.I)
65
+
66
+
67
+ def extract_doc_codes(text: str) -> set[str]:
68
+ """Return every document number (e.g. '51/2014/QH13') found in text, normalized."""
69
+ return {re.sub(r"\s+", "", m).upper() for m in DOC_CODE_RE.findall(text or "")}
70
+
71
+
72
+ def normalize_code(code: str | None) -> str:
73
+ return re.sub(r"\s+", "", code or "").upper()
74
+
75
+
76
+ def content_matches_law(requested_number: str | None, fetched_text: str) -> bool:
77
+ """True only if the requested document number actually appears in the fetched page.
78
+
79
+ This is the guard against the corpus-corruption bug: the old scraper trusted
80
+ whatever URL search returned (often the site's "văn bản mới" / newest-document
81
+ widget) and stored that unrelated text under the correct front-matter header. We
82
+ now require the requested số hiệu to be present in the page before saving.
83
+ """
84
+ want = normalize_code(requested_number)
85
+ if not want:
86
+ return False # no number to verify against -> treat as unverified
87
+ return want in extract_doc_codes(fetched_text)
88
+
89
+
90
  def create_front_matter(metadata: dict) -> str:
91
  """Create YAML front matter for markdown file."""
92
  lines = ["---"]
 
103
 
104
 
105
  def search_law_url(client: httpx.Client, name_vi: str, doc_number: str | None = None) -> str | None:
106
+ """Find a law's URL on thuvienphapluat.vn.
107
+
108
+ Only returns a URL we are confident points at the requested document: a result
109
+ whose link text / surrounding context contains the document number. Returns None
110
+ rather than guessing the first ``/van-ban/`` link on the page — the old behaviour
111
+ grabbed whatever link came first (typically the site's "văn bản mới" widget),
112
+ which is the root cause of the duplicated/mismatched corpus entries.
113
+ """
114
+ keyword = doc_number if doc_number else name_vi
115
+ params = {
116
+ "keyword": keyword,
117
+ "type": "0",
118
+ "match": "True",
119
+ "area": "0",
120
+ "status": "0",
121
+ "signer": "0",
122
+ "sort": "0",
123
+ "page": "1",
124
+ }
125
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  response = client.get(SEARCH_URL, params=params, follow_redirects=True)
127
  response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  except Exception as e:
129
  console.print(f"[yellow]Search failed for {name_vi}: {e}[/yellow]")
130
  return None
131
 
132
+ # A document-number search often redirects straight to the document page.
133
+ final_url = str(response.url)
134
+ if "/van-ban/" in final_url:
135
+ return final_url
136
+
137
+ soup = BeautifulSoup(response.text, "lxml")
138
+ want = normalize_code(doc_number)
139
+
140
+ # Collect every candidate result link together with its surrounding text.
141
+ candidates: list[tuple[str, str]] = []
142
+ for link in soup.select("a[href*='/van-ban/']"):
143
+ href = link.get("href", "")
144
+ if "/van-ban/" not in href:
145
+ continue
146
+ ctx = link.get_text(" ", strip=True)
147
+ parent = link.find_parent(["li", "div", "tr", "p"])
148
+ if parent:
149
+ ctx += " " + parent.get_text(" ", strip=True)
150
+ candidates.append((urljoin(BASE_URL, href), normalize_code(ctx)))
151
+
152
+ # Prefer the candidate whose context contains the requested document number.
153
+ if want:
154
+ for url, ctx_code in candidates:
155
+ if want in ctx_code:
156
+ return url
157
+ return None # no confident match — do not guess
158
+
159
+ # No document number to disambiguate on: only safe when there is one result.
160
+ return candidates[0][0] if len(candidates) == 1 else None
161
+
162
 
163
  def fetch_law_content(client: httpx.Client, url: str) -> dict | None:
164
  """Fetch law content from thuvienphapluat.vn."""
 
199
  if issuer:
200
  metadata["issuing_body"] = issuer.get_text(strip=True)
201
 
202
+ # Main content (thuvienphapluat renders the doc body in #divContentDoc)
203
+ content_elem = soup.select_one(
204
+ "#divContentDoc, .content1, .cldivContentDocVn, "
205
+ ".doc-content, .noi-dung, .content, article"
206
+ )
207
  if content_elem:
208
  # Remove scripts and styles
209
  for tag in content_elem.select("script, style"):
 
219
  tag.decompose()
220
  metadata["content"] = body.get_text(separator="\n", strip=True)
221
 
222
+ # Document numbers detected on the page, used by the caller to verify the
223
+ # fetched page is actually the requested law before saving it.
224
+ metadata["found_numbers"] = sorted(extract_doc_codes(metadata.get("content", "")))
225
+
226
  return metadata
227
 
228
  except Exception as e:
 
390
  console.print(f"Output directory: [cyan]{DATA_DIR}[/cyan]")
391
  console.print()
392
 
393
+ failures: list[dict] = []
394
+
395
  with Progress(
396
  SpinnerColumn(),
397
  TextColumn("[progress.description]{task.description}"),
 
426
  law["url"] = url
427
  data = fetch_law_content(client, url)
428
  if data:
429
+ fetched = data.get("content", "") or ""
430
+ # GUARD: only keep the text if the requested document
431
+ # number is actually present on the fetched page. This
432
+ # prevents storing an unrelated law under a correct header
433
+ # (the duplicated/mismatched-entries bug).
434
+ if content_matches_law(law.get("document_number"), fetched):
435
+ content = fetched
436
+ else:
437
+ failures.append({
438
+ "id": law.get("id"),
439
+ "document_number": law.get("document_number"),
440
+ "url": url,
441
+ "found_numbers": data.get("found_numbers", []),
442
+ })
443
  time.sleep(delay)
444
+ else:
445
+ failures.append({
446
+ "id": law.get("id"),
447
+ "document_number": law.get("document_number"),
448
+ "url": None,
449
+ "found_numbers": [],
450
+ })
451
 
452
  filepath = save_law_file(law, content)
453
  progress.advance(task)
 
458
  console.print()
459
  console.print(f"[green]Done![/green] Files saved to [cyan]{DATA_DIR}[/cyan]")
460
 
461
+ if fetch_content:
462
+ verified = len(laws) - len(failures)
463
+ console.print(
464
+ f"Content verified for [green]{verified}[/green]/{len(laws)} "
465
+ f"(requested số hiệu found on page); [red]{len(failures)}[/red] unresolved."
466
+ )
467
+ if failures:
468
+ import json as _json
469
+ fpath = DATA_DIR.parent / "download_failures.json"
470
+ fpath.write_text(_json.dumps(failures, ensure_ascii=False, indent=2), encoding="utf-8")
471
+ console.print(
472
+ f"Unresolved entries -> [cyan]{fpath}[/cyan] "
473
+ f"(their content was NOT saved, to avoid corrupting the corpus; re-run to retry)."
474
+ )
475
+
476
 
477
  @cli.command()
478
  def stats():
 
521
  console.print(f" ... and {len(files) - 20} more")
522
 
523
 
524
+ @cli.command()
525
+ def verify():
526
+ """Verify downloaded files: does each file's document number appear in its body?
527
+
528
+ Catches the duplicated/mismatched-content bug (issue #1035) where the front-matter
529
+ header is correct but the body is a different document.
530
+ """
531
+ if not DATA_DIR.exists():
532
+ console.print("[yellow]No data directory found[/yellow]")
533
+ return
534
+
535
+ files = sorted(DATA_DIR.rglob("*.md"))
536
+ wrong_number, wrong_type = [], []
537
+ for f in files:
538
+ text = f.read_text(encoding="utf-8")
539
+ m = re.search(r'document_number:\s*"?([^"\n]+)', text)
540
+ want = normalize_code(m.group(1)) if m else ""
541
+ tm = re.search(r'^type:\s*"?([^"\n]+)', text, re.M)
542
+ ftype = (tm.group(1).strip() if tm else "").lower()
543
+ body = text.split("## Nội dung", 1)[-1] if "## Nội dung" in text else text
544
+ found = extract_doc_codes(body)
545
+
546
+ # (1) requested số hiệu must appear in the body
547
+ if want and want not in found:
548
+ wrong_number.append((f.name, want, sorted(found)[:3]))
549
+
550
+ # (2) a law/code/constitution must not actually be a resolution/decree
551
+ kind = re.search(r"\n\s*(NGHỊ QUYẾT|NGHỊ ĐỊNH|BỘ LUẬT|LUẬT|HIẾN PHÁP|PHÁP LỆNH)\s*\n", body)
552
+ bk = kind.group(1) if kind else ""
553
+ if ftype in ("law", "code", "constitution") and bk in ("NGHỊ QUYẾT", "NGHỊ ĐỊNH"):
554
+ wrong_type.append((f.name, ftype, bk))
555
+
556
+ bad = len(wrong_number) + len(wrong_type)
557
+ console.print(
558
+ f"Checked [green]{len(files)}[/green] files; "
559
+ f"[red]{len(wrong_number)}[/red] với số hiệu header không có trong body, "
560
+ f"[red]{len(wrong_type)}[/red] là nghị quyết/nghị định bị gán nhãn luật"
561
+ )
562
+ for name, want, found in wrong_number[:20]:
563
+ console.print(f" [yellow]{name}[/yellow]: header={want}, body has {found or 'none'}")
564
+ for name, ftype, bk in wrong_type[:20]:
565
+ console.print(f" [magenta]{name}[/magenta]: type={ftype} but body is {bk}")
566
+ if bad == 0:
567
+ console.print("[green]All files consistent.[/green]")
568
+
569
+
570
  def main():
571
  cli()
572