th1nhng0 commited on
Commit
cb26e8c
·
1 Parent(s): 0a39ad7

Release 2.0.0 VBPL portal refresh

Browse files
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .ruff_cache/
5
+ .pytest_cache/
6
+
7
+ # Local crawl and rollback artifacts; published Parquet files stay tracked.
8
+ data/*_raw.jsonl
9
+ data/refresh_*/
10
+ data/archive_pre_refresh_*/
11
+ data/_*/
CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## 2.0.0 — 2026-07-23
4
+
5
+ ### Dataset
6
+
7
+ - Refreshed the active dataset from the current VBPL Next.js catalog and JSON gateway.
8
+ - Published 171,556 metadata rows, 170,824 unique HTML documents, and 1,033,255 unique relationship edges.
9
+ - Added UUID and portal-prefixed document IDs; all active-config join keys are now strings.
10
+ - Removed duplicate content rows while retaining historical records no longer listed by the portal.
11
+ - Filled missing refresh metadata from the preceding published snapshot.
12
+ - Split the incompatible `legacy` config into loadable `legacy_metadata` and `legacy_content` configs.
13
+ - Re-encoded active Parquet files as bounded Arrow string row groups for Hugging Face `datasets` and Dataset Viewer compatibility.
14
+
15
+ ### Crawler and tooling
16
+
17
+ - Replaced the retired VBPL crawl path with the current catalog server action and public document API.
18
+ - Consolidated metadata, relationships, and full-text HTML into one resumable spider.
19
+ - Added streaming JSONL-to-Parquet conversion, deterministic upsert, and comparison tools.
20
+ - Removed the obsolete content spider, Pandas helper, and unused Scrapy item/pipeline boilerplate.
21
+ - Added a reproducible `uv` project and lockfile.
README.md CHANGED
@@ -28,49 +28,61 @@ configs:
28
  data_files:
29
  - split: data
30
  path: data/content.parquet
31
- - config_name: legacy
32
  data_files:
33
- - split: content
34
- path: legacy/content.parquet
35
  - split: metadata
36
  path: legacy/metadata.parquet
 
 
 
 
37
  dataset_info:
38
- - config_name: legacy
39
  features:
40
  - name: id
41
  dtype: int64
42
  - name: document_number
43
- dtype: string
44
  - name: title
45
- dtype: string
46
  - name: legal_type
47
- dtype: string
48
  - name: legal_sectors
49
- dtype: string
50
  - name: issuing_authority
51
- dtype: string
52
  - name: issuance_date
53
- dtype: string
54
  - name: effect_date
55
- dtype: string
56
  - name: effectless_date
57
- dtype: string
58
  - name: effect_status
59
- dtype: string
60
  - name: signers
61
- dtype: string
62
  splits:
63
  - name: metadata
64
- num_bytes: 137000000
65
  num_examples: 518601
 
 
 
 
 
 
66
  - name: content
67
- num_bytes: 3507657146
 
 
 
68
  num_examples: 518235
69
- download_size: 3644657146
 
70
  - config_name: metadata
71
  features:
72
  - name: id
73
- dtype: int64
74
  - name: title
75
  dtype: string
76
  - name: so_ky_hieu
@@ -103,23 +115,38 @@ dataset_info:
103
  dtype: string
104
  - name: tinh_trang_hieu_luc
105
  dtype: string
106
- num_rows: 153420
 
 
 
 
 
107
  - config_name: relationships
108
  features:
109
  - name: doc_id
110
- dtype: int64
111
  - name: other_doc_id
112
  dtype: string
113
  - name: relationship
114
  dtype: string
115
- num_rows: 897890
 
 
 
 
 
116
  - config_name: content
117
  features:
118
  - name: id
119
  dtype: string
120
  - name: content_html
121
  dtype: string
122
- num_rows: 178665
 
 
 
 
 
123
  ---
124
 
125
  # Vietnamese Legal Documents
@@ -132,12 +159,27 @@ A comprehensive collection of Vietnamese legal documents — laws, decrees, circ
132
  - **Language:** Vietnamese
