File size: 5,327 Bytes
4f45746
c4e128a
 
 
 
 
 
 
4f45746
 
 
 
 
 
 
 
 
 
c4e128a
 
4f45746
c4e128a
 
4f45746
c4e128a
4f45746
c4e128a
 
 
 
 
 
4f45746
 
 
 
 
 
 
 
 
 
 
 
c4e128a
 
 
 
 
 
 
 
 
 
4f45746
c4e128a
4f45746
 
 
c4e128a
4f45746
 
 
 
c4e128a
4f45746
c4e128a
4f45746
c4e128a
 
4f45746
 
 
 
 
 
 
 
 
 
 
c4e128a
 
4f45746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e128a
 
 
4f45746
 
 
 
 
 
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
"""kdc ingest command — full PDF ingestion pipeline."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console
from rich.panel import Panel
from rich.progress import (
    BarColumn,
    MofNCompleteColumn,
    Progress,
    SpinnerColumn,
    TextColumn,
    TimeElapsedColumn,
)
from rich.table import Table

from app.collectors.local import LocalCollector
from app.collectors.pipeline import IngestionPipeline, IngestionStats
from app.models.document import DocumentMeta
from app.utils.container import Container
from app.utils.file import human_size

app = typer.Typer(help="Ingest PDFs, calculate SHA256, deduplicate, store, and build metadata.")
console = Console()


@app.command()
def run(
    ctx: typer.Context,
    source: Path = typer.Option(
        Path("pdf"),
        "--source",
        "-s",
        "--pdf-dir",
        help="Input directory containing PDFs.",
    ),
    pdf_dir: Path = typer.Option(
        Path("pdf"),
        "--pdf-dir-out",
        help="Output directory to store organized corpus PDFs.",
    ),
    meta_dir: Path = typer.Option(
        Path("metadata"), "--meta-dir", help="Metadata JSON output directory."
    ),
    render_previews: bool = typer.Option(
        True, "--preview/--no-preview", help="Render preview images."
    ),
    export_dataset: bool = typer.Option(
        True, "--export/--no-export", help="Export Parquet/JSONL datasets."
    ),
) -> None:
    """Ingest PDFs from SOURCE folder, calculate SHA256, assign UUIDs, store PDFs, build metadata, skip duplicates."""
    container: Container = ctx.obj
    source_dir = source.resolve()
    pdf_dir_out = pdf_dir.resolve()
    meta_dir_out = meta_dir.resolve()

    meta_dir_out.mkdir(parents=True, exist_ok=True)
    pdf_dir_out.mkdir(parents=True, exist_ok=True)

    collector = LocalCollector(pdf_dir=source_dir)
    collected_files = list(collector.collect())

    if not collected_files:
        console.print(f"[yellow]No PDF files found in {source_dir}[/yellow]")
        raise typer.Exit()

    pipeline = IngestionPipeline(
        extractor=container.extractor,
        schema_validator=container.schema_validator,
        content_validator=container.content_validator,
        dedup_registry=container.dedup_registry,
        preview_renderer=container.renderer,
        parquet_exporter=container.parquet_exporter,
        jsonl_exporter=container.jsonl_exporter,
    )

    stats = IngestionStats(total_found=len(collected_files))
    valid_docs: list[DocumentMeta] = []

    console.print(
        Panel.fit(
            f"[bold cyan]Ingesting {stats.total_found} PDF(s) from [yellow]{source_dir}[/yellow]"
        )
    )

    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        MofNCompleteColumn(),
        TimeElapsedColumn(),
        console=console,
    ) as progress:
        task = progress.add_task("Processing PDFs...", total=stats.total_found)

        for item in collected_files:
            progress.update(task, description=f"[cyan]Ingesting {item.path.name[:30]}[/cyan]")
            doc_meta, status = pipeline.process_file(
                pdf_path=item.path,
                category_hint=item.category_hint,
                target_pdf_dir=pdf_dir_out,
                target_meta_dir=meta_dir_out,
                render_preview=render_previews,
            )

            if status == "success" and doc_meta is not None:
                valid_docs.append(doc_meta)
                stats.ingested += 1
                stats.total_pages += doc_meta.pages
                stats.total_bytes += doc_meta.file_size_bytes
            elif status == "duplicate":
                stats.duplicates_skipped += 1
            elif status == "invalid":
                stats.invalid_skipped += 1
            else:
                stats.errors += 1

            progress.advance(task)

    if container.dedup_registry:
        container.dedup_registry.save()

    # Rich summary table
    table = Table(
        title="Ingestion Pipeline Summary",
        show_header=True,
        header_style="bold green",
    )
    table.add_column("Metric", style="cyan")
    table.add_column("Value", justify="right", style="bold white")

    table.add_row("Total Files Discovered", str(stats.total_found))
    table.add_row("Successfully Ingested & Stored", f"[green]{stats.ingested}[/green]")
    table.add_row("Duplicates Skipped (SHA256)", f"[yellow]{stats.duplicates_skipped}[/yellow]")
    table.add_row("Invalid Files Skipped", f"[red]{stats.invalid_skipped}[/red]")
    table.add_row("Extraction Errors", f"[red]{stats.errors}[/red]")
    table.add_row("Total Pages Extracted", str(stats.total_pages))
    table.add_row("Total Corpus Size", human_size(stats.total_bytes))

    console.print()
    console.print(table)

    # Export datasets
    if export_dataset and valid_docs:
        if container.parquet_exporter:
            p_path = container.parquet_exporter.export(valid_docs)
            console.print(f"[green]✓ Parquet dataset exported to {p_path}[/green]")
        if container.jsonl_exporter:
            j_path = container.jsonl_exporter.export(valid_docs)
            console.print(f"[green]✓ JSONL dataset exported to {j_path}[/green]")