File size: 10,969 Bytes
d520909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
Document Processing CLI Commands

Commands:
    sparknet document parse <file>     - Parse and extract text from document
    sparknet document extract <file>   - Extract structured fields
    sparknet document classify <file>  - Classify document type
    sparknet document analyze <file>   - Full document analysis
"""

import typer
from typing import Optional, List
from pathlib import Path
import json
import sys

# Create document sub-app
document_app = typer.Typer(
    name="document",
    help="Document processing commands",
)


@document_app.command("parse")
def parse_document(
    file_path: Path = typer.Argument(..., help="Path to document file"),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output JSON file"),
    ocr_engine: str = typer.Option("paddleocr", "--ocr", help="OCR engine: paddleocr, tesseract"),
    dpi: int = typer.Option(300, "--dpi", help="Rendering DPI for PDFs"),
    max_pages: Optional[int] = typer.Option(None, "--max-pages", help="Maximum pages to process"),
    include_images: bool = typer.Option(False, "--images", help="Include cropped region images"),
):
    """
    Parse a document and extract text with layout information.

    Example:
        sparknet document parse invoice.pdf -o result.json
    """
    from loguru import logger

    if not file_path.exists():
        typer.echo(f"Error: File not found: {file_path}", err=True)
        raise typer.Exit(1)

    typer.echo(f"Parsing document: {file_path}")

    try:
        from ..document.pipeline import (
            PipelineConfig,
            get_document_processor,
        )
        from ..document.ocr import OCRConfig

        # Build config
        ocr_config = OCRConfig(engine=ocr_engine)
        config = PipelineConfig(
            ocr=ocr_config,
            render_dpi=dpi,
            max_pages=max_pages,
        )

        # Process document
        processor = get_document_processor(config)
        result = processor.process(str(file_path))

        # Format output
        output_data = {
            "document_id": result.metadata.document_id,
            "filename": result.metadata.filename,
            "num_pages": result.metadata.num_pages,
            "total_chunks": result.metadata.total_chunks,
            "total_characters": result.metadata.total_characters,
            "ocr_confidence": result.metadata.ocr_confidence_avg,
            "chunks": [
                {
                    "chunk_id": c.chunk_id,
                    "type": c.chunk_type.value,
                    "page": c.page,
                    "text": c.text[:500] + "..." if len(c.text) > 500 else c.text,
                    "confidence": c.confidence,
                    "bbox": {
                        "x_min": c.bbox.x_min,
                        "y_min": c.bbox.y_min,
                        "x_max": c.bbox.x_max,
                        "y_max": c.bbox.y_max,
                    },
                }
                for c in result.chunks
            ],
            "full_text": result.full_text[:2000] + "..." if len(result.full_text) > 2000 else result.full_text,
        }

        # Output
        if output:
            with open(output, "w") as f:
                json.dump(output_data, f, indent=2)
            typer.echo(f"Results written to: {output}")
        else:
            typer.echo(json.dumps(output_data, indent=2))

        typer.echo(f"\nProcessed {result.metadata.num_pages} pages, {len(result.chunks)} chunks")

    except ImportError as e:
        typer.echo(f"Error: Missing dependency - {e}", err=True)
        raise typer.Exit(1)
    except Exception as e:
        typer.echo(f"Error processing document: {e}", err=True)
        raise typer.Exit(1)


@document_app.command("extract")
def extract_fields(
    file_path: Path = typer.Argument(..., help="Path to document file"),
    schema: Optional[Path] = typer.Option(None, "--schema", "-s", help="Extraction schema YAML file"),
    fields: Optional[List[str]] = typer.Option(None, "--field", "-f", help="Fields to extract (can use multiple)"),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output JSON file"),
    validate: bool = typer.Option(True, "--validate/--no-validate", help="Validate extraction"),
):
    """
    Extract structured fields from a document.

    Example:
        sparknet document extract invoice.pdf -f "invoice_number" -f "total_amount"
        sparknet document extract contract.pdf --schema contract_schema.yaml
    """
    from loguru import logger

    if not file_path.exists():
        typer.echo(f"Error: File not found: {file_path}", err=True)
        raise typer.Exit(1)

    if not schema and not fields:
        typer.echo("Error: Provide --schema or --field options", err=True)
        raise typer.Exit(1)

    typer.echo(f"Extracting fields from: {file_path}")

    try:
        from ..document.schemas.extraction import ExtractionSchema, FieldDefinition
        from ..agents.document_agent import DocumentAgent

        # Build extraction schema
        if schema:
            import yaml
            with open(schema) as f:
                schema_data = yaml.safe_load(f)
            extraction_schema = ExtractionSchema(**schema_data)
        else:
            # Build from field names
            field_defs = [
                FieldDefinition(
                    name=f,
                    field_type="string",
                    required=True,
                )
                for f in fields
            ]
            extraction_schema = ExtractionSchema(
                name="cli_extraction",
                fields=field_defs,
            )

        # Run extraction with agent
        import asyncio
        agent = DocumentAgent()
        asyncio.run(agent.load_document(str(file_path)))
        result = asyncio.run(agent.extract_fields(extraction_schema))

        # Format output
        output_data = {
            "document": str(file_path),
            "fields": result.fields,
            "confidence": result.confidence,
            "evidence": [
                {
                    "chunk_id": e.chunk_id,
                    "page": e.page,
                    "snippet": e.snippet,
                }
                for e in result.evidence
            ] if result.evidence else [],
        }

        # Validate if requested
        if validate and result.fields:
            from ..document.validation import get_extraction_critic
            critic = get_extraction_critic()

            evidence_chunks = [
                {"text": e.snippet, "page": e.page, "chunk_id": e.chunk_id}
                for e in result.evidence
            ] if result.evidence else []

            validation = critic.validate_extraction(result.fields, evidence_chunks)
            output_data["validation"] = {
                "status": validation.overall_status.value,
                "confidence": validation.overall_confidence,
                "should_accept": validation.should_accept,
                "abstain_reason": validation.abstain_reason,
            }

        # Output
        if output:
            with open(output, "w") as f:
                json.dump(output_data, f, indent=2)
            typer.echo(f"Results written to: {output}")
        else:
            typer.echo(json.dumps(output_data, indent=2))

    except ImportError as e:
        typer.echo(f"Error: Missing dependency - {e}", err=True)
        raise typer.Exit(1)
    except Exception as e:
        typer.echo(f"Error extracting fields: {e}", err=True)
        raise typer.Exit(1)


@document_app.command("classify")
def classify_document(
    file_path: Path = typer.Argument(..., help="Path to document file"),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output JSON file"),
):
    """
    Classify document type.

    Example:
        sparknet document classify document.pdf
    """
    from loguru import logger

    if not file_path.exists():
        typer.echo(f"Error: File not found: {file_path}", err=True)
        raise typer.Exit(1)

    typer.echo(f"Classifying document: {file_path}")

    try:
        from ..agents.document_agent import DocumentAgent
        import asyncio

        agent = DocumentAgent()
        asyncio.run(agent.load_document(str(file_path)))
        classification = asyncio.run(agent.classify())

        output_data = {
            "document": str(file_path),
            "document_type": classification.document_type.value,
            "confidence": classification.confidence,
            "reasoning": classification.reasoning,
            "metadata": classification.metadata,
        }

        if output:
            with open(output, "w") as f:
                json.dump(output_data, f, indent=2)
            typer.echo(f"Results written to: {output}")
        else:
            typer.echo(json.dumps(output_data, indent=2))

    except Exception as e:
        typer.echo(f"Error classifying document: {e}", err=True)
        raise typer.Exit(1)


@document_app.command("ask")
def ask_document(
    file_path: Path = typer.Argument(..., help="Path to document file"),
    question: str = typer.Argument(..., help="Question to ask about the document"),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output JSON file"),
):
    """
    Ask a question about a document.

    Example:
        sparknet document ask invoice.pdf "What is the total amount?"
    """
    from loguru import logger

    if not file_path.exists():
        typer.echo(f"Error: File not found: {file_path}", err=True)
        raise typer.Exit(1)

    typer.echo(f"Processing question for: {file_path}")

    try:
        from ..agents.document_agent import DocumentAgent
        import asyncio

        agent = DocumentAgent()
        asyncio.run(agent.load_document(str(file_path)))
        answer, evidence = asyncio.run(agent.answer_question(question))

        output_data = {
            "document": str(file_path),
            "question": question,
            "answer": answer,
            "evidence": [
                {
                    "chunk_id": e.chunk_id,
                    "page": e.page,
                    "snippet": e.snippet,
                    "confidence": e.confidence,
                }
                for e in evidence
            ] if evidence else [],
        }

        if output:
            with open(output, "w") as f:
                json.dump(output_data, f, indent=2)
            typer.echo(f"Results written to: {output}")
        else:
            typer.echo(f"\nQuestion: {question}")
            typer.echo(f"\nAnswer: {answer}")
            if evidence:
                typer.echo(f"\nEvidence ({len(evidence)} sources):")
                for e in evidence[:3]:
                    typer.echo(f"  - Page {e.page + 1}: {e.snippet[:100]}...")

    except Exception as e:
        typer.echo(f"Error processing question: {e}", err=True)
        raise typer.Exit(1)