Vu Anh commited on
Commit
e7cee37
·
1 Parent(s): a354783

Add dataset card and scripts

Browse files
README.md CHANGED
@@ -1,32 +1,81 @@
1
  ---
2
- dataset_info:
3
- features:
4
- - name: id
5
- dtype: string
6
- - name: filename
7
- dtype: string
8
- - name: title
9
- dtype: string
10
- - name: type
11
- dtype: string
12
- - name: content
13
- dtype: string
14
- - name: content_length
15
- dtype: int32
16
- splits:
17
- - name: '2021'
18
- num_bytes: 14282751
19
- num_examples: 110
20
- - name: '2026'
21
- num_bytes: 32429305
22
- num_examples: 318
23
- download_size: 13663651
24
- dataset_size: 46712056
25
- configs:
26
- - config_name: default
27
- data_files:
28
- - split: '2021'
29
- path: data/2021-*
30
- - split: '2026'
31
- path: data/2026-*
32
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - vi
4
+ license: mit
5
+ size_categories:
6
+ - 100<n<1K
7
+ task_categories:
8
+ - text-generation
9
+ - text-classification
10
+ tags:
11
+ - legal
12
+ - vietnamese
13
+ - law
14
+ - vietnam
15
+ - corpus
16
+ - legislation
17
+ pretty_name: Vietnamese Legal Corpus
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ---
19
+
20
+ # Vietnamese Legal Corpus (UTS_VLC)
21
+
22
+ A comprehensive dataset of Vietnamese laws and legal codes.
23
+
24
+ ## Dataset Description
25
+
26
+ This dataset contains 318 Vietnamese legal documents including:
27
+ - **6 Codes (Bo luat)**: Civil Code, Criminal Code, Labor Code, etc.
28
+ - **312 Laws (Luat)**: Various laws from 1945 to 2024
29
+
30
+ ## Splits
31
+
32
+ | Split | Documents | Description |
33
+ |-------|-----------|-------------|
34
+ | 2026 | 318 | Full corpus as of January 2026 |
35
+
36
+ ## Features
37
+
38
+ - `id`: Document identifier
39
+ - `filename`: Source filename
40
+ - `title`: Vietnamese title
41
+ - `title_en`: English title
42
+ - `type`: "code" or "law"
43
+ - `year`: Year of enactment
44
+ - `document_number`: Official document number
45
+ - `effective_date`: Date when law became effective
46
+ - `status`: Current status (Active/Amended/Repealed)
47
+ - `url`: Source URL
48
+ - `has_content`: Whether full text is available
49
+ - `content`: Full text content
50
+ - `content_length`: Character count
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ from datasets import load_dataset
56
+
57
+ # Load the 2026 split
58
+ ds = load_dataset("undertheseanlp/UTS_VLC", split="2026")
59
+
60
+ # Filter only documents with content
61
+ ds_with_content = ds.filter(lambda x: x["has_content"])
62
+
63
+ # Get all codes
64
+ codes = ds.filter(lambda x: x["type"] == "code")
65
+ ```
66
+
67
+ ## License
68
+
69
+ MIT License
70
+
71
+ ## Citation
72
+
73
+ ```bibtex
74
+ @dataset{uts_vlc_2026,
75
+ title={Vietnamese Legal Corpus},
76
+ author={Underthesea NLP},
77
+ year={2026},
78
+ publisher={Hugging Face},
79
+ url={https://huggingface.co/datasets/undertheseanlp/UTS_VLC}
80
+ }
81
+ ```
scripts/README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VLC Downloader
2
+
3
+ Vietnamese Legal Corpus Downloader - Downloads laws and codes from thuvienphapluat.vn
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ cd ~/Downloads/vlc-2026/scripts
9
+ uv venv
10
+ source .venv/bin/activate
11
+ uv pip install -e .
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ### Download laws from database to markdown files
17
+
18
+ ```bash
19
+ # Basic download (metadata only)
20
+ uv run python downloader.py download
21
+
22
+ # With full content from web
23
+ uv run python downloader.py download --fetch-content
24
+
25
+ # With custom delay and limit
26
+ uv run python downloader.py download --fetch-content --delay 2.0 --limit 10
27
+ ```
28
+
29
+ ### Show statistics
30
+
31
+ ```bash
32
+ uv run python downloader.py stats
33
+ ```
34
+
35
+ ### List downloaded files
36
+
37
+ ```bash
38
+ uv run python downloader.py list-files
39
+ ```
40
+
41
+ ## Output Structure
42
+
43
+ ```
44
+ vlc-2026/
45
+ ├── data/
46
+ │ ├── codes/
47
+ │ │ └── 2015/
48
+ │ │ ├── bo-luat-dan-su.md
49
+ │ │ ├── bo-luat-hinh-su.md
50
+ │ │ └── ...
51
+ │ └── laws/
52
+ │ ├── 2022/
53
+ │ ├── 2023/
54
+ │ ├── 2024/
55
+ │ └── 2025/
56
+ ├── scripts/
57
+ │ ├── pyproject.toml
58
+ │ ├── downloader.py
59
+ │ └── README.md
60
+ ├── vietnam_laws.sqlite
61
+ └── REFERENCES.md
62
+ ```
63
+
64
+ ## Markdown Front Matter
65
+
66
+ Each file includes YAML front matter:
67
+
68
+ ```yaml
69
+ ---
70
+ title: Luật Bảo vệ dữ liệu cá nhân
71
+ title_en: Personal Data Protection Law
72
+ type: law
73
+ year: 2025
74
+ document_number: 91/2025/QH15
75
+ effective_date: 2026-01-01
76
+ status: Active
77
+ url: https://thuvienphapluat.vn/...
78
+ downloaded_at: 2026-01-24T10:30:00
79
+ ---
80
+ ```
scripts/analyze.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Analyze downloaded Vietnamese Legal Corpus files
4
+ """
5
+
6
+ import re
7
+ from pathlib import Path
8
+ from collections import defaultdict
9
+
10
+ import click
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ console = Console()
15
+
16
+ DATA_DIR = Path(__file__).parent.parent / "data"
17
+
18
+
19
+ def parse_front_matter(content: str) -> dict:
20
+ """Parse YAML front matter from markdown file."""
21
+ metadata = {}
22
+ if content.startswith("---"):
23
+ parts = content.split("---", 2)
24
+ if len(parts) >= 3:
25
+ for line in parts[1].strip().split("\n"):
26
+ if ":" in line:
27
+ key, value = line.split(":", 1)
28
+ value = value.strip().strip('"')
29
+ metadata[key.strip()] = value
30
+ return metadata
31
+
32
+
33
+ def analyze_file(filepath: Path) -> dict:
34
+ """Analyze a single law file."""
35
+ content = filepath.read_text(encoding="utf-8")
36
+ size = filepath.stat().st_size
37
+
38
+ metadata = parse_front_matter(content)
39
+
40
+ # Check if content exists (after front matter)
41
+ parts = content.split("---", 2)
42
+ body = parts[2] if len(parts) >= 3 else ""
43
+
44
+ has_content = len(body.strip()) > 200 and "*Nội dung chưa được tải xuống.*" not in body
45
+
46
+ return {
47
+ "filename": filepath.name,
48
+ "title": metadata.get("title", "Unknown"),
49
+ "type": metadata.get("type", "unknown"),
50
+ "year": metadata.get("year", "unknown"),
51
+ "document_number": metadata.get("document_number", ""),
52
+ "url": metadata.get("url", ""),
53
+ "size": size,
54
+ "has_content": has_content,
55
+ "content_length": len(body.strip()),
56
+ }
57
+
58
+
59
+ @click.group()
60
+ def cli():
61
+ """Analyze VLC corpus files."""
62
+ pass
63
+
64
+
65
+ @cli.command()
66
+ def summary():
67
+ """Show summary statistics."""
68
+ if not DATA_DIR.exists():
69
+ console.print("[red]Data directory not found[/red]")
70
+ return
71
+
72
+ files = list(DATA_DIR.glob("*.md"))
73
+
74
+ stats = {
75
+ "total": len(files),
76
+ "with_content": 0,
77
+ "without_content": 0,
78
+ "codes": 0,
79
+ "laws": 0,
80
+ "total_size": 0,
81
+ "by_year": defaultdict(int),
82
+ }
83
+
84
+ failed = []
85
+
86
+ for f in files:
87
+ info = analyze_file(f)
88
+ stats["total_size"] += info["size"]
89
+
90
+ if info["type"] == "code":
91
+ stats["codes"] += 1
92
+ else:
93
+ stats["laws"] += 1
94
+
95
+ stats["by_year"][info["year"]] += 1
96
+
97
+ if info["has_content"]:
98
+ stats["with_content"] += 1
99
+ else:
100
+ stats["without_content"] += 1
101
+ failed.append(info)
102
+
103
+ # Print summary
104
+ console.print("[bold blue]VLC Corpus Analysis[/bold blue]\n")
105
+
106
+ table = Table(title="Summary")
107
+ table.add_column("Metric", style="cyan")
108
+ table.add_column("Value", style="green")
109
+
110
+ table.add_row("Total files", str(stats["total"]))
111
+ table.add_row("Codes (Bộ luật)", str(stats["codes"]))
112
+ table.add_row("Laws (Luật)", str(stats["laws"]))
113
+ table.add_row("With content", f"{stats['with_content']} ✓")
114
+ table.add_row("Without content", f"{stats['without_content']} ✗")
115
+ table.add_row("Success rate", f"{stats['with_content']/stats['total']*100:.1f}%")
116
+ table.add_row("Total size", f"{stats['total_size']/1024/1024:.1f} MB")
117
+
118
+ console.print(table)
119
+
120
+ # By year
121
+ console.print("\n[bold]By Year:[/bold]")
122
+ for year in sorted(stats["by_year"].keys(), reverse=True)[:10]:
123
+ console.print(f" {year}: {stats['by_year'][year]}")
124
+
125
+ # Failed files
126
+ if failed:
127
+ console.print(f"\n[bold red]Files without content ({len(failed)}):[/bold red]")
128
+ for info in failed:
129
+ console.print(f" - {info['filename']}")
130
+ console.print(f" Title: {info['title']}")
131
+ console.print(f" Doc#: {info['document_number']}")
132
+
133
+
134
+ @cli.command()
135
+ def failed():
136
+ """List files that failed to download."""
137
+ if not DATA_DIR.exists():
138
+ console.print("[red]Data directory not found[/red]")
139
+ return
140
+
141
+ files = list(DATA_DIR.glob("*.md"))
142
+
143
+ table = Table(title="Files Without Content")
144
+ table.add_column("#", style="dim")
145
+ table.add_column("Filename", style="cyan")
146
+ table.add_column("Title", style="white")
147
+ table.add_column("Year", style="green")
148
+ table.add_column("Size", style="yellow")
149
+
150
+ count = 0
151
+ for f in sorted(files):
152
+ info = analyze_file(f)
153
+ if not info["has_content"]:
154
+ count += 1
155
+ table.add_row(
156
+ str(count),
157
+ info["filename"],
158
+ info["title"][:40] + "..." if len(info["title"]) > 40 else info["title"],
159
+ str(info["year"]),
160
+ f"{info['size']} B"
161
+ )
162
+
163
+ if count > 0:
164
+ console.print(table)
165
+ console.print(f"\n[red]Total: {count} files without content[/red]")
166
+ else:
167
+ console.print("[green]All files have content![/green]")
168
+
169
+
170
+ @cli.command()
171
+ def success():
172
+ """List files that were downloaded successfully."""
173
+ if not DATA_DIR.exists():
174
+ console.print("[red]Data directory not found[/red]")
175
+ return
176
+
177
+ files = list(DATA_DIR.glob("*.md"))
178
+
179
+ table = Table(title="Successfully Downloaded Files")
180
+ table.add_column("#", style="dim")
181
+ table.add_column("Filename", style="cyan")
182
+ table.add_column("Title", style="white")
183
+ table.add_column("Size", style="green")
184
+
185
+ count = 0
186
+ for f in sorted(files, key=lambda x: x.stat().st_size, reverse=True):
187
+ info = analyze_file(f)
188
+ if info["has_content"]:
189
+ count += 1
190
+ if count <= 20: # Show top 20
191
+ table.add_row(
192
+ str(count),
193
+ info["filename"],
194
+ info["title"][:50] + "..." if len(info["title"]) > 50 else info["title"],
195
+ f"{info['size']/1024:.1f} KB"
196
+ )
197
+
198
+ console.print(table)
199
+ if count > 20:
200
+ console.print(f"\n... and {count - 20} more files")
201
+ console.print(f"\n[green]Total: {count} files with content[/green]")
202
+
203
+
204
+ @cli.command()
205
+ @click.argument("pattern", default="")
206
+ def search(pattern: str):
207
+ """Search files by name or title."""
208
+ if not DATA_DIR.exists():
209
+ console.print("[red]Data directory not found[/red]")
210
+ return
211
+
212
+ files = list(DATA_DIR.glob("*.md"))
213
+ pattern = pattern.lower()
214
+
215
+ results = []
216
+ for f in files:
217
+ info = analyze_file(f)
218
+ if pattern in info["filename"].lower() or pattern in info["title"].lower():
219
+ results.append(info)
220
+
221
+ if results:
222
+ table = Table(title=f"Search Results: '{pattern}'")
223
+ table.add_column("Filename", style="cyan")
224
+ table.add_column("Title", style="white")
225
+ table.add_column("Content", style="green")
226
+ table.add_column("Size", style="yellow")
227
+
228
+ for info in results:
229
+ table.add_row(
230
+ info["filename"],
231
+ info["title"][:40],
232
+ "✓" if info["has_content"] else "✗",
233
+ f"{info['size']/1024:.1f} KB"
234
+ )
235
+
236
+ console.print(table)
237
+ else:
238
+ console.print(f"[yellow]No files found matching '{pattern}'[/yellow]")
239
+
240
+
241
+ REQUIRED_FIELDS = ["title", "type", "year", "document_number"]
242
+ OPTIONAL_FIELDS = ["title_en", "effective_date", "status", "url", "downloaded_at"]
243
+
244
+
245
+ def validate_front_matter(filepath: Path) -> dict:
246
+ """Validate front matter of a file and return issues."""
247
+ content = filepath.read_text(encoding="utf-8")
248
+ issues = []
249
+ metadata = {}
250
+
251
+ # Check if file starts with front matter
252
+ if not content.startswith("---"):
253
+ issues.append("Missing front matter (no opening ---)")
254
+ return {"filename": filepath.name, "issues": issues, "metadata": metadata}
255
+
256
+ parts = content.split("---", 2)
257
+ if len(parts) < 3:
258
+ issues.append("Invalid front matter (no closing ---)")
259
+ return {"filename": filepath.name, "issues": issues, "metadata": metadata}
260
+
261
+ # Parse front matter
262
+ for line in parts[1].strip().split("\n"):
263
+ if ":" in line:
264
+ key, value = line.split(":", 1)
265
+ key = key.strip()
266
+ value = value.strip().strip('"')
267
+ metadata[key] = value
268
+
269
+ # Check required fields
270
+ for field in REQUIRED_FIELDS:
271
+ if field not in metadata:
272
+ issues.append(f"Missing required field: {field}")
273
+ elif not metadata[field] or metadata[field] in ("Unknown", "unknown", ""):
274
+ issues.append(f"Empty or invalid value for: {field}")
275
+
276
+ # Validate type field
277
+ if metadata.get("type") and metadata["type"] not in ("code", "law"):
278
+ issues.append(f"Invalid type: {metadata['type']} (should be 'code' or 'law')")
279
+
280
+ # Validate year field
281
+ year = metadata.get("year", "")
282
+ if year and not year.isdigit():
283
+ issues.append(f"Invalid year format: {year}")
284
+ elif year and (int(year) < 1945 or int(year) > 2030):
285
+ issues.append(f"Year out of range: {year}")
286
+
287
+ # Check filename matches metadata
288
+ expected_prefix = "code" if metadata.get("type") == "code" else "law"
289
+ if not filepath.name.startswith(f"{expected_prefix}-"):
290
+ issues.append(f"Filename prefix mismatch: expected '{expected_prefix}-'")
291
+
292
+ if year and f"-{year}-" not in filepath.name:
293
+ issues.append(f"Year in filename doesn't match metadata: {year}")
294
+
295
+ return {"filename": filepath.name, "issues": issues, "metadata": metadata}
296
+
297
+
298
+ @cli.command()
299
+ def validate():
300
+ """Validate front matter of all files."""
301
+ if not DATA_DIR.exists():
302
+ console.print("[red]Data directory not found[/red]")
303
+ return
304
+
305
+ files = list(DATA_DIR.glob("*.md"))
306
+ invalid_files = []
307
+
308
+ for f in sorted(files):
309
+ result = validate_front_matter(f)
310
+ if result["issues"]:
311
+ invalid_files.append(result)
312
+
313
+ if invalid_files:
314
+ table = Table(title="Files with Invalid Front Matter")
315
+ table.add_column("#", style="dim")
316
+ table.add_column("Filename", style="cyan")
317
+ table.add_column("Issues", style="red")
318
+
319
+ for i, item in enumerate(invalid_files, 1):
320
+ table.add_row(
321
+ str(i),
322
+ item["filename"],
323
+ "\n".join(item["issues"])
324
+ )
325
+
326
+ console.print(table)
327
+ console.print(f"\n[red]Total: {len(invalid_files)} files with issues[/red]")
328
+ else:
329
+ console.print("[green]All files have valid front matter![/green]")
330
+
331
+ # Summary
332
+ console.print(f"\n[bold]Validation Summary:[/bold]")
333
+ console.print(f" Total files: {len(files)}")
334
+ console.print(f" Valid: {len(files) - len(invalid_files)}")
335
+ console.print(f" Invalid: {len(invalid_files)}")
336
+
337
+
338
+ @cli.command()
339
+ @click.argument("filename", required=False)
340
+ def inspect(filename: str):
341
+ """Inspect front matter of a specific file or show all fields."""
342
+ if not DATA_DIR.exists():
343
+ console.print("[red]Data directory not found[/red]")
344
+ return
345
+
346
+ if filename:
347
+ # Inspect single file
348
+ filepath = DATA_DIR / filename
349
+ if not filepath.exists():
350
+ # Try to find matching file
351
+ matches = list(DATA_DIR.glob(f"*{filename}*"))
352
+ if matches:
353
+ filepath = matches[0]
354
+ else:
355
+ console.print(f"[red]File not found: {filename}[/red]")
356
+ return
357
+
358
+ result = validate_front_matter(filepath)
359
+ console.print(f"\n[bold]File: {result['filename']}[/bold]\n")
360
+
361
+ table = Table(title="Front Matter")
362
+ table.add_column("Field", style="cyan")
363
+ table.add_column("Value", style="white")
364
+ table.add_column("Status", style="green")
365
+
366
+ for field in REQUIRED_FIELDS + OPTIONAL_FIELDS:
367
+ value = result["metadata"].get(field, "")
368
+ if field in REQUIRED_FIELDS:
369
+ status = "✓" if value and value not in ("Unknown", "unknown") else "✗ required"
370
+ else:
371
+ status = "✓" if value else "-"
372
+ table.add_row(field, str(value)[:50], status)
373
+
374
+ console.print(table)
375
+
376
+ if result["issues"]:
377
+ console.print("\n[bold red]Issues:[/bold red]")
378
+ for issue in result["issues"]:
379
+ console.print(f" - {issue}")
380
+ else:
381
+ # Show field statistics
382
+ files = list(DATA_DIR.glob("*.md"))
383
+ field_stats = defaultdict(int)
384
+
385
+ for f in files:
386
+ result = validate_front_matter(f)
387
+ for field in REQUIRED_FIELDS + OPTIONAL_FIELDS:
388
+ if result["metadata"].get(field):
389
+ field_stats[field] += 1
390
+
391
+ table = Table(title="Front Matter Field Statistics")
392
+ table.add_column("Field", style="cyan")
393
+ table.add_column("Present", style="green")
394
+ table.add_column("Missing", style="red")
395
+ table.add_column("Coverage", style="yellow")
396
+
397
+ for field in REQUIRED_FIELDS + OPTIONAL_FIELDS:
398
+ present = field_stats[field]
399
+ missing = len(files) - present
400
+ coverage = f"{present/len(files)*100:.1f}%"
401
+ req = " (required)" if field in REQUIRED_FIELDS else ""
402
+ table.add_row(f"{field}{req}", str(present), str(missing), coverage)
403
+
404
+ console.print(table)
405
+
406
+
407
+ @cli.command()
408
+ def export_failed():
409
+ """Export failed files to retry list."""
410
+ if not DATA_DIR.exists():
411
+ console.print("[red]Data directory not found[/red]")
412
+ return
413
+
414
+ files = list(DATA_DIR.glob("*.md"))
415
+
416
+ failed = []
417
+ for f in files:
418
+ info = analyze_file(f)
419
+ if not info["has_content"]:
420
+ failed.append({
421
+ "filename": info["filename"],
422
+ "title": info["title"],
423
+ "document_number": info["document_number"],
424
+ })
425
+
426
+ if failed:
427
+ output = DATA_DIR.parent / "failed_downloads.txt"
428
+ with open(output, "w", encoding="utf-8") as f:
429
+ for item in failed:
430
+ f.write(f"{item['filename']}\t{item['title']}\t{item['document_number']}\n")
431
+
432
+ console.print(f"[green]Exported {len(failed)} failed files to {output}[/green]")
433
+ else:
434
+ console.print("[green]No failed files to export[/green]")
435
+
436
+
437
+ if __name__ == "__main__":
438
+ cli()
scripts/browser_downloader.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Vietnamese Legal Corpus Browser Downloader
4
+ Uses Playwright to download laws from thuvienphapluat.vn
5
+ """
6
+
7
+ import re
8
+ import sqlite3
9
+ import asyncio
10
+ from pathlib import Path
11
+ from datetime import datetime
12
+
13
+ import click
14
+ from rich.console import Console
15
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
16
+
17
+ console = Console()
18
+
19
+ DATA_DIR = Path(__file__).parent.parent / "data"
20
+ DB_PATH = Path(__file__).parent.parent / "vietnam_laws.sqlite"
21
+
22
+ # Known URL patterns for major codes
23
+ KNOWN_URLS = {
24
+ "91/2015/QH13": "https://thuvienphapluat.vn/van-ban/Quyen-dan-su/Bo-luat-dan-su-2015-296215.aspx",
25
+ "92/2015/QH13": "https://thuvienphapluat.vn/van-ban/Thu-tuc-To-tung/Bo-luat-to-tung-dan-su-2015-296861.aspx",
26
+ "100/2015/QH13": "https://thuvienphapluat.vn/van-ban/Trach-nhiem-hinh-su/Bo-luat-hinh-su-2015-296661.aspx",
27
+ "101/2015/QH13": "https://thuvienphapluat.vn/van-ban/Trach-nhiem-hinh-su/Bo-luat-to-tung-hinh-su-2015-296884.aspx",
28
+ "95/2015/QH13": "https://thuvienphapluat.vn/van-ban/Giao-thong-Van-tai/Bo-luat-hang-hai-Viet-Nam-2015-298822.aspx",
29
+ "45/2019/QH14": "https://thuvienphapluat.vn/van-ban/Lao-dong-Tien-luong/Bo-luat-Lao-dong-2019-428584.aspx",
30
+ }
31
+
32
+
33
+ def slugify(text: str) -> str:
34
+ """Convert Vietnamese text to slug."""
35
+ vietnamese_map = {
36
+ 'à': 'a', 'á': 'a', 'ả': 'a', 'ã': 'a', 'ạ': 'a',
37
+ 'ă': 'a', 'ằ': 'a', 'ắ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ặ': 'a',
38
+ 'â': 'a', 'ầ': 'a', 'ấ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ậ': 'a',
39
+ 'đ': 'd',
40
+ 'è': 'e', 'é': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ẹ': 'e',
41
+ 'ê': 'e', 'ề': 'e', 'ế': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e',
42
+ 'ì': 'i', 'í': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ị': 'i',
43
+ 'ò': 'o', 'ó': 'o', 'ỏ': 'o', 'õ': 'o', 'ọ': 'o',
44
+ 'ô': 'o', 'ồ': 'o', 'ố': 'o', 'ổ': 'o', 'ỗ': 'o', 'ộ': 'o',
45
+ 'ơ': 'o', 'ờ': 'o', 'ớ': 'o', 'ở': 'o', 'ỡ': 'o', 'ợ': 'o',
46
+ 'ù': 'u', 'ú': 'u', 'ủ': 'u', 'ũ': 'u', 'ụ': 'u',
47
+ 'ư': 'u', 'ừ': 'u', 'ứ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u',
48
+ 'ỳ': 'y', 'ý': 'y', 'ỷ': 'y', 'ỹ': 'y', 'ỵ': 'y',
49
+ }
50
+ text = text.lower()
51
+ for viet, ascii_char in vietnamese_map.items():
52
+ text = text.replace(viet, ascii_char)
53
+ text = re.sub(r'[^a-z0-9]+', '-', text)
54
+ text = re.sub(r'-+', '-', text)
55
+ return text.strip('-')
56
+
57
+
58
+ def create_front_matter(metadata: dict) -> str:
59
+ """Create YAML front matter."""
60
+ lines = ["---"]
61
+ for key, value in metadata.items():
62
+ if value is not None:
63
+ if isinstance(value, str) and ('\n' in value or ':' in value or '"' in value):
64
+ value = value.replace('"', '\\"').replace('\n', ' ')
65
+ lines.append(f'{key}: "{value}"')
66
+ else:
67
+ lines.append(f"{key}: {value}")
68
+ lines.append("---")
69
+ return "\n".join(lines)
70
+
71
+
72
+ def get_laws_from_db() -> list[dict]:
73
+ """Get laws from SQLite database."""
74
+ if not DB_PATH.exists():
75
+ return []
76
+
77
+ conn = sqlite3.connect(DB_PATH)
78
+ conn.row_factory = sqlite3.Row
79
+ cursor = conn.cursor()
80
+
81
+ laws = []
82
+
83
+ cursor.execute("SELECT * FROM codes")
84
+ for row in cursor.fetchall():
85
+ laws.append({
86
+ "id": f"code-{row['id']}",
87
+ "type": "code",
88
+ "name": row["name"],
89
+ "name_vi": row["name_vi"],
90
+ "year": row["year"],
91
+ "document_number": row["document_number"],
92
+ "effective_date": row["effective_date"],
93
+ "status": row["status"],
94
+ })
95
+
96
+ cursor.execute("SELECT * FROM laws")
97
+ for row in cursor.fetchall():
98
+ laws.append({
99
+ "id": f"law-{row['id']}",
100
+ "type": "law",
101
+ "name": row["name"],
102
+ "name_vi": row["name_vi"],
103
+ "year": row["year"],
104
+ "document_number": row["document_number"],
105
+ "effective_date": row["effective_date"],
106
+ "status": row["status"],
107
+ })
108
+
109
+ conn.close()
110
+ return laws
111
+
112
+
113
+ def save_law_file(law: dict, content: str | None = None, url: str | None = None) -> Path:
114
+ """Save law to markdown file."""
115
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
116
+
117
+ law_type = law.get("type", "law")
118
+ year = law.get("year", "unknown")
119
+ name_vi = law.get("name_vi", law.get("name", "unknown"))
120
+ slug = slugify(name_vi)
121
+
122
+ prefix = "code" if law_type == "code" else "law"
123
+ filename = f"{prefix}-{year}-{slug}.md"
124
+ filepath = DATA_DIR / filename
125
+
126
+ front_matter_data = {
127
+ "title": law.get("name_vi", law.get("name")),
128
+ "title_en": law.get("name"),
129
+ "type": law_type,
130
+ "year": year,
131
+ "document_number": law.get("document_number"),
132
+ "effective_date": law.get("effective_date"),
133
+ "status": law.get("status", "Active"),
134
+ "url": url,
135
+ "downloaded_at": datetime.now().isoformat(),
136
+ }
137
+
138
+ md_content = create_front_matter(front_matter_data)
139
+ md_content += "\n\n"
140
+ md_content += f"# {law.get('name_vi', law.get('name'))}\n\n"
141
+
142
+ if law.get("name"):
143
+ md_content += f"**English:** {law['name']}\n\n"
144
+ if law.get("document_number"):
145
+ md_content += f"**Số hiệu:** {law['document_number']}\n\n"
146
+ if law.get("effective_date"):
147
+ md_content += f"**Ngày hiệu lực:** {law['effective_date']}\n\n"
148
+
149
+ if content:
150
+ md_content += "---\n\n"
151
+ md_content += content
152
+ else:
153
+ md_content += "*Nội dung chưa được tải xuống.*\n"
154
+
155
+ filepath.write_text(md_content, encoding="utf-8")
156
+ return filepath
157
+
158
+
159
+ async def download_with_playwright(laws: list[dict], delay: float = 2.0):
160
+ """Download laws using Playwright."""
161
+ try:
162
+ from playwright.async_api import async_playwright
163
+ except ImportError:
164
+ console.print("[red]Playwright not installed. Run: uv pip install playwright && playwright install chromium[/red]")
165
+ return
166
+
167
+ async with async_playwright() as p:
168
+ browser = await p.chromium.launch(headless=True)
169
+ context = await browser.new_context(
170
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
171
+ )
172
+ page = await context.new_page()
173
+
174
+ with Progress(
175
+ SpinnerColumn(),
176
+ TextColumn("[progress.description]{task.description}"),
177
+ BarColumn(),
178
+ TaskProgressColumn(),
179
+ console=console,
180
+ ) as progress:
181
+ task = progress.add_task("Downloading...", total=len(laws))
182
+
183
+ for law in laws:
184
+ name = law.get("name_vi", law.get("name", "Unknown"))
185
+ doc_num = law.get("document_number", "")
186
+ progress.update(task, description=f"[cyan]{name[:40]}[/cyan]")
187
+
188
+ content = None
189
+ url = KNOWN_URLS.get(doc_num)
190
+
191
+ if not url:
192
+ # Search on thuvienphapluat.vn
193
+ try:
194
+ search_url = f"https://thuvienphapluat.vn/page/tim-van-ban.aspx?keyword={doc_num or name}"
195
+ await page.goto(search_url, wait_until="networkidle", timeout=30000)
196
+ await asyncio.sleep(1)
197
+
198
+ # Find first result link
199
+ link = await page.query_selector("a[href*='/van-ban/']")
200
+ if link:
201
+ url = await link.get_attribute("href")
202
+ if url and not url.startswith("http"):
203
+ url = f"https://thuvienphapluat.vn{url}"
204
+ except Exception as e:
205
+ console.print(f"[yellow]Search failed: {name}: {e}[/yellow]")
206
+
207
+ if url:
208
+ try:
209
+ await page.goto(url, wait_until="networkidle", timeout=30000)
210
+ await asyncio.sleep(1)
211
+
212
+ # Extract content
213
+ content_elem = await page.query_selector(".content1, .toanvancontent, .fulltext")
214
+ if content_elem:
215
+ content = await content_elem.inner_text()
216
+ except Exception as e:
217
+ console.print(f"[yellow]Fetch failed: {name}: {e}[/yellow]")
218
+
219
+ save_law_file(law, content, url)
220
+ progress.advance(task)
221
+ await asyncio.sleep(delay)
222
+
223
+ await browser.close()
224
+
225
+
226
+ @click.command()
227
+ @click.option("--delay", default=2.0, help="Delay between requests (seconds)")
228
+ @click.option("--limit", default=0, help="Limit number of laws (0 = all)")
229
+ def download(delay: float, limit: int):
230
+ """Download laws using browser automation."""
231
+ console.print("[bold blue]VLC Browser Downloader[/bold blue]\n")
232
+
233
+ laws = get_laws_from_db()
234
+ if not laws:
235
+ console.print("[yellow]No laws in database[/yellow]")
236
+ return
237
+
238
+ if limit > 0:
239
+ laws = laws[:limit]
240
+
241
+ console.print(f"Found [green]{len(laws)}[/green] laws to download")
242
+ console.print(f"Output: [cyan]{DATA_DIR}[/cyan]\n")
243
+
244
+ asyncio.run(download_with_playwright(laws, delay))
245
+
246
+ console.print(f"\n[green]Done![/green] Files saved to {DATA_DIR}")
247
+
248
+
249
+ if __name__ == "__main__":
250
+ download()
scripts/downloader.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Vietnamese Legal Corpus Downloader
4
+ Downloads laws and codes from thuvienphapluat.vn
5
+ """
6
+
7
+ import re
8
+ import time
9
+ import sqlite3
10
+ from pathlib import Path
11
+ from datetime import datetime
12
+ from urllib.parse import urljoin
13
+
14
+ import httpx
15
+ import click
16
+ from bs4 import BeautifulSoup
17
+ from rich.console import Console
18
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
19
+
20
+ console = Console()
21
+
22
+ BASE_URL = "https://thuvienphapluat.vn"
23
+ SEARCH_URL = "https://thuvienphapluat.vn/page/tim-van-ban.aspx"
24
+ DATA_DIR = Path(__file__).parent.parent / "data"
25
+ DB_PATH = Path(__file__).parent.parent / "vietnam_laws.sqlite"
26
+
27
+ HEADERS = {
28
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
29
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
30
+ "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8",
31
+ "Referer": "https://thuvienphapluat.vn/",
32
+ }
33
+
34
+
35
+ def slugify(text: str) -> str:
36
+ """Convert Vietnamese text to slug."""
37
+ # Vietnamese character mapping
38
+ vietnamese_map = {
39
+ 'à': 'a', 'á': 'a', 'ả': 'a', 'ã': 'a', 'ạ': 'a',
40
+ 'ă': 'a', 'ằ': 'a', 'ắ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ặ': 'a',
41
+ 'â': 'a', 'ầ': 'a', 'ấ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ậ': 'a',
42
+ 'đ': 'd',
43
+ 'è': 'e', 'é': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ẹ': 'e',
44
+ 'ê': 'e', 'ề': 'e', 'ế': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e',
45
+ 'ì': 'i', 'í': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ị': 'i',
46
+ 'ò': 'o', 'ó': 'o', 'ỏ': 'o', 'õ': 'o', 'ọ': 'o',
47
+ 'ô': 'o', 'ồ': 'o', 'ố': 'o', 'ổ': 'o', 'ỗ': 'o', 'ộ': 'o',
48
+ 'ơ': 'o', 'ờ': 'o', 'ớ': 'o', 'ở': 'o', 'ỡ': 'o', 'ợ': 'o',
49
+ 'ù': 'u', 'ú': 'u', 'ủ': 'u', 'ũ': 'u', 'ụ': 'u',
50
+ 'ư': 'u', 'ừ': 'u', 'ứ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u',
51
+ 'ỳ': 'y', 'ý': 'y', 'ỷ': 'y', 'ỹ': 'y', 'ỵ': 'y',
52
+ }
53
+
54
+ text = text.lower()
55
+ for viet, ascii_char in vietnamese_map.items():
56
+ text = text.replace(viet, ascii_char)
57
+
58
+ # Replace spaces and special chars with hyphens
59
+ text = re.sub(r'[^a-z0-9]+', '-', text)
60
+ text = re.sub(r'-+', '-', text)
61
+ return text.strip('-')
62
+
63
+
64
+ def create_front_matter(metadata: dict) -> str:
65
+ """Create YAML front matter for markdown file."""
66
+ lines = ["---"]
67
+ for key, value in metadata.items():
68
+ if value is not None:
69
+ if isinstance(value, str) and ('\n' in value or ':' in value or '"' in value):
70
+ # Multi-line or special chars: use quoted string
71
+ value = value.replace('"', '\\"')
72
+ lines.append(f'{key}: "{value}"')
73
+ else:
74
+ lines.append(f"{key}: {value}")
75
+ lines.append("---")
76
+ return "\n".join(lines)
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."""
123
+ try:
124
+ response = client.get(url, follow_redirects=True)
125
+ response.raise_for_status()
126
+
127
+ soup = BeautifulSoup(response.text, "lxml")
128
+
129
+ # Extract metadata
130
+ metadata = {
131
+ "url": url,
132
+ "downloaded_at": datetime.now().isoformat(),
133
+ }
134
+
135
+ # Title
136
+ title_elem = soup.select_one("h1.title, .doc-title h1, h1")
137
+ if title_elem:
138
+ metadata["title"] = title_elem.get_text(strip=True)
139
+
140
+ # Document number
141
+ doc_num = soup.select_one(".doc-number, .so-hieu")
142
+ if doc_num:
143
+ metadata["document_number"] = doc_num.get_text(strip=True)
144
+
145
+ # Effective date
146
+ effective = soup.select_one(".effective-date, .ngay-hieu-luc")
147
+ if effective:
148
+ metadata["effective_date"] = effective.get_text(strip=True)
149
+
150
+ # Status
151
+ status = soup.select_one(".doc-status, .tinh-trang")
152
+ if status:
153
+ metadata["status"] = status.get_text(strip=True)
154
+
155
+ # Issuing body
156
+ issuer = soup.select_one(".issuing-body, .co-quan-ban-hanh")
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"):
165
+ tag.decompose()
166
+
167
+ content = content_elem.get_text(separator="\n", strip=True)
168
+ metadata["content"] = content
169
+ else:
170
+ # Fallback: get body text
171
+ body = soup.find("body")
172
+ if body:
173
+ for tag in body.select("script, style, nav, header, footer"):
174
+ tag.decompose()
175
+ metadata["content"] = body.get_text(separator="\n", strip=True)
176
+
177
+ return metadata
178
+
179
+ except Exception as e:
180
+ console.print(f"[red]Error fetching {url}: {e}[/red]")
181
+ return None
182
+
183
+
184
+ def fetch_law_list_page(client: httpx.Client, page: int = 1) -> list[dict]:
185
+ """Fetch list of laws from thuvienphapluat.vn."""
186
+ url = f"{BASE_URL}/page/tim-van-ban.aspx?keyword=&type=0&match=True&area=0&status=0&signer=0&sort=0&page={page}"
187
+
188
+ try:
189
+ response = client.get(url, follow_redirects=True)
190
+ response.raise_for_status()
191
+
192
+ soup = BeautifulSoup(response.text, "lxml")
193
+ laws = []
194
+
195
+ for item in soup.select(".doc-item, .search-result-item, .item"):
196
+ law = {}
197
+
198
+ link = item.select_one("a[href*='/van-ban/']")
199
+ if link:
200
+ law["url"] = urljoin(BASE_URL, link.get("href", ""))
201
+ law["title"] = link.get_text(strip=True)
202
+
203
+ doc_num = item.select_one(".doc-number, .so-hieu")
204
+ if doc_num:
205
+ law["document_number"] = doc_num.get_text(strip=True)
206
+
207
+ if law.get("url"):
208
+ laws.append(law)
209
+
210
+ return laws
211
+
212
+ except Exception as e:
213
+ console.print(f"[red]Error fetching law list page {page}: {e}[/red]")
214
+ return []
215
+
216
+
217
+ def get_laws_from_db() -> list[dict]:
218
+ """Get laws from SQLite database."""
219
+ if not DB_PATH.exists():
220
+ console.print(f"[yellow]Database not found: {DB_PATH}[/yellow]")
221
+ return []
222
+
223
+ conn = sqlite3.connect(DB_PATH)
224
+ conn.row_factory = sqlite3.Row
225
+ cursor = conn.cursor()
226
+
227
+ laws = []
228
+
229
+ # Get codes
230
+ cursor.execute("SELECT * FROM codes")
231
+ for row in cursor.fetchall():
232
+ laws.append({
233
+ "id": f"code-{row['id']}",
234
+ "type": "code",
235
+ "name": row["name"],
236
+ "name_vi": row["name_vi"],
237
+ "year": row["year"],
238
+ "document_number": row["document_number"],
239
+ "effective_date": row["effective_date"],
240
+ "status": row["status"],
241
+ "url": row["url"],
242
+ })
243
+
244
+ # Get laws
245
+ cursor.execute("SELECT * FROM laws")
246
+ for row in cursor.fetchall():
247
+ laws.append({
248
+ "id": f"law-{row['id']}",
249
+ "type": "law",
250
+ "name": row["name"],
251
+ "name_vi": row["name_vi"],
252
+ "year": row["year"],
253
+ "document_number": row["document_number"],
254
+ "effective_date": row["effective_date"],
255
+ "status": row["status"],
256
+ "url": row["url"],
257
+ })
258
+
259
+ conn.close()
260
+ return laws
261
+
262
+
263
+ def save_law_file(law: dict, content: str | None = None) -> Path:
264
+ """Save law to markdown file with front matter."""
265
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
266
+
267
+ # Generate filename with year prefix for uniqueness
268
+ law_type = law.get("type", "law")
269
+ year = law.get("year", "unknown")
270
+ name_vi = law.get("name_vi", law.get("name", "unknown"))
271
+ slug = slugify(name_vi)
272
+
273
+ # Prefix: code- or law- with year
274
+ prefix = "code" if law_type == "code" else "law"
275
+ filename = f"{prefix}-{year}-{slug}.md"
276
+ filepath = DATA_DIR / filename
277
+
278
+ # Prepare front matter
279
+ front_matter_data = {
280
+ "title": law.get("name_vi", law.get("name")),
281
+ "title_en": law.get("name"),
282
+ "type": law_type,
283
+ "year": year,
284
+ "document_number": law.get("document_number"),
285
+ "effective_date": law.get("effective_date"),
286
+ "status": law.get("status", "Active"),
287
+ "url": law.get("url"),
288
+ "downloaded_at": datetime.now().isoformat(),
289
+ }
290
+
291
+ # Build markdown content
292
+ md_content = create_front_matter(front_matter_data)
293
+ md_content += "\n\n"
294
+ md_content += f"# {law.get('name_vi', law.get('name'))}\n\n"
295
+
296
+ if law.get("name"):
297
+ md_content += f"**English:** {law['name']}\n\n"
298
+
299
+ if law.get("document_number"):
300
+ md_content += f"**Số hiệu:** {law['document_number']}\n\n"
301
+
302
+ if law.get("effective_date"):
303
+ md_content += f"**Ngày hiệu lực:** {law['effective_date']}\n\n"
304
+
305
+ if content:
306
+ md_content += "## Nội dung\n\n"
307
+ md_content += content
308
+ else:
309
+ md_content += "*Nội dung chưa được tải xuống.*\n"
310
+
311
+ filepath.write_text(md_content, encoding="utf-8")
312
+ return filepath
313
+
314
+
315
+ @click.group()
316
+ def cli():
317
+ """Vietnamese Legal Corpus Downloader"""
318
+ pass
319
+
320
+
321
+ @cli.command()
322
+ @click.option("--fetch-content", is_flag=True, help="Fetch full content from web")
323
+ @click.option("--delay", default=1.0, help="Delay between requests (seconds)")
324
+ @click.option("--limit", default=0, help="Limit number of laws to download (0 = all)")
325
+ def download(fetch_content: bool, delay: float, limit: int):
326
+ """Download laws from database to markdown files."""
327
+ console.print("[bold blue]Vietnamese Legal Corpus Downloader[/bold blue]")
328
+ console.print()
329
+
330
+ # Get laws from database
331
+ laws = get_laws_from_db()
332
+
333
+ if not laws:
334
+ console.print("[yellow]No laws found in database. Please populate the database first.[/yellow]")
335
+ return
336
+
337
+ if limit > 0:
338
+ laws = laws[:limit]
339
+
340
+ console.print(f"Found [green]{len(laws)}[/green] laws/codes to download")
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}"),
347
+ BarColumn(),
348
+ TaskProgressColumn(),
349
+ console=console,
350
+ ) as progress:
351
+ task = progress.add_task("Downloading...", total=len(laws))
352
+
353
+ client = httpx.Client(headers=HEADERS, timeout=30.0)
354
+
355
+ try:
356
+ for law in laws:
357
+ name = law.get("name_vi", law.get("name", "Unknown"))
358
+ progress.update(task, description=f"[cyan]{name[:40]}[/cyan]")
359
+
360
+ content = None
361
+ url = law.get("url")
362
+
363
+ if fetch_content:
364
+ # Search for URL if not in database
365
+ if not url:
366
+ url = search_law_url(
367
+ client,
368
+ law.get("name_vi", ""),
369
+ law.get("document_number")
370
+ )
371
+ time.sleep(delay)
372
+
373
+ # Fetch content from URL
374
+ if url:
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)
383
+
384
+ finally:
385
+ client.close()
386
+
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():
393
+ """Show statistics from database."""
394
+ laws = get_laws_from_db()
395
+
396
+ if not laws:
397
+ console.print("[yellow]No data in database[/yellow]")
398
+ return
399
+
400
+ codes = [l for l in laws if l["type"] == "code"]
401
+ law_list = [l for l in laws if l["type"] == "law"]
402
+
403
+ console.print("[bold]Vietnamese Legal Corpus Statistics[/bold]")
404
+ console.print()
405
+ console.print(f" Codes (Bộ luật): [green]{len(codes)}[/green]")
406
+ console.print(f" Laws (Luật): [green]{len(law_list)}[/green]")
407
+ console.print(f" [bold]Total: [green]{len(laws)}[/green][/bold]")
408
+
409
+ # By year
410
+ console.print()
411
+ console.print("[bold]By Year:[/bold]")
412
+ years = {}
413
+ for law in laws:
414
+ year = law.get("year", "Unknown")
415
+ years[year] = years.get(year, 0) + 1
416
+
417
+ for year in sorted(years.keys(), reverse=True)[:10]:
418
+ console.print(f" {year}: {years[year]}")
419
+
420
+
421
+ @cli.command()
422
+ def list_files():
423
+ """List downloaded files."""
424
+ if not DATA_DIR.exists():
425
+ console.print("[yellow]No data directory found[/yellow]")
426
+ return
427
+
428
+ files = list(DATA_DIR.rglob("*.md"))
429
+ console.print(f"Found [green]{len(files)}[/green] files in {DATA_DIR}")
430
+
431
+ for f in files[:20]:
432
+ console.print(f" {f.relative_to(DATA_DIR)}")
433
+
434
+ if len(files) > 20:
435
+ console.print(f" ... and {len(files) - 20} more")
436
+
437
+
438
+ def main():
439
+ cli()
440
+
441
+
442
+ if __name__ == "__main__":
443
+ main()
scripts/fast_downloader.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Fast Vietnamese Legal Corpus Downloader
4
+ Uses Playwright with concurrent downloads
5
+ """
6
+
7
+ import re
8
+ import sqlite3
9
+ import asyncio
10
+ from pathlib import Path
11
+ from datetime import datetime
12
+
13
+ import click
14
+ from rich.console import Console
15
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
16
+
17
+ console = Console()
18
+
19
+ DATA_DIR = Path(__file__).parent.parent / "data"
20
+ DB_PATH = Path(__file__).parent.parent / "vietnam_laws.sqlite"
21
+
22
+
23
+ def slugify(text: str) -> str:
24
+ vietnamese_map = {
25
+ 'à': 'a', 'á': 'a', 'ả': 'a', 'ã': 'a', 'ạ': 'a',
26
+ 'ă': 'a', 'ằ': 'a', 'ắ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ặ': 'a',
27
+ 'â': 'a', 'ầ': 'a', 'ấ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ậ': 'a',
28
+ 'đ': 'd',
29
+ 'è': 'e', 'é': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ẹ': 'e',
30
+ 'ê': 'e', 'ề': 'e', 'ế': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e',
31
+ 'ì': 'i', 'í': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ị': 'i',
32
+ 'ò': 'o', 'ó': 'o', 'ỏ': 'o', 'õ': 'o', 'ọ': 'o',
33
+ 'ô': 'o', 'ồ': 'o', 'ố': 'o', 'ổ': 'o', 'ỗ': 'o', 'ộ': 'o',
34
+ 'ơ': 'o', 'ờ': 'o', 'ớ': 'o', 'ở': 'o', 'ỡ': 'o', 'ợ': 'o',
35
+ 'ù': 'u', 'ú': 'u', 'ủ': 'u', 'ũ': 'u', 'ụ': 'u',
36
+ 'ư': 'u', 'ừ': 'u', 'ứ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u',
37
+ 'ỳ': 'y', 'ý': 'y', 'ỷ': 'y', 'ỹ': 'y', 'ỵ': 'y',
38
+ }
39
+ text = text.lower()
40
+ for viet, ascii_char in vietnamese_map.items():
41
+ text = text.replace(viet, ascii_char)
42
+ text = re.sub(r'[^a-z0-9]+', '-', text)
43
+ return text.strip('-')
44
+
45
+
46
+ def get_laws_from_db() -> list[dict]:
47
+ if not DB_PATH.exists():
48
+ return []
49
+ conn = sqlite3.connect(DB_PATH)
50
+ conn.row_factory = sqlite3.Row
51
+ cursor = conn.cursor()
52
+ laws = []
53
+
54
+ cursor.execute("SELECT * FROM codes")
55
+ for row in cursor.fetchall():
56
+ laws.append({
57
+ "type": "code", "name": row["name"], "name_vi": row["name_vi"],
58
+ "year": row["year"], "document_number": row["document_number"],
59
+ "effective_date": row["effective_date"], "status": row["status"],
60
+ })
61
+
62
+ cursor.execute("SELECT * FROM laws")
63
+ for row in cursor.fetchall():
64
+ laws.append({
65
+ "type": "law", "name": row["name"], "name_vi": row["name_vi"],
66
+ "year": row["year"], "document_number": row["document_number"],
67
+ "effective_date": row["effective_date"], "status": row["status"],
68
+ })
69
+
70
+ conn.close()
71
+ return laws
72
+
73
+
74
+ def get_filepath(law: dict) -> Path:
75
+ law_type = law.get("type", "law")
76
+ year = law.get("year", "unknown")
77
+ name_vi = law.get("name_vi", law.get("name", "unknown"))
78
+ slug = slugify(name_vi)
79
+ prefix = "code" if law_type == "code" else "law"
80
+ return DATA_DIR / f"{prefix}-{year}-{slug}.md"
81
+
82
+
83
+ def needs_download(law: dict) -> bool:
84
+ filepath = get_filepath(law)
85
+ if not filepath.exists():
86
+ return True
87
+ # Check if file has content (> 1KB)
88
+ return filepath.stat().st_size < 1000
89
+
90
+
91
+ def save_law_file(law: dict, content: str | None = None, url: str | None = None):
92
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
93
+ filepath = get_filepath(law)
94
+
95
+ lines = ["---"]
96
+ lines.append(f"title: {law.get('name_vi', law.get('name'))}")
97
+ if law.get("name"):
98
+ lines.append(f"title_en: {law['name']}")
99
+ lines.append(f"type: {law.get('type', 'law')}")
100
+ lines.append(f"year: {law.get('year')}")
101
+ if law.get("document_number"):
102
+ lines.append(f"document_number: {law['document_number']}")
103
+ if law.get("effective_date"):
104
+ lines.append(f"effective_date: {law['effective_date']}")
105
+ lines.append(f"status: {law.get('status', 'Active')}")
106
+ if url:
107
+ lines.append(f'url: "{url}"')
108
+ lines.append(f'downloaded_at: "{datetime.now().isoformat()}"')
109
+ lines.append("---\n")
110
+
111
+ md = "\n".join(lines)
112
+ md += f"\n# {law.get('name_vi', law.get('name'))}\n\n"
113
+ if law.get("document_number"):
114
+ md += f"**Số hiệu:** {law['document_number']}\n\n"
115
+ if content:
116
+ md += "---\n\n" + content
117
+ else:
118
+ md += "*Nội dung chưa được tải xuống.*\n"
119
+
120
+ filepath.write_text(md, encoding="utf-8")
121
+
122
+
123
+ async def download_law(page, law: dict, semaphore: asyncio.Semaphore) -> bool:
124
+ async with semaphore:
125
+ name = law.get("name_vi", "")
126
+ doc_num = law.get("document_number", "")
127
+
128
+ try:
129
+ # Search for law
130
+ keyword = doc_num if doc_num else name
131
+ search_url = f"https://thuvienphapluat.vn/page/tim-van-ban.aspx?keyword={keyword}"
132
+
133
+ await page.goto(search_url, wait_until="domcontentloaded", timeout=15000)
134
+ await asyncio.sleep(0.5)
135
+
136
+ # Find first result
137
+ link = await page.query_selector("a[href*='/van-ban/']")
138
+ if not link:
139
+ save_law_file(law, None, None)
140
+ return False
141
+
142
+ url = await link.get_attribute("href")
143
+ if not url.startswith("http"):
144
+ url = f"https://thuvienphapluat.vn{url}"
145
+
146
+ # Go to law page
147
+ await page.goto(url, wait_until="domcontentloaded", timeout=15000)
148
+ await asyncio.sleep(0.5)
149
+
150
+ # Extract content
151
+ content = None
152
+ content_elem = await page.query_selector(".content1, .toanvancontent, .fulltext, #toanvancontent")
153
+ if content_elem:
154
+ content = await content_elem.inner_text()
155
+
156
+ save_law_file(law, content, url)
157
+ return True
158
+
159
+ except Exception as e:
160
+ save_law_file(law, None, None)
161
+ return False
162
+
163
+
164
+ async def run_downloads(laws: list[dict], concurrency: int = 5):
165
+ from playwright.async_api import async_playwright
166
+
167
+ async with async_playwright() as p:
168
+ browser = await p.chromium.launch(headless=True)
169
+ semaphore = asyncio.Semaphore(concurrency)
170
+
171
+ # Create multiple pages
172
+ pages = []
173
+ for _ in range(concurrency):
174
+ context = await browser.new_context(
175
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
176
+ )
177
+ page = await context.new_page()
178
+ pages.append(page)
179
+
180
+ success = 0
181
+ with Progress(
182
+ SpinnerColumn(),
183
+ TextColumn("[progress.description]{task.description}"),
184
+ BarColumn(),
185
+ TaskProgressColumn(),
186
+ console=console,
187
+ ) as progress:
188
+ task = progress.add_task("Downloading...", total=len(laws))
189
+
190
+ # Process in batches
191
+ for i in range(0, len(laws), concurrency):
192
+ batch = laws[i:i + concurrency]
193
+ tasks = []
194
+
195
+ for j, law in enumerate(batch):
196
+ page = pages[j % len(pages)]
197
+ tasks.append(download_law(page, law, semaphore))
198
+
199
+ results = await asyncio.gather(*tasks, return_exceptions=True)
200
+
201
+ for r in results:
202
+ if r is True:
203
+ success += 1
204
+ progress.advance(task)
205
+
206
+ progress.update(task, description=f"[cyan]Downloaded: {success}/{len(laws)}[/cyan]")
207
+
208
+ await browser.close()
209
+ return success
210
+
211
+
212
+ @click.command()
213
+ @click.option("--concurrency", default=5, help="Number of concurrent downloads")
214
+ @click.option("--skip-existing", is_flag=True, help="Skip files that already have content")
215
+ def download(concurrency: int, skip_existing: bool):
216
+ """Fast parallel download of Vietnamese laws."""
217
+ console.print("[bold blue]VLC Fast Downloader[/bold blue]\n")
218
+
219
+ laws = get_laws_from_db()
220
+ if not laws:
221
+ console.print("[yellow]No laws in database[/yellow]")
222
+ return
223
+
224
+ if skip_existing:
225
+ laws = [l for l in laws if needs_download(l)]
226
+ console.print(f"[yellow]Skipping already downloaded files[/yellow]")
227
+
228
+ console.print(f"Downloading [green]{len(laws)}[/green] laws (concurrency: {concurrency})")
229
+ console.print(f"Output: [cyan]{DATA_DIR}[/cyan]\n")
230
+
231
+ success = asyncio.run(run_downloads(laws, concurrency))
232
+
233
+ console.print(f"\n[green]Done![/green] Successfully downloaded: {success}/{len(laws)}")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ download()
scripts/pyproject.toml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "vlc-downloader"
3
+ version = "1.0.0"
4
+ description = "Vietnamese Legal Corpus Downloader"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ dependencies = [
8
+ "httpx>=0.27.0",
9
+ "beautifulsoup4>=4.12.0",
10
+ "lxml>=5.0.0",
11
+ "rich>=13.0.0",
12
+ "click>=8.1.0",
13
+ ]
14
+
15
+ [project.scripts]
16
+ vlc-download = "downloader:main"
17
+
18
+ [build-system]
19
+ requires = ["hatchling"]
20
+ build-backend = "hatchling.build"
scripts/upload_hf.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Upload Vietnamese Legal Corpus to Hugging Face Hub
4
+ """
5
+
6
+ import re
7
+ from pathlib import Path
8
+ from datetime import datetime
9
+
10
+ import click
11
+ from rich.console import Console
12
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
13
+ from datasets import Dataset, DatasetDict, Features, Value
14
+ from huggingface_hub import HfApi, login
15
+
16
+ console = Console()
17
+
18
+ DATA_DIR = Path(__file__).parent.parent / "data"
19
+
20
+
21
+ def parse_front_matter(content: str) -> dict:
22
+ """Parse YAML front matter from markdown file."""
23
+ metadata = {}
24
+ if content.startswith("---"):
25
+ parts = content.split("---", 2)
26
+ if len(parts) >= 3:
27
+ for line in parts[1].strip().split("\n"):
28
+ if ":" in line:
29
+ key, value = line.split(":", 1)
30
+ value = value.strip().strip('"')
31
+ metadata[key.strip()] = value
32
+ return metadata
33
+
34
+
35
+ def extract_body(content: str) -> str:
36
+ """Extract body content after front matter."""
37
+ if content.startswith("---"):
38
+ parts = content.split("---", 2)
39
+ if len(parts) >= 3:
40
+ return parts[2].strip()
41
+ return content
42
+
43
+
44
+ def load_corpus() -> list[dict]:
45
+ """Load all law files into a list of records."""
46
+ records = []
47
+ files = sorted(DATA_DIR.glob("*.md"))
48
+
49
+ with Progress(
50
+ SpinnerColumn(),
51
+ TextColumn("[progress.description]{task.description}"),
52
+ BarColumn(),
53
+ TaskProgressColumn(),
54
+ console=console,
55
+ ) as progress:
56
+ task = progress.add_task("Loading files...", total=len(files))
57
+
58
+ for f in files:
59
+ content = f.read_text(encoding="utf-8")
60
+ metadata = parse_front_matter(content)
61
+ body = extract_body(content)
62
+
63
+ # Check if has real content
64
+ has_content = len(body) > 200 and "*Nội dung chưa được tải xuống.*" not in body
65
+
66
+ record = {
67
+ "id": f.stem,
68
+ "filename": f.name,
69
+ "title": metadata.get("title", ""),
70
+ "title_en": metadata.get("title_en", ""),
71
+ "type": metadata.get("type", ""),
72
+ "year": int(metadata.get("year", 0)) if metadata.get("year", "").isdigit() else 0,
73
+ "document_number": metadata.get("document_number", ""),
74
+ "effective_date": metadata.get("effective_date", ""),
75
+ "status": metadata.get("status", ""),
76
+ "url": metadata.get("url", ""),
77
+ "downloaded_at": metadata.get("downloaded_at", ""),
78
+ "has_content": has_content,
79
+ "content": body if has_content else "",
80
+ "content_length": len(body),
81
+ }
82
+ records.append(record)
83
+ progress.advance(task)
84
+
85
+ return records
86
+
87
+
88
+ def create_dataset(records: list[dict]) -> Dataset:
89
+ """Create a Hugging Face Dataset from records."""
90
+ features = Features({
91
+ "id": Value("string"),
92
+ "filename": Value("string"),
93
+ "title": Value("string"),
94
+ "title_en": Value("string"),
95
+ "type": Value("string"),
96
+ "year": Value("int32"),
97
+ "document_number": Value("string"),
98
+ "effective_date": Value("string"),
99
+ "status": Value("string"),
100
+ "url": Value("string"),
101
+ "downloaded_at": Value("string"),
102
+ "has_content": Value("bool"),
103
+ "content": Value("string"),
104
+ "content_length": Value("int32"),
105
+ })
106
+
107
+ return Dataset.from_list(records, features=features)
108
+
109
+
110
+ @click.group()
111
+ def cli():
112
+ """Upload VLC corpus to Hugging Face."""
113
+ pass
114
+
115
+
116
+ @cli.command()
117
+ def preview():
118
+ """Preview the dataset before uploading."""
119
+ if not DATA_DIR.exists():
120
+ console.print("[red]Data directory not found[/red]")
121
+ return
122
+
123
+ records = load_corpus()
124
+ dataset = create_dataset(records)
125
+
126
+ console.print("\n[bold blue]Dataset Preview[/bold blue]\n")
127
+ console.print(dataset)
128
+ console.print(f"\n[bold]Features:[/bold]")
129
+ for name, feat in dataset.features.items():
130
+ console.print(f" {name}: {feat}")
131
+
132
+ # Statistics
133
+ codes = sum(1 for r in records if r["type"] == "code")
134
+ laws = sum(1 for r in records if r["type"] == "law")
135
+ with_content = sum(1 for r in records if r["has_content"])
136
+ total_chars = sum(r["content_length"] for r in records)
137
+
138
+ console.print(f"\n[bold]Statistics:[/bold]")
139
+ console.print(f" Total records: {len(records)}")
140
+ console.print(f" Codes (Bộ luật): {codes}")
141
+ console.print(f" Laws (Luật): {laws}")
142
+ console.print(f" With content: {with_content}")
143
+ console.print(f" Total characters: {total_chars:,}")
144
+
145
+ # Year distribution
146
+ years = {}
147
+ for r in records:
148
+ y = r["year"]
149
+ years[y] = years.get(y, 0) + 1
150
+
151
+ console.print(f"\n[bold]By Year (top 10):[/bold]")
152
+ for year in sorted(years.keys(), reverse=True)[:10]:
153
+ console.print(f" {year}: {years[year]}")
154
+
155
+ # Sample records
156
+ console.print(f"\n[bold]Sample Records:[/bold]")
157
+ for r in records[:3]:
158
+ console.print(f" - {r['title']} ({r['document_number']}, {r['year']})")
159
+
160
+
161
+ @cli.command()
162
+ @click.option("--repo-id", default="undertheseanlp/vietnamese-legal-corpus", help="Hugging Face repo ID")
163
+ @click.option("--private", is_flag=True, help="Make the dataset private")
164
+ @click.option("--token", envvar="HF_TOKEN", help="Hugging Face token")
165
+ def upload(repo_id: str, private: bool, token: str):
166
+ """Upload dataset to Hugging Face Hub."""
167
+ if not DATA_DIR.exists():
168
+ console.print("[red]Data directory not found[/red]")
169
+ return
170
+
171
+ # Login
172
+ if token:
173
+ login(token=token)
174
+ else:
175
+ console.print("[yellow]No token provided. Using cached credentials.[/yellow]")
176
+
177
+ # Load and create dataset
178
+ console.print("[bold]Loading corpus...[/bold]")
179
+ records = load_corpus()
180
+ dataset = create_dataset(records)
181
+
182
+ console.print(f"\n[bold]Dataset:[/bold] {dataset}")
183
+
184
+ # Upload
185
+ console.print(f"\n[bold]Uploading to {repo_id}...[/bold]")
186
+
187
+ dataset.push_to_hub(
188
+ repo_id,
189
+ private=private,
190
+ commit_message=f"Upload Vietnamese Legal Corpus ({len(records)} documents)",
191
+ )
192
+
193
+ console.print(f"\n[green]Done![/green] Dataset uploaded to: https://huggingface.co/datasets/{repo_id}")
194
+
195
+
196
+ @cli.command()
197
+ @click.option("--output", "-o", default="vlc_dataset", help="Output directory")
198
+ def save_local(output: str):
199
+ """Save dataset locally in Arrow format."""
200
+ if not DATA_DIR.exists():
201
+ console.print("[red]Data directory not found[/red]")
202
+ return
203
+
204
+ output_path = Path(output)
205
+
206
+ console.print("[bold]Loading corpus...[/bold]")
207
+ records = load_corpus()
208
+ dataset = create_dataset(records)
209
+
210
+ console.print(f"\n[bold]Dataset:[/bold] {dataset}")
211
+
212
+ # Save
213
+ console.print(f"\n[bold]Saving to {output_path}...[/bold]")
214
+ dataset.save_to_disk(output_path)
215
+
216
+ console.print(f"\n[green]Done![/green] Dataset saved to: {output_path}")
217
+
218
+
219
+ @cli.command()
220
+ @click.option("--output", "-o", default="vlc_dataset.parquet", help="Output parquet file")
221
+ def save_parquet(output: str):
222
+ """Save dataset as Parquet file."""
223
+ if not DATA_DIR.exists():
224
+ console.print("[red]Data directory not found[/red]")
225
+ return
226
+
227
+ output_path = Path(output)
228
+
229
+ console.print("[bold]Loading corpus...[/bold]")
230
+ records = load_corpus()
231
+ dataset = create_dataset(records)
232
+
233
+ console.print(f"\n[bold]Dataset:[/bold] {dataset}")
234
+
235
+ # Save
236
+ console.print(f"\n[bold]Saving to {output_path}...[/bold]")
237
+ dataset.to_parquet(output_path)
238
+
239
+ console.print(f"\n[green]Done![/green] Dataset saved to: {output_path}")
240
+ console.print(f" Size: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
241
+
242
+
243
+ if __name__ == "__main__":
244
+ cli()