|
|
|
|
|
""" |
|
|
Upload Vietnamese Legal Corpus to Hugging Face Hub |
|
|
""" |
|
|
|
|
|
import re |
|
|
from pathlib import Path |
|
|
from datetime import datetime |
|
|
|
|
|
import click |
|
|
from rich.console import Console |
|
|
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn |
|
|
from datasets import Dataset, DatasetDict, Features, Value |
|
|
from huggingface_hub import HfApi, login |
|
|
|
|
|
console = Console() |
|
|
|
|
|
DATA_DIR = Path(__file__).parent.parent / "data" |
|
|
|
|
|
|
|
|
def parse_front_matter(content: str) -> dict: |
|
|
"""Parse YAML front matter from markdown file.""" |
|
|
metadata = {} |
|
|
if content.startswith("---"): |
|
|
parts = content.split("---", 2) |
|
|
if len(parts) >= 3: |
|
|
for line in parts[1].strip().split("\n"): |
|
|
if ":" in line: |
|
|
key, value = line.split(":", 1) |
|
|
value = value.strip().strip('"') |
|
|
metadata[key.strip()] = value |
|
|
return metadata |
|
|
|
|
|
|
|
|
def extract_body(content: str) -> str: |
|
|
"""Extract body content after front matter.""" |
|
|
if content.startswith("---"): |
|
|
parts = content.split("---", 2) |
|
|
if len(parts) >= 3: |
|
|
return parts[2].strip() |
|
|
return content |
|
|
|
|
|
|
|
|
def load_corpus() -> list[dict]: |
|
|
"""Load all law files into a list of records.""" |
|
|
records = [] |
|
|
files = sorted(DATA_DIR.glob("*.md")) |
|
|
|
|
|
with Progress( |
|
|
SpinnerColumn(), |
|
|
TextColumn("[progress.description]{task.description}"), |
|
|
BarColumn(), |
|
|
TaskProgressColumn(), |
|
|
console=console, |
|
|
) as progress: |
|
|
task = progress.add_task("Loading files...", total=len(files)) |
|
|
|
|
|
for f in files: |
|
|
content = f.read_text(encoding="utf-8") |
|
|
metadata = parse_front_matter(content) |
|
|
body = extract_body(content) |
|
|
|
|
|
|
|
|
has_content = len(body) > 200 and "*Nội dung chưa được tải xuống.*" not in body |
|
|
|
|
|
record = { |
|
|
"id": f.stem, |
|
|
"filename": f.name, |
|
|
"title": metadata.get("title", ""), |
|
|
"title_en": metadata.get("title_en", ""), |
|
|
"type": metadata.get("type", ""), |
|
|
"year": int(metadata.get("year", 0)) if metadata.get("year", "").isdigit() else 0, |
|
|
"document_number": metadata.get("document_number", ""), |
|
|
"effective_date": metadata.get("effective_date", ""), |
|
|
"status": metadata.get("status", ""), |
|
|
"url": metadata.get("url", ""), |
|
|
"downloaded_at": metadata.get("downloaded_at", ""), |
|
|
"has_content": has_content, |
|
|
"content": body if has_content else "", |
|
|
"content_length": len(body), |
|
|
} |
|
|
records.append(record) |
|
|
progress.advance(task) |
|
|
|
|
|
return records |
|
|
|
|
|
|
|
|
def create_dataset(records: list[dict]) -> Dataset: |
|
|
"""Create a Hugging Face Dataset from records.""" |
|
|
features = Features({ |
|
|
"id": Value("string"), |
|
|
"filename": Value("string"), |
|
|
"title": Value("string"), |
|
|
"title_en": Value("string"), |
|
|
"type": Value("string"), |
|
|
"year": Value("int32"), |
|
|
"document_number": Value("string"), |
|
|
"effective_date": Value("string"), |
|
|
"status": Value("string"), |
|
|
"url": Value("string"), |
|
|
"downloaded_at": Value("string"), |
|
|
"has_content": Value("bool"), |
|
|
"content": Value("string"), |
|
|
"content_length": Value("int32"), |
|
|
}) |
|
|
|
|
|
return Dataset.from_list(records, features=features) |
|
|
|
|
|
|
|
|
@click.group() |
|
|
def cli(): |
|
|
"""Upload VLC corpus to Hugging Face.""" |
|
|
pass |
|
|
|
|
|
|
|
|
@cli.command() |
|
|
def preview(): |
|
|
"""Preview the dataset before uploading.""" |
|
|
if not DATA_DIR.exists(): |
|
|
console.print("[red]Data directory not found[/red]") |
|
|
return |
|
|
|
|
|
records = load_corpus() |
|
|
dataset = create_dataset(records) |
|
|
|
|
|
console.print("\n[bold blue]Dataset Preview[/bold blue]\n") |
|
|
console.print(dataset) |
|
|
console.print(f"\n[bold]Features:[/bold]") |
|
|
for name, feat in dataset.features.items(): |
|
|
console.print(f" {name}: {feat}") |
|
|
|
|
|
|
|
|
codes = sum(1 for r in records if r["type"] == "code") |
|
|
laws = sum(1 for r in records if r["type"] == "law") |
|
|
with_content = sum(1 for r in records if r["has_content"]) |
|
|
total_chars = sum(r["content_length"] for r in records) |
|
|
|
|
|
console.print(f"\n[bold]Statistics:[/bold]") |
|
|
console.print(f" Total records: {len(records)}") |
|
|
console.print(f" Codes (Bộ luật): {codes}") |
|
|
console.print(f" Laws (Luật): {laws}") |
|
|
console.print(f" With content: {with_content}") |
|
|
console.print(f" Total characters: {total_chars:,}") |
|
|
|
|
|
|
|
|
years = {} |
|
|
for r in records: |
|
|
y = r["year"] |
|
|
years[y] = years.get(y, 0) + 1 |
|
|
|
|
|
console.print(f"\n[bold]By Year (top 10):[/bold]") |
|
|
for year in sorted(years.keys(), reverse=True)[:10]: |
|
|
console.print(f" {year}: {years[year]}") |
|
|
|
|
|
|
|
|
console.print(f"\n[bold]Sample Records:[/bold]") |
|
|
for r in records[:3]: |
|
|
console.print(f" - {r['title']} ({r['document_number']}, {r['year']})") |
|
|
|
|
|
|
|
|
@cli.command() |
|
|
@click.option("--repo-id", default="undertheseanlp/vietnamese-legal-corpus", help="Hugging Face repo ID") |
|
|
@click.option("--private", is_flag=True, help="Make the dataset private") |
|
|
@click.option("--token", envvar="HF_TOKEN", help="Hugging Face token") |
|
|
def upload(repo_id: str, private: bool, token: str): |
|
|
"""Upload dataset to Hugging Face Hub.""" |
|
|
if not DATA_DIR.exists(): |
|
|
console.print("[red]Data directory not found[/red]") |
|
|
return |
|
|
|
|
|
|
|
|
if token: |
|
|
login(token=token) |
|
|
else: |
|
|
console.print("[yellow]No token provided. Using cached credentials.[/yellow]") |
|
|
|
|
|
|
|
|
console.print("[bold]Loading corpus...[/bold]") |
|
|
records = load_corpus() |
|
|
dataset = create_dataset(records) |
|
|
|
|
|
console.print(f"\n[bold]Dataset:[/bold] {dataset}") |
|
|
|
|
|
|
|
|
console.print(f"\n[bold]Uploading to {repo_id}...[/bold]") |
|
|
|
|
|
dataset.push_to_hub( |
|
|
repo_id, |
|
|
private=private, |
|
|
commit_message=f"Upload Vietnamese Legal Corpus ({len(records)} documents)", |
|
|
) |
|
|
|
|
|
console.print(f"\n[green]Done![/green] Dataset uploaded to: https://huggingface.co/datasets/{repo_id}") |
|
|
|
|
|
|
|
|
@cli.command() |
|
|
@click.option("--output", "-o", default="vlc_dataset", help="Output directory") |
|
|
def save_local(output: str): |
|
|
"""Save dataset locally in Arrow format.""" |
|
|
if not DATA_DIR.exists(): |
|
|
console.print("[red]Data directory not found[/red]") |
|
|
return |
|
|
|
|
|
output_path = Path(output) |
|
|
|
|
|
console.print("[bold]Loading corpus...[/bold]") |
|
|
records = load_corpus() |
|
|
dataset = create_dataset(records) |
|
|
|
|
|
console.print(f"\n[bold]Dataset:[/bold] {dataset}") |
|
|
|
|
|
|
|
|
console.print(f"\n[bold]Saving to {output_path}...[/bold]") |
|
|
dataset.save_to_disk(output_path) |
|
|
|
|
|
console.print(f"\n[green]Done![/green] Dataset saved to: {output_path}") |
|
|
|
|
|
|
|
|
@cli.command() |
|
|
@click.option("--output", "-o", default="vlc_dataset.parquet", help="Output parquet file") |
|
|
def save_parquet(output: str): |
|
|
"""Save dataset as Parquet file.""" |
|
|
if not DATA_DIR.exists(): |
|
|
console.print("[red]Data directory not found[/red]") |
|
|
return |
|
|
|
|
|
output_path = Path(output) |
|
|
|
|
|
console.print("[bold]Loading corpus...[/bold]") |
|
|
records = load_corpus() |
|
|
dataset = create_dataset(records) |
|
|
|
|
|
console.print(f"\n[bold]Dataset:[/bold] {dataset}") |
|
|
|
|
|
|
|
|
console.print(f"\n[bold]Saving to {output_path}...[/bold]") |
|
|
dataset.to_parquet(output_path) |
|
|
|
|
|
console.print(f"\n[green]Done![/green] Dataset saved to: {output_path}") |
|
|
console.print(f" Size: {output_path.stat().st_size / 1024 / 1024:.2f} MB") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
cli() |
|
|
|