darachhat
feat: build production-ready Khmer Document Corpus v0.2.0 with Typer CLI, PyMuPDF, Polars, and DI architecture
c4e128a | """kdc stats command — corpus statistics powered by Polars.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import polars as pl | |
| import typer | |
| from rich.console import Console | |
| from rich.table import Table | |
| from app.models.corpus import CorpusRecord | |
| from app.models.document import DocumentMeta | |
| app = typer.Typer(help="Display corpus statistics using Polars.") | |
| console = Console() | |
| def run( | |
| meta_dir: Path = typer.Option(Path("metadata"), "--meta-dir", help="Metadata directory."), | |
| ) -> None: | |
| """Summarize corpus metrics using Polars aggregates.""" | |
| meta_dir = meta_dir.resolve() | |
| files = list(meta_dir.glob("*.json")) | |
| if not files: | |
| console.print(f"[yellow]No metadata found in {meta_dir}[/yellow]") | |
| raise typer.Exit() | |
| records = [] | |
| for f in files: | |
| try: | |
| data = json.loads(f.read_text(encoding="utf-8")) | |
| doc = DocumentMeta.model_validate(data) | |
| records.append(doc.to_flat_dict()) | |
| except Exception: | |
| pass | |
| if not records: | |
| console.print("[yellow]No valid document records to display.[/yellow]") | |
| raise typer.Exit() | |
| df = pl.DataFrame(records, schema=CorpusRecord.polars_schema()) | |
| total_docs = len(df) | |
| total_pages = df["pages"].sum() | |
| total_size_mb = df["file_size_bytes"].sum() / (1024 * 1024) | |
| console.print(f"\n[bold]Total Documents:[/bold] {total_docs}") | |
| console.print(f"[bold]Total Pages:[/bold] {total_pages}") | |
| console.print(f"[bold]Total Size:[/bold] {total_size_mb:.2f} MB\n") | |
| # Language breakdown | |
| lang_df = df.group_by("language").len().sort("len", descending=True) | |
| lang_table = Table(title="Language Distribution") | |
| lang_table.add_column("Language", style="cyan") | |
| lang_table.add_column("Count", justify="right") | |
| for row in lang_df.iter_rows(): | |
| lang_table.add_row(str(row[0]), str(row[1])) | |
| console.print(lang_table) | |
| # Category breakdown | |
| cat_df = df.group_by("category").len().sort("len", descending=True) | |
| cat_table = Table(title="Category Distribution") | |
| cat_table.add_column("Category", style="cyan") | |
| cat_table.add_column("Count", justify="right") | |
| for row in cat_df.iter_rows(): | |
| cat_table.add_row(str(row[0]), str(row[1])) | |
| console.print(cat_table) | |