File size: 7,812 Bytes
e7cee37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
"""
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)

            # Check if has real 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}")

    # Statistics
    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:,}")

    # Year distribution
    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]}")

    # Sample records
    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

    # Login
    if token:
        login(token=token)
    else:
        console.print("[yellow]No token provided. Using cached credentials.[/yellow]")

    # Load and create dataset
    console.print("[bold]Loading corpus...[/bold]")
    records = load_corpus()
    dataset = create_dataset(records)

    console.print(f"\n[bold]Dataset:[/bold] {dataset}")

    # Upload
    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}")

    # Save
    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}")

    # Save
    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()