| """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() |
|
|
| |
| 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) |
|
|
| |
| 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]") |
|
|