File size: 2,333 Bytes
c4e128a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()


@app.command()
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)