133
  - **License:** [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ## Quick Start
136
 
137
  ```python
138
  from datasets import load_dataset
139
 
140
- # Metadata for all 153k documents
141
  meta = load_dataset("th1nhng0/vietnamese-legal-documents", "metadata", split="data")
142
  print(meta.to_pandas().head())
143
 
@@ -145,7 +187,7 @@ print(meta.to_pandas().head())
145
  rels = load_dataset("th1nhng0/vietnamese-legal-documents", "relationships", split="data")
146
  print(rels.to_pandas().head())
147
 
148
- # Full-text HTML content for ~149k documents
149
  content = load_dataset("th1nhng0/vietnamese-legal-documents", "content", split="data")
150
  print(content.to_pandas().head())
151
  ```
@@ -165,21 +207,21 @@ print(citing[["id", "title", "relationship"]])
165
 
166
  ## Dataset Structure
167
 
168
- The dataset has four configs:
169
 
170
  | Config | Split | Rows | Description |
171
  |---|---|---|---|
172
- | `metadata` | `data` | 153,420 | One row per document — 16 metadata fields |
173
- | `content` | `data` | 178,665 | Raw HTML full-text content |
174
- | `relationships` | `data` | 897,890 | Directed edges between documents |
175
- | `legacy` | `metadata` | 518,601 | Older crawl — English field names, more docs |
176
- | `legacy` | `content` | 518,235 | Plain-text content for older crawl |
177
 
178
  ### `metadata`
179
 
180
  | Column | Description |
181
  |---|---|
182
- | `id` | Unique document ID (int) |
183
  | `title` | Full Vietnamese title |
184
  | `so_ky_hieu` | Official number, e.g. `115/NQ-HĐBCQG` |
185
  | `ngay_ban_hanh` | Issuance date (`DD/MM/YYYY`) |
@@ -204,7 +246,7 @@ The dataset has four configs:
204
  | `id` | Document ID (join key → `metadata.id`) |
205
  | `content_html` | Raw HTML body of the document |
206
 
207
- > **Note:** Some documents in `metadata` do not have a corresponding entry in `content` because the portal only provides PDF scans for those documents (no HTML version available).
208
 
209
  ### `relationships`
210
 
@@ -212,9 +254,13 @@ The dataset has four configs:
212
  |---|---|
213
  | `doc_id` | Source document ID (join key → `metadata.id`) |
214
  | `other_doc_id` | Target document ID |
215
- | `relationship` | Edge label |
216
 
217
- ### `legacy`
 
 
 
 
218
 
219
  An older, larger crawl snapshot with ~518 k documents. Field names and enumerated values are in English (unlike the current configs which use Vietnamese originals). Dates are `YYYY-MM-DD`. Use this config when you need broader coverage at the cost of reduced metadata richness.
220
 
@@ -246,35 +292,52 @@ An older, larger crawl snapshot with ~518 k documents. Field names and enumerate
246
  ```python
247
  from datasets import load_dataset
248
 
249
- legacy_meta = load_dataset("th1nhng0/vietnamese-legal-documents", "legacy", split="metadata")
250
- legacy_content = load_dataset("th1nhng0/vietnamese-legal-documents", "legacy", split="content")
251
  ```
252
 
253
- ## Statistics
254
-
255
- ![Documents by year](charts/docs_by_year.png)
256
-
257
- ![Document type distribution](charts/legal_type_distribution.png)
258
 
259
- ![Top issuing authorities](charts/top_authorities.png)
260
 
261
- ## Data Collection
262
 
263
- All data was scraped from [vbpl.vn](https://vbpl.vn) using a [Scrapy](https://scrapy.org/) crawler (included under [`crawler/`](crawler/)). Metadata and cross-document relationships were extracted directly from the portal's structured pages.
 
264
 
265
  ```bash
266
  cd crawler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
- scrapy crawl vbpl -a seed_file=data/ids.txt # basic
269
- scrapy crawl vbpl -a seed_file=data/ids.txt -a proxy_file=proxies.txt # with proxies
270
- scrapy crawl vbpl -a seed_file=data/ids.txt -a resume=1 # resume
271
  ```
272
 
273
- Output: `data/raw.jsonl`
 
274
 
275
  ## Limitations
276
 
277
  - Coverage depends on what [vbpl.vn](https://vbpl.vn) has indexed; older or undigitized documents may be missing.
 
278
  - Effect status reflects the portal at crawl time and may lag behind real-world changes.
279
  - This is a snapshot, not a live mirror. Always cross-check with the portal for authoritative status.
280
 
@@ -298,4 +361,4 @@ The dataset contains names of document signatories (public officials acting in t
298
 
299
  Vietnamese legal documents are **public domain** under the [Law on Access to Information (No. 104/2016/QH13)](https://chinhphu.vn/default.aspx?pageid=27160&docid=184568) and the [Law on Promulgation of Legal Documents (No. 64/2025/QH15)](https://chinhphu.vn/?pageid=27160&docid=213327&classid=1&typegroupid=3).
300
 
301
- The compiled dataset (schema, processing, curation) is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Not a substitute for legal advice.
 
28
  data_files:
29
  - split: data
30
  path: data/content.parquet
31
+ - config_name: legacy_metadata
32
  data_files:
 
 
33
  - split: metadata
34
  path: legacy/metadata.parquet
35
+ - config_name: legacy_content
36
+ data_files:
37
+ - split: content
38
+ path: legacy/content.parquet
39
  dataset_info:
40
+ - config_name: legacy_metadata
41
  features:
42
  - name: id
43
  dtype: int64
44
  - name: document_number
45
+ dtype: large_string
46
  - name: title
47
+ dtype: large_string
48
  - name: legal_type
49
+ dtype: large_string
50
  - name: legal_sectors
51
+ dtype: large_string
52
  - name: issuing_authority
53
+ dtype: large_string
54
  - name: issuance_date
55
+ dtype: large_string
56
  - name: effect_date
57
+ dtype: large_string
58
  - name: effectless_date
59
+ dtype: large_string
60
  - name: effect_status
61
+ dtype: large_string
62
  - name: signers
63
+ dtype: large_string
64
  splits:
65
  - name: metadata
66
+ num_bytes: 217111959
67
  num_examples: 518601
68
+ download_size: 51272673
69
+ dataset_size: 217111959
70
+ - config_name: legacy_content
71
+ features:
72
+ - name: id
73
+ dtype: int64
74
  - name: content
75
+ dtype: large_string
76
+ splits:
77
+ - name: content
78
+ num_bytes: 10683289665
79
  num_examples: 518235
80
+ download_size: 3507657146
81
+ dataset_size: 10683289665
82
  - config_name: metadata
83
  features:
84
  - name: id
85
+ dtype: string
86
  - name: title
87
  dtype: string
88
  - name: so_ky_hieu
 
115
  dtype: string
116
  - name: tinh_trang_hieu_luc
117
  dtype: string
118
+ splits:
119
+ - name: data
120
+ num_bytes: 81375915
121
+ num_examples: 171556
122
+ download_size: 15335252
123
+ dataset_size: 81375915
124
  - config_name: relationships
125
  features:
126
  - name: doc_id
127
+ dtype: string
128
  - name: other_doc_id
129
  dtype: string
130
  - name: relationship
131
  dtype: string
132
+ splits:
133
+ - name: data
134
+ num_bytes: 39475717
135
+ num_examples: 1033255
136
+ download_size: 9436116
137
+ dataset_size: 39475717
138
  - config_name: content
139
  features:
140
  - name: id
141
  dtype: string
142
  - name: content_html
143
  dtype: string
144
+ splits:
145
+ - name: data
146
+ num_bytes: 5646405351
147
+ num_examples: 170824
148
+ download_size: 787193691
149
+ dataset_size: 5646405351
150
  ---
151
 
152
  # Vietnamese Legal Documents
 
159
  - **Language:** Vietnamese
160
  - **License:** [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
161
 
162
+ ## 2026 Portal Refresh
163
+
164
+ This release migrates the active configs to the current VBPL Next.js catalog
165
+ and public JSON gateway. It adds UUID and portal-prefixed records, removes
166
+ duplicate content rows, refreshes document text and relationships, and retains
167
+ records that disappeared from the live catalog as historical rows.
168
+
169
+ **Migration note:** `metadata.id`, `content.id`, `relationships.doc_id`, and
170
+ `relationships.other_doc_id` are now strings. Consumers that previously joined
171
+ on integer IDs must cast their keys to string before upgrading. The former
172
+ mixed-schema `legacy` config is now exposed as the loadable `legacy_metadata`
173
+ and `legacy_content` configs.
174
+
175
+ See [CHANGELOG.md](CHANGELOG.md) for the complete release summary.
176
+
177
  ## Quick Start
178
 
179
  ```python
180
  from datasets import load_dataset
181
 
182
+ # Metadata for 171k documents
183
  meta = load_dataset("th1nhng0/vietnamese-legal-documents", "metadata", split="data")
184
  print(meta.to_pandas().head())
185
 
 
187
  rels = load_dataset("th1nhng0/vietnamese-legal-documents", "relationships", split="data")
188
  print(rels.to_pandas().head())
189
 
190
+ # Full-text HTML content for 170k documents
191
  content = load_dataset("th1nhng0/vietnamese-legal-documents", "content", split="data")
192
  print(content.to_pandas().head())
193
  ```
 
207
 
208
  ## Dataset Structure
209
 
210
+ The dataset has five configs:
211
 
212
  | Config | Split | Rows | Description |
213
  |---|---|---|---|
214
+ | `metadata` | `data` | 171,556 | One row per document — 17 metadata fields |
215
+ | `content` | `data` | 170,824 | One unique raw HTML body per document |
216
+ | `relationships` | `data` | 1,033,255 | Unique directed edges between documents |
217
+ | `legacy_metadata` | `metadata` | 518,601 | Older crawl — English field names, more docs |
218
+ | `legacy_content` | `content` | 518,235 | Plain-text content for older crawl |
219
 
220
  ### `metadata`
221
 
222
  | Column | Description |
223
  |---|---|
224
+ | `id` | Unique document ID (string; numeric, UUID, or portal-prefixed) |
225
  | `title` | Full Vietnamese title |
226
  | `so_ky_hieu` | Official number, e.g. `115/NQ-HĐBCQG` |
227
  | `ngay_ban_hanh` | Issuance date (`DD/MM/YYYY`) |
 
246
  | `id` | Document ID (join key → `metadata.id`) |
247
  | `content_html` | Raw HTML body of the document |
248
 
249
+ > **Note:** 732 metadata rows do not have a corresponding `content` row. The portal does not expose an HTML body for those records (some are PDF-only).
250
 
251
  ### `relationships`
252
 
 
254
  |---|---|
255
  | `doc_id` | Source document ID (join key → `metadata.id`) |
256
  | `other_doc_id` | Target document ID |
257
+ | `relationship` | Edge label from the current portal; archived old-only pairs retain their historical label |
258
 
259
+ Every `doc_id` is present in `metadata`. Relationship targets may reference
260
+ documents outside the live catalog; 17,706 distinct `other_doc_id` values do
261
+ not have a metadata row in this snapshot.
262
+
263
+ ### Legacy configs
264
 
265
  An older, larger crawl snapshot with ~518 k documents. Field names and enumerated values are in English (unlike the current configs which use Vietnamese originals). Dates are `YYYY-MM-DD`. Use this config when you need broader coverage at the cost of reduced metadata richness.
266
 
 
292
  ```python
293
  from datasets import load_dataset
294
 
295
+ legacy_meta = load_dataset("th1nhng0/vietnamese-legal-documents", "legacy_metadata", split="metadata")
296
+ legacy_content = load_dataset("th1nhng0/vietnamese-legal-documents", "legacy_content", split="content")
297
  ```
298
 
299
+ ## Data Collection
 
 
 
 
300
 
301
+ All data was scraped from [vbpl.vn](https://vbpl.vn) using the [Scrapy](https://scrapy.org/) crawler under [`crawler/`](crawler/). The single `vbpl` spider targets the current Next.js catalog and public JSON detail gateway, collecting metadata, HTML content, signers, fields, and relationships in one pass. IDs are strings because the migrated portal uses numeric IDs, UUIDs, and prefixed identifiers.
302
 
303
+ The current files were refreshed on 2026-07-23. Refresh rows are authoritative for overlapping IDs; missing refresh fields are filled from the prior dataset, and records no longer exposed by the live catalog are retained as historical rows.
304
 
305
+ For local rollback, the immediately preceding files are preserved under the
306
+ Git-ignored `data/archive_pre_refresh_2026-07-23/` directory.
307
 
308
  ```bash
309
  cd crawler
310
+ uv sync --extra validation
311
+
312
+ uv run scrapy crawl vbpl -a seed_file=data/ids.txt
313
+ uv run scrapy crawl vbpl -a seed_file=data/ids.txt -a proxy_file=proxies.txt
314
+ uv run scrapy crawl vbpl -a seed_file=data/ids.txt -a resume=1 -a resume_from=../data/metadata_raw.jsonl
315
+
316
+ # Crawl the complete catalog. This one pass includes metadata, relationships,
317
+ # and full-text HTML.
318
+ uv run scrapy crawl vbpl -a full=1 -a output=../data/metadata_raw.jsonl
319
+
320
+ # Safely continue an interrupted full crawl.
321
+ uv run scrapy crawl vbpl -a full=1 -a resume=1 -a resume_from=../data/metadata_raw.jsonl -a output=../data/metadata_raw.jsonl
322
+
323
+ # Stream the combined crawl into separate, versioned Parquet files.
324
+ uv run python build_full_dataset.py ../data/metadata_raw.jsonl ../data/refresh_YYYY-MM-DD
325
+
326
+ # Upsert a verified refresh into a staging directory. Refresh values win,
327
+ # missing values are recovered from the current data, and old-only rows remain.
328
+ uv run python upsert_dataset.py ../data/refresh_YYYY-MM-DD ../data/upsert_YYYY-MM-DD
329
 
330
+ # Validate card metadata, Parquet schemas/counts, uniqueness, and join integrity.
331
+ uv run --extra validation python validate_release.py ..
 
332
  ```
333
 
334
+ Both processing commands refuse to overwrite their output directory. Validate
335
+ the staged Parquet files before promoting them into `data/`.
336
 
337
  ## Limitations
338
 
339
  - Coverage depends on what [vbpl.vn](https://vbpl.vn) has indexed; older or undigitized documents may be missing.
340
+ - The live catalog can change during a long crawl. Use `-a resume=1` for a final catalog-only verification pass; zero newly scraped items means every currently listed ID is already present.
341
  - Effect status reflects the portal at crawl time and may lag behind real-world changes.
342
  - This is a snapshot, not a live mirror. Always cross-check with the portal for authoritative status.
343
 
 
361
 
362
  Vietnamese legal documents are **public domain** under the [Law on Access to Information (No. 104/2016/QH13)](https://chinhphu.vn/default.aspx?pageid=27160&docid=184568) and the [Law on Promulgation of Legal Documents (No. 64/2025/QH15)](https://chinhphu.vn/?pageid=27160&docid=213327&classid=1&typegroupid=3).
363
 
364
+ The compiled dataset (schema, processing, curation) is released under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Not a substitute for legal advice.
crawler/build_full_dataset.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stream a combined VBPL JSONL crawl into versioned Parquet datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import pyarrow as pa
10
+ import pyarrow.parquet as pq
11
+
12
+
13
+ METADATA_FIELDS = (
14
+ "id",
15
+ "title",
16
+ "so_ky_hieu",
17
+ "ngay_ban_hanh",
18
+ "loai_van_ban",
19
+ "ngay_co_hieu_luc",
20
+ "ngay_het_hieu_luc",
21
+ "nguon_thu_thap",
22
+ "ngay_dang_cong_bao",
23
+ "nganh",
24
+ "linh_vuc",
25
+ "co_quan_ban_hanh",
26
+ "chuc_danh",
27
+ "nguoi_ky",
28
+ "pham_vi",
29
+ "thong_tin_ap_dung",
30
+ "tinh_trang_hieu_luc",
31
+ "crawl_status",
32
+ )
33
+ METADATA_SCHEMA = pa.schema([(field, pa.string()) for field in METADATA_FIELDS])
34
+ CONTENT_SCHEMA = pa.schema([("id", pa.string()), ("content_html", pa.string())])
35
+ RELATIONSHIP_SCHEMA = pa.schema(
36
+ [
37
+ ("doc_id", pa.string()),
38
+ ("other_doc_id", pa.string()),
39
+ ("relationship", pa.string()),
40
+ ]
41
+ )
42
+
43
+
44
+ def flush(writer: pq.ParquetWriter, rows: list[dict], schema: pa.Schema) -> None:
45
+ if rows:
46
+ writer.write_table(pa.Table.from_pylist(rows, schema=schema))
47
+ rows.clear()
48
+
49
+
50
+ def build(input_path: Path, output_dir: Path, batch_size: int) -> dict[str, int]:
51
+ output_dir.mkdir(parents=True, exist_ok=True)
52
+ paths = {
53
+ "metadata": output_dir / "metadata.parquet",
54
+ "content": output_dir / "content.parquet",
55
+ "relationships": output_dir / "relationships.parquet",
56
+ }
57
+ for path in paths.values():
58
+ if path.exists():
59
+ raise FileExistsError(f"Refusing to overwrite {path}")
60
+
61
+ counts = {"metadata": 0, "content": 0, "relationships": 0}
62
+ metadata_rows: list[dict] = []
63
+ content_rows: list[dict] = []
64
+ relationship_rows: list[dict] = []
65
+
66
+ with (
67
+ pq.ParquetWriter(paths["metadata"], METADATA_SCHEMA, compression="zstd") as metadata_writer,
68
+ pq.ParquetWriter(paths["content"], CONTENT_SCHEMA, compression="zstd") as content_writer,
69
+ pq.ParquetWriter(
70
+ paths["relationships"], RELATIONSHIP_SCHEMA, compression="zstd"
71
+ ) as relationship_writer,
72
+ input_path.open("r", encoding="utf-8") as source,
73
+ ):
74
+ for line_number, line in enumerate(source, 1):
75
+ if not line.strip():
76
+ continue
77
+ try:
78
+ item = json.loads(line)
79
+ except json.JSONDecodeError as exc:
80
+ raise ValueError(f"Invalid JSON on line {line_number}") from exc
81
+
82
+ item["id"] = str(item["id"])
83
+ metadata_rows.append({field: item.get(field) for field in METADATA_FIELDS})
84
+ counts["metadata"] += 1
85
+
86
+ content = item.get("content")
87
+ if isinstance(content, str) and content.strip():
88
+ content_rows.append({"id": item["id"], "content_html": content})
89
+ counts["content"] += 1
90
+
91
+ for relationship, other_ids in (item.get("relationships") or {}).items():
92
+ for other_id in other_ids or ():
93
+ relationship_rows.append(
94
+ {
95
+ "doc_id": item["id"],
96
+ "other_doc_id": str(other_id),
97
+ "relationship": relationship,
98
+ }
99
+ )
100
+ counts["relationships"] += 1
101
+
102
+ if len(metadata_rows) >= batch_size:
103
+ flush(metadata_writer, metadata_rows, METADATA_SCHEMA)
104
+ flush(content_writer, content_rows, CONTENT_SCHEMA)
105
+ flush(relationship_writer, relationship_rows, RELATIONSHIP_SCHEMA)
106
+
107
+ flush(metadata_writer, metadata_rows, METADATA_SCHEMA)
108
+ flush(content_writer, content_rows, CONTENT_SCHEMA)
109
+ flush(relationship_writer, relationship_rows, RELATIONSHIP_SCHEMA)
110
+
111
+ return counts
112
+
113
+
114
+ def main() -> None:
115
+ parser = argparse.ArgumentParser()
116
+ parser.add_argument("input", type=Path)
117
+ parser.add_argument("output_dir", type=Path)
118
+ parser.add_argument("--batch-size", type=int, default=5_000)
119
+ args = parser.parse_args()
120
+ print(json.dumps(build(args.input, args.output_dir, args.batch_size), indent=2))
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
crawler/compare_content_text.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare visible text while ignoring HTML markup differences."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import html as html_module
7
+ import json
8
+ import re
9
+ import unicodedata
10
+ from pathlib import Path
11
+
12
+ import polars as pl
13
+
14
+
15
+ IGNORED_HTML = re.compile(
16
+ r"<(head|script|style|noscript)\b[^>]*>.*?</\1\s*>", re.IGNORECASE | re.DOTALL
17
+ )
18
+ COMMENTS = re.compile(r"<!--.*?-->", re.DOTALL)
19
+ TAGS = re.compile(r"<[^>]*>", re.DOTALL)
20
+
21
+
22
+ def normalized_text(value: str | None) -> str:
23
+ if not value:
24
+ return ""
25
+ text = IGNORED_HTML.sub(" ", value)
26
+ text = COMMENTS.sub(" ", text)
27
+ text = TAGS.sub(" ", text)
28
+ text = html_module.unescape(text).replace("\xa0", " ")
29
+ text = unicodedata.normalize("NFC", text)
30
+ return "".join(text.split()).casefold()
31
+
32
+
33
+ def main() -> None:
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument("new_content", type=Path)
36
+ parser.add_argument("current_content", type=Path)
37
+ parser.add_argument("--output", type=Path)
38
+ args = parser.parse_args()
39
+
40
+ new = (
41
+ pl.read_parquet(args.new_content)
42
+ .with_columns(pl.col("id").cast(pl.String))
43
+ .unique("id", keep="last")
44
+ )
45
+ current = (
46
+ pl.read_parquet(args.current_content)
47
+ .with_columns(pl.col("id").cast(pl.String))
48
+ .unique("id", keep="last")
49
+ )
50
+ shared = new.join(current, on="id", how="inner", suffix="_current")
51
+
52
+ exact = 0
53
+ changed = 0
54
+ for new_html, current_html in shared.select(
55
+ "content_html", "content_html_current"
56
+ ).iter_rows():
57
+ if normalized_text(new_html) == normalized_text(current_html):
58
+ exact += 1
59
+ else:
60
+ changed += 1
61
+
62
+ result = {
63
+ "shared_ids": shared.height,
64
+ "same_canonical_visible_text": exact,
65
+ "changed_canonical_visible_text": changed,
66
+ }
67
+ rendered = json.dumps(result, indent=2)
68
+ if args.output:
69
+ args.output.write_text(rendered + "\n", encoding="utf-8")
70
+ print(rendered)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
crawler/compare_datasets.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare a refreshed VBPL export with the repository's current datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+
10
+ import polars as pl
11
+
12
+
13
+ SHARED_METADATA_FIELDS = (
14
+ "title",
15
+ "so_ky_hieu",
16
+ "ngay_ban_hanh",
17
+ "loai_van_ban",
18
+ "ngay_co_hieu_luc",
19
+ "ngay_het_hieu_luc",
20
+ "ngay_dang_cong_bao",
21
+ "nganh",
22
+ "linh_vuc",
23
+ "co_quan_ban_hanh",
24
+ "chuc_danh",
25
+ "nguoi_ky",
26
+ "pham_vi",
27
+ "tinh_trang_hieu_luc",
28
+ )
29
+
30
+
31
+ def load(path: Path) -> pl.DataFrame:
32
+ return pl.read_parquet(path).with_columns(pl.col("id").cast(pl.String))
33
+
34
+
35
+ def unique_ids(frame: pl.DataFrame) -> pl.DataFrame:
36
+ return frame.unique("id", keep="last")
37
+
38
+
39
+ def count_join(left: pl.DataFrame, right: pl.DataFrame, how: str) -> int:
40
+ return left.select("id").join(right.select("id"), on="id", how=how).height
41
+
42
+
43
+ def id_shape(value: str) -> str:
44
+ if value.isdigit():
45
+ return "numeric"
46
+ if re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", value, re.I):
47
+ return "uuid"
48
+ prefix = re.sub(r"\d+$", "", value)
49
+ return prefix or "other"
50
+
51
+
52
+ def bridge_by_number_and_date(new: pl.DataFrame, old: pl.DataFrame) -> int:
53
+ def keyed(frame: pl.DataFrame) -> pl.DataFrame:
54
+ return (
55
+ frame.with_columns(
56
+ pl.concat_str(
57
+ pl.col("so_ky_hieu").fill_null("").str.strip_chars().str.to_lowercase(),
58
+ pl.lit("|"),
59
+ pl.col("ngay_ban_hanh").fill_null("").str.strip_chars(),
60
+ ).alias("key")
61
+ )
62
+ .filter(pl.col("key") != "|")
63
+ .group_by("key")
64
+ .agg(pl.col("id"))
65
+ .filter(pl.col("id").list.len() == 1)
66
+ .with_columns(pl.col("id").list.first())
67
+ )
68
+
69
+ new_only = new.join(old.select("id"), on="id", how="anti")
70
+ old_only = old.join(new.select("id"), on="id", how="anti")
71
+ return keyed(new_only).join(keyed(old_only), on="key", how="inner").height
72
+
73
+
74
+ def compare(args: argparse.Namespace) -> dict:
75
+ new_meta_raw = load(args.new_dir / "metadata.parquet")
76
+ old_meta_raw = load(args.current_dir / "metadata.parquet")
77
+ new_meta = unique_ids(new_meta_raw)
78
+ old_meta = unique_ids(old_meta_raw)
79
+
80
+ shared = new_meta.join(old_meta, on="id", how="inner", suffix="_old")
81
+ field_changes = {}
82
+ changed_expressions = []
83
+ for field in SHARED_METADATA_FIELDS:
84
+ changed = (
85
+ pl.col(field).fill_null("").str.strip_chars()
86
+ != pl.col(f"{field}_old").fill_null("").str.strip_chars()
87
+ )
88
+ field_changes[field] = shared.select(changed.sum()).item()
89
+ changed_expressions.append(changed)
90
+
91
+ changed_shared_rows = shared.select(pl.any_horizontal(changed_expressions).sum()).item()
92
+ null_coverage = {}
93
+ for field in SHARED_METADATA_FIELDS:
94
+ missing = pl.col(field).is_null() | (pl.col(field).str.strip_chars() == "")
95
+ old_missing = pl.col(f"{field}_old").is_null() | (
96
+ pl.col(f"{field}_old").str.strip_chars() == ""
97
+ )
98
+ null_coverage[field] = {
99
+ "new_missing_on_shared_ids": shared.select(missing.sum()).item(),
100
+ "current_missing_on_shared_ids": shared.select(old_missing.sum()).item(),
101
+ }
102
+ shapes = {}
103
+ for value in new_meta["id"]:
104
+ shape = id_shape(value)
105
+ shapes[shape] = shapes.get(shape, 0) + 1
106
+
107
+ new_content_raw = load(args.new_dir / "content.parquet")
108
+ old_content_raw = load(args.current_dir / "content.parquet")
109
+ new_content = unique_ids(new_content_raw)
110
+ old_content = unique_ids(old_content_raw)
111
+ content_shared = new_content.join(old_content, on="id", how="inner", suffix="_old")
112
+ content_equal = content_shared.select(
113
+ (pl.col("content_html") == pl.col("content_html_old")).sum()
114
+ ).item()
115
+
116
+ new_rel = pl.read_parquet(args.new_dir / "relationships.parquet").with_columns(
117
+ pl.col("doc_id").cast(pl.String), pl.col("other_doc_id").cast(pl.String)
118
+ )
119
+ old_rel = pl.read_parquet(args.current_dir / "relationships.parquet").with_columns(
120
+ pl.col("doc_id").cast(pl.String), pl.col("other_doc_id").cast(pl.String)
121
+ )
122
+ rel_keys = ["doc_id", "other_doc_id", "relationship"]
123
+ new_rel_unique = new_rel.unique(rel_keys)
124
+ old_rel_unique = old_rel.unique(rel_keys)
125
+ shared_edges = new_rel_unique.join(old_rel_unique, on=rel_keys, how="inner").height
126
+ pair_keys = ["doc_id", "other_doc_id"]
127
+ new_pairs = new_rel_unique.unique(pair_keys)
128
+ old_pairs = old_rel_unique.unique(pair_keys)
129
+ shared_pairs = new_pairs.join(old_pairs, on=pair_keys, how="inner").height
130
+
131
+ legacy_meta = load(args.legacy_dir / "metadata.parquet")
132
+ legacy_content = load(args.legacy_dir / "content.parquet")
133
+ return {
134
+ "metadata": {
135
+ "new_rows": new_meta_raw.height,
136
+ "new_unique_ids": new_meta.height,
137
+ "new_duplicate_rows": new_meta_raw.height - new_meta.height,
138
+ "current_rows": old_meta_raw.height,
139
+ "current_unique_ids": old_meta.height,
140
+ "exact_id_overlap": count_join(new_meta, old_meta, "inner"),
141
+ "new_only_ids": count_join(new_meta, old_meta, "anti"),
142
+ "current_only_ids": count_join(old_meta, new_meta, "anti"),
143
+ "unique_number_date_matches_with_changed_id": bridge_by_number_and_date(
144
+ new_meta, old_meta
145
+ ),
146
+ "shared_rows_with_any_field_change": changed_shared_rows,
147
+ "field_change_counts": field_changes,
148
+ "missing_value_counts_on_shared_ids": null_coverage,
149
+ "new_id_shapes": dict(sorted(shapes.items())),
150
+ },
151
+ "content": {
152
+ "new_rows": new_content_raw.height,
153
+ "new_unique_ids": new_content.height,
154
+ "current_rows": old_content_raw.height,
155
+ "current_unique_ids": old_content.height,
156
+ "exact_id_overlap": content_shared.height,
157
+ "exact_html_matches": content_equal,
158
+ "changed_html": content_shared.height - content_equal,
159
+ "new_only_ids": count_join(new_content, old_content, "anti"),
160
+ "current_only_ids": count_join(old_content, new_content, "anti"),
161
+ },
162
+ "relationships": {
163
+ "new_rows": new_rel.height,
164
+ "new_unique_edges": new_rel_unique.height,
165
+ "current_rows": old_rel.height,
166
+ "current_unique_edges": old_rel_unique.height,
167
+ "exact_edge_overlap": shared_edges,
168
+ "document_pair_overlap_ignoring_label": shared_pairs,
169
+ "new_only_edges": new_rel_unique.height - shared_edges,
170
+ "current_only_edges": old_rel_unique.height - shared_edges,
171
+ },
172
+ "legacy": {
173
+ "metadata_rows": legacy_meta.height,
174
+ "metadata_exact_id_overlap_with_new": count_join(new_meta, unique_ids(legacy_meta), "inner"),
175
+ "content_rows": legacy_content.height,
176
+ "content_exact_id_overlap_with_new": count_join(
177
+ new_content, unique_ids(legacy_content), "inner"
178
+ ),
179
+ },
180
+ }
181
+
182
+
183
+ def main() -> None:
184
+ parser = argparse.ArgumentParser()
185
+ parser.add_argument("new_dir", type=Path)
186
+ parser.add_argument("--current-dir", type=Path, default=Path("../data"))
187
+ parser.add_argument("--legacy-dir", type=Path, default=Path("../legacy"))
188
+ parser.add_argument("--output", type=Path)
189
+ args = parser.parse_args()
190
+ result = compare(args)
191
+ rendered = json.dumps(result, ensure_ascii=False, indent=2)
192
+ if args.output:
193
+ args.output.write_text(rendered + "\n", encoding="utf-8")
194
+ print(rendered)
195
+
196
+
197
+ if __name__ == "__main__":
198
+ main()
crawler/helper.py DELETED
@@ -1,58 +0,0 @@
1
- import pandas as pd
2
- import json
3
- import re
4
- import polars as pl
5
-
6
-
7
- def metadata_process():
8
- df = pd.read_json("raw.jsonl", lines=True)
9
- df = df.drop(columns=["content"])
10
-
11
- # Export metadata parquet (without relationships)
12
- metadata_df = df.drop(columns=["relationships"])
13
- metadata_df.to_parquet("metadata.parquet", index=False)
14
- print(f"✓ Exported metadata.parquet with shape {metadata_df.shape}")
15
-
16
- # Build relationships dataframe
17
- relationships_records = []
18
-
19
- for doc_id, relationships_json in zip(df["id"], df["relationships"]):
20
- rel_obj = (
21
- json.loads(relationships_json)
22
- if isinstance(relationships_json, str)
23
- else relationships_json
24
- )
25
-
26
- for rel_type, other_ids in rel_obj.items():
27
- # Remove count from relationship type: "Văn bản căn cứ (1)" -> "Văn bản căn cứ"
28
- cleaned_rel_type = re.sub(r"\s*\(\d+\)\s*$", "", rel_type)
29
-
30
- # other_ids is a list
31
- for other_id in other_ids:
32
- relationships_records.append(
33
- {
34
- "doc_id": doc_id,
35
- "other_doc_id": other_id,
36
- "relationship": cleaned_rel_type,
37
- }
38
- )
39
-
40
- relationships_df = pd.DataFrame(relationships_records)
41
- # other_doc_id should be int too
42
- relationships_df["other_doc_id"] = relationships_df["other_doc_id"].astype(int)
43
- relationships_df.to_parquet("relationships.parquet", index=False)
44
- print(f"✓ Exported relationships.parquet with shape {relationships_df.shape}")
45
-
46
- print(f"\nRelationship types found:")
47
- print(relationships_df["relationship"].value_counts())
48
-
49
-
50
- def content_process():
51
- # scan_ndjson is lazy; sink_parquet streams the result directly to disk
52
- pl.scan_ndjson("../data/raw.jsonl").sink_parquet("../data/content.parquet")
53
- print("✓ Exported content.parquet via streaming")
54
-
55
-
56
- if __name__ == "__main__":
57
- # metadata_process()
58
- content_process()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
crawler/pyproject.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "vbpl-crawler"
3
+ version = "2.0.0"
4
+ description = "Crawler and release tooling for the Vietnamese Legal Documents dataset"
5
+ requires-python = ">=3.11"
6
+ dependencies = [
7
+ "polars>=1.20",
8
+ "pyarrow>=18",
9
+ "scrapy>=2.13",
10
+ ]
11
+
12
+ [project.optional-dependencies]
13
+ validation = [
14
+ "datasets>=4",
15
+ "huggingface-hub>=0.30",
16
+ ]
17
+
18
+ [dependency-groups]
19
+ dev = ["ruff>=0.12"]
20
+
21
+ [tool.uv]
22
+ package = false
23
+
24
+ [tool.ruff]
25
+ target-version = "py311"
crawler/upsert_dataset.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Merge a verified VBPL refresh into the published Parquet datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import polars as pl
10
+ import pyarrow as pa
11
+ import pyarrow.compute as pc
12
+ import pyarrow.parquet as pq
13
+
14
+
15
+ METADATA_FIELDS = (
16
+ "id",
17
+ "title",
18
+ "so_ky_hieu",
19
+ "ngay_ban_hanh",
20
+ "loai_van_ban",
21
+ "ngay_co_hieu_luc",
22
+ "ngay_het_hieu_luc",
23
+ "nguon_thu_thap",
24
+ "ngay_dang_cong_bao",
25
+ "nganh",
26
+ "linh_vuc",
27
+ "co_quan_ban_hanh",
28
+ "chuc_danh",
29
+ "nguoi_ky",
30
+ "pham_vi",
31
+ "thong_tin_ap_dung",
32
+ "tinh_trang_hieu_luc",
33
+ )
34
+ RELATIONSHIP_PAIR = ("doc_id", "other_doc_id")
35
+
36
+
37
+ def string_columns(fields: tuple[str, ...]) -> list[pl.Expr]:
38
+ return [pl.col(field).cast(pl.String, strict=False) for field in fields]
39
+
40
+
41
+ def write_huggingface_parquet(
42
+ frame: pl.LazyFrame,
43
+ output_path: Path,
44
+ fields: tuple[str, ...],
45
+ batch_size: int = 5_000,
46
+ ) -> None:
47
+ """Write bounded Arrow string row groups that ``datasets`` can load."""
48
+ intermediate = output_path.with_name(f".{output_path.name}.polars")
49
+ frame.sink_parquet(intermediate, compression="zstd")
50
+
51
+ schema = pa.schema([(field, pa.string()) for field in fields])
52
+ with pq.ParquetWriter(output_path, schema, compression="zstd") as writer:
53
+ parquet = pq.ParquetFile(intermediate)
54
+ for batch in parquet.iter_batches(batch_size=batch_size, columns=list(fields)):
55
+ table = pa.Table.from_arrays(
56
+ [pc.cast(batch.column(field), pa.string()) for field in fields],
57
+ schema=schema,
58
+ )
59
+ writer.write_table(table, row_group_size=batch_size)
60
+ parquet.close()
61
+
62
+ intermediate.unlink()
63
+
64
+
65
+ def upsert_metadata(current_dir: Path, refresh_dir: Path, output_dir: Path) -> None:
66
+ current = (
67
+ pl.scan_parquet(current_dir / "metadata.parquet")
68
+ .select(string_columns(METADATA_FIELDS))
69
+ .unique("id", keep="last")
70
+ )
71
+ refresh = (
72
+ pl.scan_parquet(refresh_dir / "metadata.parquet")
73
+ .select(string_columns(METADATA_FIELDS))
74
+ .unique("id", keep="last")
75
+ )
76
+
77
+ current_values = current.rename(
78
+ {field: f"{field}_current" for field in METADATA_FIELDS if field != "id"}
79
+ )
80
+ joined = refresh.join(current_values, on="id", how="left")
81
+ merged_refresh = joined.select(
82
+ pl.col("id"),
83
+ *[
84
+ pl.when(pl.col(field).is_null() | (pl.col(field).str.strip_chars() == ""))
85
+ .then(pl.col(f"{field}_current"))
86
+ .otherwise(pl.col(field))
87
+ .alias(field)
88
+ for field in METADATA_FIELDS
89
+ if field != "id"
90
+ ],
91
+ )
92
+ current_only = current.join(refresh.select("id"), on="id", how="anti")
93
+ write_huggingface_parquet(
94
+ pl.concat([merged_refresh, current_only], how="vertical"),
95
+ output_dir / "metadata.parquet",
96
+ METADATA_FIELDS,
97
+ )
98
+
99
+
100
+ def upsert_content(current_dir: Path, refresh_dir: Path, output_dir: Path) -> None:
101
+ current = (
102
+ pl.scan_parquet(current_dir / "content.parquet")
103
+ .select(pl.col("id").cast(pl.String), pl.col("content_html"))
104
+ .unique("id", keep="last")
105
+ )
106
+ refresh = (
107
+ pl.scan_parquet(refresh_dir / "content.parquet")
108
+ .select(pl.col("id").cast(pl.String), pl.col("content_html"))
109
+ .unique("id", keep="last")
110
+ )
111
+ current_only = current.join(refresh.select("id"), on="id", how="anti")
112
+ write_huggingface_parquet(
113
+ pl.concat([refresh, current_only], how="vertical"),
114
+ output_dir / "content.parquet",
115
+ ("id", "content_html"),
116
+ )
117
+
118
+
119
+ def upsert_relationships(
120
+ current_dir: Path, refresh_dir: Path, output_dir: Path
121
+ ) -> None:
122
+ columns = ("doc_id", "other_doc_id", "relationship")
123
+ current = (
124
+ pl.scan_parquet(current_dir / "relationships.parquet")
125
+ .select(string_columns(columns))
126
+ .unique(columns)
127
+ )
128
+ refresh = (
129
+ pl.scan_parquet(refresh_dir / "relationships.parquet")
130
+ .select(string_columns(columns))
131
+ .unique(columns)
132
+ )
133
+
134
+ # The new portal renamed relationship labels. New edges therefore replace
135
+ # every old label for the same directed document pair. Only pairs absent
136
+ # from the current portal are retained with their historical labels.
137
+ refresh_pairs = refresh.select(RELATIONSHIP_PAIR).unique()
138
+ current_only_pairs = current.join(
139
+ refresh_pairs, on=RELATIONSHIP_PAIR, how="anti"
140
+ )
141
+ write_huggingface_parquet(
142
+ pl.concat([refresh, current_only_pairs], how="vertical").unique(columns),
143
+ output_dir / "relationships.parquet",
144
+ columns,
145
+ )
146
+
147
+
148
+ def row_counts(output_dir: Path) -> dict[str, int]:
149
+ return {
150
+ name: pl.scan_parquet(output_dir / f"{name}.parquet")
151
+ .select(pl.len())
152
+ .collect()
153
+ .item()
154
+ for name in ("metadata", "content", "relationships")
155
+ }
156
+
157
+
158
+ def main() -> None:
159
+ parser = argparse.ArgumentParser()
160
+ parser.add_argument("refresh_dir", type=Path)
161
+ parser.add_argument("output_dir", type=Path)
162
+ parser.add_argument("--current-dir", type=Path, default=Path("../data"))
163
+ args = parser.parse_args()
164
+
165
+ if args.output_dir.exists():
166
+ raise FileExistsError(f"Refusing to overwrite {args.output_dir}")
167
+ args.output_dir.mkdir(parents=True)
168
+
169
+ upsert_metadata(args.current_dir, args.refresh_dir, args.output_dir)
170
+ upsert_content(args.current_dir, args.refresh_dir, args.output_dir)
171
+ upsert_relationships(args.current_dir, args.refresh_dir, args.output_dir)
172
+ print(json.dumps(row_counts(args.output_dir), indent=2))
173
+
174
+
175
+ if __name__ == "__main__":
176
+ main()
crawler/uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
crawler/validate_release.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the local Hugging Face dataset release before publishing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import polars as pl
10
+ import pyarrow.parquet as pq
11
+ from huggingface_hub import DatasetCard
12
+
13
+
14
+ CONFIG_PATHS = {
15
+ "metadata": ("data/metadata.parquet", "data"),
16
+ "relationships": ("data/relationships.parquet", "data"),
17
+ "content": ("data/content.parquet", "data"),
18
+ "legacy_metadata": ("legacy/metadata.parquet", "metadata"),
19
+ "legacy_content": ("legacy/content.parquet", "content"),
20
+ }
21
+
22
+
23
+ def validate(root: Path) -> dict[str, dict[str, int]]:
24
+ card = DatasetCard.load(root / "README.md")
25
+ card.validate()
26
+ metadata = card.data.to_dict()
27
+ infos = {item["config_name"]: item for item in metadata["dataset_info"]}
28
+ configs = {item["config_name"]: item for item in metadata["configs"]}
29
+ assert set(infos) == set(CONFIG_PATHS)
30
+ assert set(configs) == set(CONFIG_PATHS)
31
+
32
+ result = {}
33
+ for name, (relative_path, split_name) in CONFIG_PATHS.items():
34
+ path = root / relative_path
35
+ parquet = pq.ParquetFile(path)
36
+ info = infos[name]
37
+ split = next(item for item in info["splits"] if item["name"] == split_name)
38
+ card_path = configs[name]["data_files"][0]["path"]
39
+ feature_types = {
40
+ feature["name"]: feature["dtype"] for feature in info["features"]
41
+ }
42
+ parquet_types = {
43
+ field.name: str(field.type) for field in parquet.schema_arrow
44
+ }
45
+ assert card_path == relative_path
46
+ assert split["num_examples"] == parquet.metadata.num_rows
47
+ assert info["download_size"] == path.stat().st_size
48
+ assert feature_types == parquet_types
49
+ result[name] = {
50
+ "rows": parquet.metadata.num_rows,
51
+ "download_size": path.stat().st_size,
52
+ }
53
+ parquet.close()
54
+
55
+ frames = {
56
+ name: pl.scan_parquet(root / relative_path)
57
+ for name, (relative_path, _) in CONFIG_PATHS.items()
58
+ if name in {"metadata", "content", "relationships"}
59
+ }
60
+ metadata_ids = frames["metadata"].select("id")
61
+ content_ids = frames["content"].select("id")
62
+ relationship_sources = frames["relationships"].select(
63
+ pl.col("doc_id").alias("id")
64
+ )
65
+ assert metadata_ids.select(pl.len()).collect().item() == metadata_ids.unique().select(
66
+ pl.len()
67
+ ).collect().item()
68
+ assert content_ids.select(pl.len()).collect().item() == content_ids.unique().select(
69
+ pl.len()
70
+ ).collect().item()
71
+ assert frames["relationships"].select(pl.len()).collect().item() == frames[
72
+ "relationships"
73
+ ].unique().select(pl.len()).collect().item()
74
+ assert content_ids.join(metadata_ids, on="id", how="anti").collect().is_empty()
75
+ assert relationship_sources.join(
76
+ metadata_ids, on="id", how="anti"
77
+ ).collect().is_empty()
78
+ return result
79
+
80
+
81
+ def main() -> None:
82
+ parser = argparse.ArgumentParser()
83
+ parser.add_argument("root", type=Path, nargs="?", default=Path(".."))
84
+ args = parser.parse_args()
85
+ print(json.dumps(validate(args.root.resolve()), indent=2))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
crawler/vbpl/api.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for the public VBPL JSON API and catalog action."""
2
+
3
+ import json
4
+ import re
5
+ from datetime import datetime
6
+
7
+
8
+ BASE_URL = "https://vbpl-bientap-gateway.moj.gov.vn/api"
9
+ DOCUMENT_URL_TEMPLATE = f"{BASE_URL}/qtdc/public/doc/{{}}"
10
+ CATALOG_URL = "https://vbpl.vn/van-ban/trung-uong"
11
+
12
+ # The portal keeps catalog search behind a Next.js server action. This value can
13
+ # be overridden with ``-a catalog_action_id=...`` after a future deployment.
14
+ CATALOG_ACTION_ID = "c529d164f28418e5898a834422629e64c6816af1"
15
+
16
+
17
+ def feed_settings(output_path):
18
+ """Build an explicit single-file Scrapy feed configuration."""
19
+ return {
20
+ output_path: {
21
+ "format": "jsonlines",
22
+ "encoding": "utf-8",
23
+ "overwrite": False,
24
+ }
25
+ }
26
+
27
+ # Official relationship labels used by the current VBPL frontend.
28
+ REFERENCE_TYPES = {
29
+ 1: "Bãi bỏ",
30
+ 2: "Bản dịch",
31
+ 3: "Căn cứ",
32
+ 4: "Dẫn chiếu",
33
+ 5: "Đình chỉ thi hành",
34
+ 6: "Đính chính",
35
+ 7: "Hợp nhất",
36
+ 8: "Hướng dẫn áp dụng",
37
+ 9: "Quy định chi tiết, hướng dẫn thi hành",
38
+ 10: "Sửa đổi, bổ sung",
39
+ 11: "Tạm ngưng hiệu lực",
40
+ 12: "Thay thế",
41
+ 13: "Bổ sung",
42
+ 14: "Giải thích",
43
+ 15: "Công bố",
44
+ }
45
+
46
+
47
+ def unwrap_document(payload):
48
+ """Return document data from a successful gateway response."""
49
+ if not isinstance(payload, dict) or payload.get("success") is not True:
50
+ return None
51
+ data = payload.get("data")
52
+ return data if isinstance(data, dict) else None
53
+
54
+
55
+ def format_date(value):
56
+ """Convert an API ISO datetime to the dataset's DD/MM/YYYY format."""
57
+ if not value:
58
+ return None
59
+ try:
60
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).strftime("%d/%m/%Y")
61
+ except (TypeError, ValueError):
62
+ return value
63
+
64
+
65
+ def join_unique(values):
66
+ """Join non-empty values while preserving their original order."""
67
+ unique = []
68
+ for value in values:
69
+ if value and value not in unique:
70
+ unique.append(value)
71
+ return ", ".join(unique) if unique else None
72
+
73
+
74
+ def catalog_body(page_number, page_size):
75
+ """Build the argument array expected by the portal's catalog action."""
76
+ return json.dumps(
77
+ [{"pageNumber": page_number, "pageSize": page_size}],
78
+ ensure_ascii=False,
79
+ separators=(",", ":"),
80
+ )
81
+
82
+
83
+ def unwrap_catalog(response_text):
84
+ """Extract catalog JSON from a Next.js React Server Components response."""
85
+ decoder = json.JSONDecoder()
86
+ # Large RSC strings use length-prefixed chunks, so the following JSON chunk
87
+ # is not necessarily line-aligned (for example ``...title1:{...}``).
88
+ for marker in re.finditer(r"[0-9a-f]+:(?=\{)", response_text):
89
+ try:
90
+ payload, _ = decoder.raw_decode(response_text, marker.end())
91
+ except json.JSONDecodeError:
92
+ continue
93
+ if isinstance(payload, dict) and isinstance(payload.get("items"), list):
94
+ return payload
95
+ return None
crawler/vbpl/items.py DELETED
@@ -1,11 +0,0 @@
1
- """Item definitions for the VBPL crawler."""
2
-
3
- import scrapy
4
-
5
-
6
- class VbplItem(scrapy.Item):
7
- """Optional structured item model.
8
-
9
- The current spider yields plain dictionaries for flexibility.
10
- Keep this class for teams that prefer explicit Scrapy item schemas.
11
- """
 
 
 
 
 
 
 
 
 
 
 
 
crawler/vbpl/pipelines.py DELETED
@@ -1,11 +0,0 @@
1
- """Pipelines for post-processing scraped items."""
2
-
3
-
4
- class VbplPipeline:
5
- """Pass-through pipeline.
6
-
7
- Enable in settings when you need centralized item validation or cleanup.
8
- """
9
-
10
- def process_item(self, item, spider):
11
- return item
 
 
 
 
 
 
 
 
 
 
 
 
crawler/vbpl/settings.py CHANGED
@@ -16,9 +16,10 @@ RANDOMIZE_DOWNLOAD_DELAY = False
16
 
17
  COOKIES_ENABLED = False
18
 
19
- # Proxy middleware is disabled by default.
20
- # Pass -a proxy_file=<path> to the spider to enable it.
21
- DOWNLOADER_MIDDLEWARES = {}
 
22
 
23
  USER_AGENT = (
24
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
@@ -32,7 +33,7 @@ FEED_EXPORT_ENCODING = "utf-8"
32
 
33
  # Output goes to the dataset data/ folder (one level up from crawler/).
34
  FEEDS = {
35
- "../data/raw.jsonl": {
36
  "format": "jsonlines",
37
  "encoding": "utf-8",
38
  "overwrite": False,
 
16
 
17
  COOKIES_ENABLED = False
18
 
19
+ # The spider removes this middleware unless ``-a proxy_file=<path>`` is passed.
20
+ DOWNLOADER_MIDDLEWARES = {
21
+ "vbpl.middlewares.RotatingProxyMiddleware": 610,
22
+ }
23
 
24
  USER_AGENT = (
25
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
 
33
 
34
  # Output goes to the dataset data/ folder (one level up from crawler/).
35
  FEEDS = {
36
+ "../data/metadata_raw.jsonl": {
37
  "format": "jsonlines",
38
  "encoding": "utf-8",
39
  "overwrite": False,
crawler/vbpl/spiders/vbpl.py CHANGED
@@ -1,30 +1,43 @@
1
  import json
2
- import re
 
3
  from pathlib import Path
4
- from urllib.parse import parse_qs, urlparse
5
 
6
  import scrapy
7
 
8
- # Base URLs for dynamic construction
9
- BASE_URL = "https://vbpl.vn"
10
- METADATA_URL_TEMPLATE = f"{BASE_URL}/TW/Pages/vbpq-thuoctinh.aspx?ItemID={{}}"
11
- LUOCDO_URL_TEMPLATE = f"{BASE_URL}/ninhbinh/Pages/vbpq-luocdo.aspx?ItemID={{}}"
 
 
 
 
 
 
 
 
12
 
13
 
14
  class VbplSpider(scrapy.Spider):
15
- """Crawl VBPL metadata pages and relationship graph from seed ItemIDs."""
16
 
17
  name = "vbpl"
18
 
19
  @classmethod
20
  def from_crawler(cls, crawler, *args, **kwargs):
21
  proxy_file = kwargs.get("proxy_file")
 
 
 
22
  if proxy_file:
23
  crawler.settings.set("PROXY_LIST_FILE", proxy_file, priority="spider")
24
  else:
25
- mw = dict(crawler.settings.getwithbase("DOWNLOADER_MIDDLEWARES"))
26
- mw.pop("vbpl.middlewares.RotatingProxyMiddleware", None)
27
- crawler.settings.set("DOWNLOADER_MIDDLEWARES", mw, priority="spider")
 
 
28
  return super().from_crawler(crawler, *args, **kwargs)
29
 
30
  def __init__(
@@ -34,11 +47,21 @@ class VbplSpider(scrapy.Spider):
34
  proxy_file=None,
35
  resume=0,
36
  resume_from="data.jsonl",
 
 
 
 
 
37
  *args,
38
  **kwargs,
39
  ):
40
  super().__init__(*args, **kwargs)
41
  self.proxy_file = proxy_file
 
 
 
 
 
42
  if seed_file:
43
  self.seed_ids = [
44
  line.strip()
@@ -47,19 +70,19 @@ class VbplSpider(scrapy.Spider):
47
  ]
48
  else:
49
  self.seed_ids = [item_id.strip() for item_id in str(seed_ids).split(",")]
 
50
  self.seen_ids = set()
51
  if int(resume):
52
  resume_path = Path(resume_from)
53
  if resume_path.exists():
54
- for line in resume_path.read_text(encoding="utf-8").splitlines():
55
- line = line.strip()
56
- if line:
57
  try:
58
  item = json.loads(line)
59
- if "id" in item:
60
- self.seen_ids.add(str(item["id"]))
61
  except json.JSONDecodeError:
62
- pass
 
 
63
  self.logger.info(
64
  "Resume mode: loaded %d already-scraped IDs from %s",
65
  len(self.seen_ids),
@@ -67,147 +90,208 @@ class VbplSpider(scrapy.Spider):
67
  )
68
 
69
  async def start(self):
70
- """Scrapy 2.13+ entry point when custom start_requests() is used."""
71
  for request in self.start_requests():
72
  yield request
73
 
74
  def start_requests(self):
75
- """Start crawling from seed IDs."""
 
 
76
  for item_id in self.seed_ids:
77
- self.seen_ids.add(item_id)
78
- yield scrapy.Request(
79
- METADATA_URL_TEMPLATE.format(item_id),
80
- callback=self.parse_metadata,
81
- cb_kwargs={"doc_id": item_id, "content_html": None},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  )
 
83
 
84
- def _request_if_new(self, item_id):
85
- """Return a Request for item_id if not already seen, else None."""
86
- if item_id not in self.seen_ids:
87
- self.seen_ids.add(item_id)
88
- return scrapy.Request(
89
- METADATA_URL_TEMPLATE.format(item_id),
90
- callback=self.parse_metadata,
91
- cb_kwargs={"doc_id": item_id, "content_html": None},
 
 
 
92
  )
 
 
93
 
94
- @staticmethod
95
- def clean_text(extracted_data):
96
- """Helper to clean up whitespace, tabs, and newlines from HTML text."""
97
- if not extracted_data:
 
 
 
 
98
  return None
99
- if isinstance(extracted_data, str):
100
- return extracted_data.strip()
101
-
102
- cleaned = [text.strip() for text in extracted_data if text.strip()]
103
- return " ".join(cleaned) if cleaned else None
104
-
105
- def _get_table_value(self, response, label_name, offset=1):
106
- """Helper to extract values from the metadata table based on the label."""
107
- xpath_query = f'//td[contains(text(), "{label_name}")]/following-sibling::td[{offset}]//text()'
108
- return self.clean_text(response.xpath(xpath_query).getall())
109
-
110
- def parse_metadata(self, response, doc_id, content_html=None):
111
- """Extract metadata and continue to relationship page for the same document."""
112
- if "vbpq-thuoctinh.aspx" in response.url:
113
- title = self.clean_text(
114
- response.xpath(
115
- '(//div[@class="vbProperties"]//td[@class="title"])[1]//text()'
116
- ).getall()
117
- )
118
 
119
- if title:
120
- item_data = {
121
- "id": doc_id,
122
- "title": title,
123
- "so_ky_hieu": self._get_table_value(response, "Số ký hiệu"),
124
- "ngay_ban_hanh": self._get_table_value(response, "Ngày ban hành"),
125
- "loai_van_ban": self._get_table_value(response, "Loại văn bản"),
126
- "ngay_co_hieu_luc": self._get_table_value(
127
- response, "Ngày có hiệu lực"
128
- ),
129
- "ngay_het_hieu_luc": self._get_table_value(
130
- response, "Ngày hết hiệu lực"
131
- ),
132
- "nguon_thu_thap": self._get_table_value(
133
- response, "Nguồn thu thập"
134
- ),
135
- "ngay_dang_cong_bao": self._get_table_value(
136
- response, "Ngày đăng công báo"
137
- ),
138
- "nganh": self._get_table_value(response, "Ngành"),
139
- "linh_vuc": self._get_table_value(response, "Lĩnh vực"),
140
- "co_quan_ban_hanh": self._get_table_value(
141
- response, "Cơ quan ban hành"
142
- ),
143
- "chuc_danh": self._get_table_value(
144
- response, "Cơ quan ban hành", offset=2
145
- ),
146
- "nguoi_ky": self._get_table_value(
147
- response, "Cơ quan ban hành", offset=3
148
- ),
149
- "pham_vi": self._get_table_value(response, "Phạm vi"),
150
- "thong_tin_ap_dung": self._get_table_value(
151
- response, "Thông tin áp dụng"
152
- ),
153
- "tinh_trang_hieu_luc": self.clean_text(
154
- response.xpath(
155
- '//div[@class="vbInfo"]//li[@class="red"]/text()'
156
- ).get()
157
- ),
158
- "content": content_html,
159
- }
160
-
161
- # Fetch the relationship graph block for linked documents.
162
- yield scrapy.Request(
163
- url=LUOCDO_URL_TEMPLATE.format(doc_id),
164
- callback=self.parse_luocdo,
165
- cb_kwargs={"item_data": item_data},
166
  )
167
  else:
168
- self.logger.debug("Skipping %s: missing document title", doc_id)
169
- else:
170
- self.logger.debug("Skipping non-metadata page: %s", response.url)
171
-
172
- def parse_luocdo(self, response, item_data):
173
- """Step 3: Extract document relationships and yield the final item."""
174
- if "vbpq-luocdo.aspx" in response.url:
175
- relationships = {}
176
- blocks = response.xpath('//div[contains(@class, "luocdo")]')
177
-
178
- for block in blocks:
179
- title_nodes = block.xpath(
180
- './/div[starts-with(@class, "title")]//text()'
181
- ).getall()
182
- raw_title = " ".join(
183
- [text.strip() for text in title_nodes if text.strip() != "\xa0"]
184
  )
185
- rel_title = re.sub(r"\s*\(\d+\)$", "", raw_title).strip()
186
-
187
- doc_items = block.xpath('.//div[@class="content"]//li')
188
- if not doc_items:
189
- continue
190
-
191
- doc_list = []
192
- for doc in doc_items:
193
- doc_href = doc.xpath("./a[1]/@href").get()
194
- if doc_href and doc_href != "#":
195
- parsed_href = urlparse(doc_href)
196
- query_params = parse_qs(parsed_href.query)
197
- item_ids = query_params.get("ItemID")
198
- if item_ids:
199
- doc_list.append(item_ids[0])
200
-
201
- if doc_list:
202
- relationships[rel_title] = doc_list
203
-
204
- item_data["relationships"] = relationships
205
- yield item_data
206
-
207
- for doc_ids in relationships.values():
208
- for doc_id in doc_ids:
209
- req = self._request_if_new(doc_id)
210
- if req:
211
- yield req
212
- else:
213
- self.logger.debug("Skipping non-luocdo page: %s", response.url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import json
2
+ import math
3
+ from collections import defaultdict
4
  from pathlib import Path
 
5
 
6
  import scrapy
7
 
8
+ from vbpl.api import (
9
+ CATALOG_ACTION_ID,
10
+ CATALOG_URL,
11
+ DOCUMENT_URL_TEMPLATE,
12
+ REFERENCE_TYPES,
13
+ catalog_body,
14
+ feed_settings,
15
+ format_date,
16
+ join_unique,
17
+ unwrap_catalog,
18
+ unwrap_document,
19
+ )
20
 
21
 
22
  class VbplSpider(scrapy.Spider):
23
+ """Crawl VBPL metadata and relationships from seed document IDs."""
24
 
25
  name = "vbpl"
26
 
27
  @classmethod
28
  def from_crawler(cls, crawler, *args, **kwargs):
29
  proxy_file = kwargs.get("proxy_file")
30
+ output = kwargs.get("output")
31
+ if output:
32
+ crawler.settings.set("FEEDS", feed_settings(output), priority="spider")
33
  if proxy_file:
34
  crawler.settings.set("PROXY_LIST_FILE", proxy_file, priority="spider")
35
  else:
36
+ middlewares = dict(crawler.settings.getwithbase("DOWNLOADER_MIDDLEWARES"))
37
+ middlewares.pop("vbpl.middlewares.RotatingProxyMiddleware", None)
38
+ crawler.settings.set(
39
+ "DOWNLOADER_MIDDLEWARES", middlewares, priority="spider"
40
+ )
41
  return super().from_crawler(crawler, *args, **kwargs)
42
 
43
  def __init__(
 
47
  proxy_file=None,
48
  resume=0,
49
  resume_from="data.jsonl",
50
+ full=0,
51
+ page_size=100,
52
+ max_pages=0,
53
+ catalog_action_id=CATALOG_ACTION_ID,
54
+ output=None,
55
  *args,
56
  **kwargs,
57
  ):
58
  super().__init__(*args, **kwargs)
59
  self.proxy_file = proxy_file
60
+ self.full = bool(int(full))
61
+ self.page_size = int(page_size)
62
+ self.max_pages = int(max_pages)
63
+ self.catalog_action_id = catalog_action_id
64
+ self.output = output
65
  if seed_file:
66
  self.seed_ids = [
67
  line.strip()
 
70
  ]
71
  else:
72
  self.seed_ids = [item_id.strip() for item_id in str(seed_ids).split(",")]
73
+
74
  self.seen_ids = set()
75
  if int(resume):
76
  resume_path = Path(resume_from)
77
  if resume_path.exists():
78
+ with resume_path.open(encoding="utf-8") as source:
79
+ for line in source:
 
80
  try:
81
  item = json.loads(line)
 
 
82
  except json.JSONDecodeError:
83
+ continue
84
+ if "id" in item:
85
+ self.seen_ids.add(str(item["id"]))
86
  self.logger.info(
87
  "Resume mode: loaded %d already-scraped IDs from %s",
88
  len(self.seen_ids),
 
90
  )
91
 
92
  async def start(self):
 
93
  for request in self.start_requests():
94
  yield request
95
 
96
  def start_requests(self):
97
+ if self.full:
98
+ yield self._catalog_request(1)
99
+ return
100
  for item_id in self.seed_ids:
101
+ request = self._request_if_new(item_id)
102
+ if request:
103
+ yield request
104
+
105
+ def _catalog_request(self, page_number):
106
+ return scrapy.Request(
107
+ CATALOG_URL,
108
+ method="POST",
109
+ body=catalog_body(page_number, self.page_size),
110
+ callback=self.parse_catalog,
111
+ cb_kwargs={"page_number": page_number},
112
+ headers={
113
+ "Accept": "text/x-component",
114
+ "Content-Type": "text/plain;charset=UTF-8",
115
+ "Next-Action": self.catalog_action_id,
116
+ "Origin": "https://vbpl.vn",
117
+ "Referer": CATALOG_URL,
118
+ },
119
+ )
120
+
121
+ def parse_catalog(self, response, page_number):
122
+ catalog = unwrap_catalog(response.text)
123
+ if not catalog:
124
+ retry_times = response.meta.get("invalid_response_retries", 0)
125
+ if retry_times < 3:
126
+ self.logger.warning(
127
+ "Retrying invalid catalog page %d (%d/3)",
128
+ page_number,
129
+ retry_times + 1,
130
+ )
131
+ yield response.request.replace(
132
+ dont_filter=True,
133
+ meta={**response.meta, "invalid_response_retries": retry_times + 1},
134
+ )
135
+ return
136
+ self.logger.error(
137
+ "Could not parse catalog page %d after 3 retries. "
138
+ "The catalog action ID may have changed.",
139
+ page_number,
140
  )
141
+ return
142
 
143
+ if page_number == 1:
144
+ total = int(catalog.get("total") or 0)
145
+ total_page_count = math.ceil(total / self.page_size)
146
+ page_count = total_page_count
147
+ if self.max_pages:
148
+ page_count = min(page_count, self.max_pages)
149
+ self.logger.info(
150
+ "Full crawl discovered %d documents; scheduling %d of %d catalog pages",
151
+ total,
152
+ page_count,
153
+ total_page_count,
154
  )
155
+ for next_page in range(2, page_count + 1):
156
+ yield self._catalog_request(next_page)
157
 
158
+ for item in catalog["items"]:
159
+ request = self._request_if_new(item.get("id"), catalog_item=item)
160
+ if request:
161
+ yield request
162
+
163
+ def _request_if_new(self, item_id, catalog_item=None):
164
+ item_id = str(item_id)
165
+ if not item_id or item_id in self.seen_ids:
166
  return None
167
+ self.seen_ids.add(item_id)
168
+ return scrapy.Request(
169
+ DOCUMENT_URL_TEMPLATE.format(item_id),
170
+ callback=self.parse_document,
171
+ cb_kwargs={"doc_id": item_id, "catalog_item": catalog_item},
172
+ headers={"Accept": "application/json", "Referer": "https://vbpl.vn/"},
173
+ meta={"handle_httpstatus_all": True},
174
+ )
 
 
 
 
 
 
 
 
 
 
 
175
 
176
+ def parse_document(self, response, doc_id, catalog_item=None):
177
+ """Extract one API document and follow its linked document IDs."""
178
+ if response.status >= 400:
179
+ if catalog_item:
180
+ yield self._catalog_fallback(
181
+ catalog_item, f"catalog_only_http_{response.status}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  )
183
  else:
184
+ self.logger.error("Skipping %s after HTTP %d", doc_id, response.status)
185
+ return
186
+
187
+ try:
188
+ document = unwrap_document(response.json())
189
+ except ValueError:
190
+ document = None
191
+
192
+ if not document:
193
+ retry_times = response.meta.get("invalid_response_retries", 0)
194
+ if retry_times < 3:
195
+ self.logger.warning(
196
+ "Retrying invalid document %s (%d/3)", doc_id, retry_times + 1
 
 
 
197
  )
198
+ yield response.request.replace(
199
+ dont_filter=True,
200
+ meta={**response.meta, "invalid_response_retries": retry_times + 1},
201
+ )
202
+ return
203
+ self.logger.error("Skipping %s after 3 invalid API responses", doc_id)
204
+ if catalog_item:
205
+ yield self._catalog_fallback(catalog_item, "catalog_only_invalid_detail")
206
+ return
207
+
208
+ issues = document.get("documentIssues") or []
209
+ majors = document.get("documentMajors") or []
210
+ fields = document.get("documentFields") or []
211
+ references = document.get("references") or []
212
+
213
+ relationships = defaultdict(list)
214
+ linked_ids = []
215
+ for reference in references:
216
+ target = reference.get("targetDocument") or {}
217
+ target_id = target.get("id")
218
+ if not target_id:
219
+ continue
220
+ target_id = str(target_id)
221
+ relationship = REFERENCE_TYPES.get(
222
+ reference.get("referenceType"),
223
+ f"Loại quan hệ {reference.get('referenceType')}",
224
+ )
225
+ if target_id not in relationships[relationship]:
226
+ relationships[relationship].append(target_id)
227
+ linked_ids.append(target_id)
228
+
229
+ agency = join_unique(issue.get("agencyName") for issue in issues)
230
+ if not agency:
231
+ agency = document.get("agencyName")
232
+
233
+ yield {
234
+ "id": str(document.get("id") or doc_id),
235
+ "title": document.get("title"),
236
+ "so_ky_hieu": document.get("docNum"),
237
+ "ngay_ban_hanh": format_date(document.get("issueDate")),
238
+ "loai_van_ban": (document.get("docType") or {}).get("name"),
239
+ "ngay_co_hieu_luc": format_date(document.get("effFrom")),
240
+ "ngay_het_hieu_luc": format_date(document.get("effTo")),
241
+ "nguon_thu_thap": None,
242
+ "ngay_dang_cong_bao": format_date(document.get("publicDate")),
243
+ "nganh": join_unique(major.get("name") for major in majors),
244
+ "linh_vuc": join_unique(field.get("name") for field in fields),
245
+ "co_quan_ban_hanh": agency,
246
+ "chuc_danh": join_unique(issue.get("jobTitleName") for issue in issues),
247
+ "nguoi_ky": join_unique(issue.get("personName") for issue in issues),
248
+ "pham_vi": (
249
+ "Trung ương"
250
+ if document.get("isLw") is True
251
+ else "Địa phương"
252
+ if document.get("isLw") is False
253
+ else None
254
+ ),
255
+ "thong_tin_ap_dung": None,
256
+ "tinh_trang_hieu_luc": (document.get("effStatus") or {}).get("name"),
257
+ "content": (document.get("documentContent") or {}).get("content"),
258
+ "relationships": dict(relationships),
259
+ }
260
+
261
+ if not self.full:
262
+ for linked_id in linked_ids:
263
+ request = self._request_if_new(linked_id)
264
+ if request:
265
+ yield request
266
+
267
+ @staticmethod
268
+ def _catalog_fallback(document, crawl_status):
269
+ majors = document.get("documentMajors") or []
270
+ return {
271
+ "id": str(document.get("id")),
272
+ "title": document.get("title"),
273
+ "so_ky_hieu": document.get("docNum"),
274
+ "ngay_ban_hanh": format_date(document.get("issueDate")),
275
+ "loai_van_ban": (document.get("docType") or {}).get("name"),
276
+ "ngay_co_hieu_luc": format_date(document.get("effFrom")),
277
+ "ngay_het_hieu_luc": format_date(document.get("effTo")),
278
+ "nguon_thu_thap": None,
279
+ "ngay_dang_cong_bao": format_date(document.get("publicDate")),
280
+ "nganh": join_unique(major.get("name") for major in majors),
281
+ "linh_vuc": None,
282
+ "co_quan_ban_hanh": document.get("agencyName"),
283
+ "chuc_danh": None,
284
+ "nguoi_ky": None,
285
+ "pham_vi": (
286
+ "Trung ương"
287
+ if document.get("isLw") is True
288
+ else "Địa phương"
289
+ if document.get("isLw") is False
290
+ else None
291
+ ),
292
+ "thong_tin_ap_dung": None,
293
+ "tinh_trang_hieu_luc": (document.get("effStatus") or {}).get("name"),
294
+ "content": None,
295
+ "relationships": {},
296
+ "crawl_status": crawl_status,
297
+ }
crawler/vbpl/spiders/vbpl_content.py DELETED
@@ -1,43 +0,0 @@
1
- from pathlib import Path
2
-
3
- import scrapy
4
-
5
-
6
- class VbplSpider(scrapy.Spider):
7
- """Crawl VBPL content pages and extract HTML content."""
8
-
9
- name = "vbpl_content"
10
-
11
- def __init__(self, seed_file=None, seed_ids="1", *args, **kwargs):
12
- super().__init__(*args, **kwargs)
13
- if seed_file:
14
- self.seed_ids = [
15
- line.strip()
16
- for line in Path(seed_file).read_text(encoding="utf-8").splitlines()
17
- if line.strip()
18
- ]
19
- else:
20
- self.seed_ids = [item_id.strip() for item_id in str(seed_ids).split(",")]
21
-
22
- def start_requests(self):
23
- """Start crawling from seed IDs."""
24
- for item_id in self.seed_ids:
25
- yield scrapy.Request(
26
- f"https://vbpl.vn/tw/Pages/vbpq-print.aspx?ItemID={item_id}",
27
- callback=self.parse,
28
- cb_kwargs={"doc_id": item_id},
29
- )
30
-
31
- def parse(self, response, doc_id):
32
- """Extract content from #content element."""
33
- # Skip if URL was redirected (not the vbpq-print URL anymore)
34
- if "vbpq-print.aspx" not in response.url:
35
- return
36
-
37
- content_html = response.css("#content").get()
38
- # Only yield if content is not empty
39
- if content_html and content_html.strip():
40
- yield {
41
- "id": doc_id,
42
- "content_html": content_html,
43
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/content.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2db77423942fda0fb9fd422d0e95194450237fe6bc9663571db2b828dbd2b289
3
- size 411822717
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36127fdd1bfb0129cb80447b427ff236395c7ab8c75f822a9975c872afd62b7c
3
+ size 787193691
data/metadata.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:89913874a90dc4adc4b4ef40356716713cdf15bac756b8e6662b598ecff7b65d
3
- size 14081647
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72dbb208c4d5d9f05c1294818c4175603ecc8f853f8745ca35aef7786c0e2e0a
3
+ size 15335252
data/relationships.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:53d9a2e7205c771b72517c82096a1418eafea92e310f5a98bb0a23d8adfa138c
3
- size 4066078
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cdb628b4dfdc92e33d234785f80378d0b99418c7711adcbe6402ade98b57ffb
3
+ size 9436116