File size: 1,662 Bytes
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
"""corpus metadata command — extract and display metadata for a single PDF or folder."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console
from rich.syntax import Syntax

from app.utils.container import Container

app = typer.Typer(help="Extract and view document metadata.")
console = Console()


@app.command("show")
@app.command("extract")
def run(
    ctx: typer.Context,
    pdf_path: Path = typer.Argument(..., help="Path to a PDF document."),
    save: bool = typer.Option(
        False,
        "--save",
        "-s",
        help="Save extracted metadata to metadata/ directory.",
    ),
) -> None:
    """Extract and inspect metadata for a single PDF file."""
    container: Container = ctx.obj
    extractor = container.extractor

    pdf_path = pdf_path.resolve()
    if not pdf_path.exists():
        console.print(f"[red]PDF file not found: {pdf_path}[/red]")
        raise typer.Exit(1)

    try:
        doc_meta = extractor.extract(pdf_path)
        json_str = doc_meta.model_dump_json(indent=2)
        syntax = Syntax(json_str, "json", theme="monokai", line_numbers=True)
        console.print(syntax)

        if save:
            meta_dir = container.settings.paths.metadata_dir.resolve()
            meta_dir.mkdir(parents=True, exist_ok=True)
            out_file = meta_dir / f"{pdf_path.stem}.json"
            out_file.write_text(json_str, encoding="utf-8")
            console.print(f"[green]✓ Metadata saved to {out_file}[/green]")

    except Exception as exc:
        console.print(f"[red]Error extracting metadata: {exc}[/red]")
        raise typer.Exit(1) from exc