📦 EqualifyEverything / equalify-reflow

📄 processing_result.py · 470 lines
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470"""Processing result models for the 4-phase architecture.

ProcessingResult is the top-level API output containing:
- Final markdown with auto-corrections applied
- Full glass box processing trace
- Human review checklist

ProcessingTrace captures everything that happened during processing,
including phase summaries and per-agent traces.
"""

from datetime import UTC, datetime
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field

from .agent_trace import AgentTrace
from .review_checklist import ReviewChecklist


class AnalysisSummary(BaseModel):
    """Summary of Phase 1: Analysis.

    Captures what the analysis phase discovered about the document,
    including document type, key entities, and routing decisions.

    Attributes:
        document_type: Classified document type
        total_pages: Number of pages in document
        key_entities: Important names/terms extracted
        required_agents: Agents that will run based on content
        confidence: Confidence in analysis
        time_seconds: Execution time
        cost_cents: LLM cost

    Example:
        >>> summary = AnalysisSummary(
        ...     document_type="research_paper",
        ...     total_pages=9,
        ...     key_entities=["yt", "Enzo", "DVCS"],
        ...     required_agents=["figures", "tables", "typography"],
        ...     confidence=0.95,
        ...     time_seconds=12.5,
        ...     cost_cents=5.8
        ... )
    """

    document_type: str = Field(
        ...,
        description="Classified document type"
    )
    total_pages: int = Field(
        ...,
        ge=1,
        description="Number of pages in document"
    )
    key_entities: list[str] = Field(
        default_factory=list,
        description="Important names/terms extracted"
    )
    required_agents: list[str] = Field(
        default_factory=list,
        description="Agents that will run based on content"
    )
    confidence: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Confidence in analysis"
    )
    time_seconds: float = Field(
        ...,
        ge=0.0,
        description="Execution time"
    )
    cost_cents: float = Field(
        ...,
        ge=0.0,
        description="LLM cost"
    )

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "document_type": "research_paper",
                "total_pages": 9,
                "key_entities": ["yt", "Enzo", "DVCS"],
                "required_agents": ["figures", "tables", "typography"],
                "confidence": 0.95,
                "time_seconds": 12.5,
                "cost_cents": 5.8
            }
        }
    )


class ExtractionSummary(BaseModel):
    """Summary of Phase 2: Extraction.

    Captures extraction phase metrics including confidence
    and any correction iterations performed.

    Attributes:
        confidence: Confidence in extraction quality
        pages_extracted: Number of pages processed
        correction_iterations: Number of extraction refinement iterations
        time_seconds: Execution time
        cost_cents: LLM cost

    Example:
        >>> summary = ExtractionSummary(
        ...     confidence=0.92,
        ...     pages_extracted=9,
        ...     correction_iterations=1,
        ...     time_seconds=45.2,
        ...     cost_cents=8.4
        ... )
    """

    confidence: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Confidence in extraction quality"
    )
    pages_extracted: int = Field(
        ...,
        ge=0,
        description="Number of pages processed"
    )
    correction_iterations: int = Field(
        default=1,
        ge=0,
        description="Number of extraction refinement iterations"
    )
    time_seconds: float = Field(
        ...,
        ge=0.0,
        description="Execution time"
    )
    cost_cents: float = Field(
        ...,
        ge=0.0,
        description="LLM cost"
    )

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "confidence": 0.92,
                "pages_extracted": 9,
                "correction_iterations": 1,
                "time_seconds": 45.2,
                "cost_cents": 8.4
            }
        }
    )


class StructureSummary(BaseModel):
    """Summary of Phase 3a: Structure Verification Loop.

    Captures metrics from the structure verification loop including
    lint issues found/fixed and OCR corrections.

    Attributes:
        iterations: Number of verification loop iterations
        lint_issues_found: Total lint issues detected
        lint_issues_fixed: Lint issues auto-fixed
        ocr_suggestions_processed: OCR suggestions reviewed
        corrections_applied: Total corrections applied
        final_lint_clean: Whether final output passes lint
        time_seconds: Execution time
        cost_cents: LLM cost

    Example:
        >>> summary = StructureSummary(
        ...     iterations=2,
        ...     lint_issues_found=5,
        ...     lint_issues_fixed=5,
        ...     ocr_suggestions_processed=3,
        ...     corrections_applied=2,
        ...     final_lint_clean=True,
        ...     time_seconds=18.3,
        ...     cost_cents=4.2
        ... )
    """

    iterations: int = Field(
        ...,
        ge=1,
        description="Number of verification loop iterations"
    )
    lint_issues_found: int = Field(
        default=0,
        ge=0,
        description="Total lint issues detected"
    )
    lint_issues_fixed: int = Field(
        default=0,
        ge=0,
        description="Lint issues auto-fixed"
    )
    ocr_suggestions_processed: int = Field(
        default=0,
        ge=0,
        description="OCR suggestions reviewed"
    )
    corrections_applied: int = Field(
        default=0,
        ge=0,
        description="Total corrections applied"
    )
    final_lint_clean: bool = Field(
        ...,
        description="Whether final output passes lint"
    )
    time_seconds: float = Field(
        ...,
        ge=0.0,
        description="Execution time"
    )
    cost_cents: float = Field(
        ...,
        ge=0.0,
        description="LLM cost"
    )

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "iterations": 2,
                "lint_issues_found": 5,
                "lint_issues_fixed": 5,
                "ocr_suggestions_processed": 3,
                "corrections_applied": 2,
                "final_lint_clean": True,
                "time_seconds": 18.3,
                "cost_cents": 4.2
            }
        }
    )


class ProcessingTrace(BaseModel):
    """Glass box: Everything that happened during processing.

    ProcessingTrace captures the complete execution history of the
    4-phase pipeline, including phase summaries and per-agent traces.

    This provides full transparency for auditing and debugging.

    Attributes:
        analysis: Phase 1 summary
        extraction: Phase 2 summary
        structure: Phase 3a summary (structure loop)
        agents: Per-agent traces (Phase 3b specialized agents)
        total_observations: Total issues detected
        auto_corrections_applied: Corrections applied automatically
        review_items_generated: Items requiring human review
        total_cost_cents: Total LLM cost
        total_time_seconds: Total execution time
        total_tokens: Total tokens used

    Example:
        >>> trace = ProcessingTrace(
        ...     analysis=analysis_summary,
        ...     extraction=extraction_summary,
        ...     structure=structure_summary,
        ...     agents=[figures_trace, tables_trace],
        ...     total_observations=8,
        ...     auto_corrections_applied=5,
        ...     review_items_generated=3,
        ...     total_cost_cents=42.5,
        ...     total_time_seconds=120.0,
        ...     total_tokens=45000
        ... )
    """

    # Phase summaries
    analysis: AnalysisSummary = Field(
        ...,
        description="Phase 1: Analyze summary"
    )
    extraction: ExtractionSummary = Field(
        ...,
        description="Phase 2: Extract summary"
    )
    structure: StructureSummary = Field(
        ...,
        description="Phase 3a: Structure loop summary"
    )

    # Per-agent results (Phase 3b: Refine - specialized agents)
    agents: list[AgentTrace] = Field(
        default_factory=list,
        description="Per-agent traces"
    )

    # Aggregate stats
    total_observations: int = Field(
        default=0,
        ge=0,
        description="Total issues detected"
    )
    auto_corrections_applied: int = Field(
        default=0,
        ge=0,
        description="Corrections applied automatically"
    )
    review_items_generated: int = Field(
        default=0,
        ge=0,
        description="Items requiring human review"
    )
    total_cost_cents: float = Field(
        default=0.0,
        ge=0.0,
        description="Total LLM cost"
    )
    total_time_seconds: float = Field(
        default=0.0,
        ge=0.0,
        description="Total execution time"
    )
    total_tokens: int = Field(
        default=0,
        ge=0,
        description="Total tokens used"
    )

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "analysis": {
                    "document_type": "research_paper",
                    "total_pages": 9,
                    "key_entities": ["yt", "Enzo"],
                    "required_agents": ["figures", "tables"],
                    "confidence": 0.95,
                    "time_seconds": 12.5,
                    "cost_cents": 5.8
                },
                "extraction": {
                    "confidence": 0.92,
                    "pages_extracted": 9,
                    "correction_iterations": 1,
                    "time_seconds": 45.2,
                    "cost_cents": 8.4
                },
                "structure": {
                    "iterations": 2,
                    "lint_issues_found": 5,
                    "lint_issues_fixed": 5,
                    "ocr_suggestions_processed": 3,
                    "corrections_applied": 2,
                    "final_lint_clean": True,
                    "time_seconds": 18.3,
                    "cost_cents": 4.2
                },
                "agents": [],
                "total_observations": 8,
                "auto_corrections_applied": 5,
                "review_items_generated": 3,
                "total_cost_cents": 42.5,
                "total_time_seconds": 120.0,
                "total_tokens": 45000
            }
        }
    )


class ProcessingResult(BaseModel):
    """Complete result of document processing - exposed via API.

    This is the top-level output of the 4-phase pipeline, containing:
    - Final markdown with auto-corrections applied
    - Full glass box processing trace
    - Human review checklist for remaining items

    Attributes:
        job_id: Associated job ID
        status: Processing outcome (completed, needs_review, failed)
        markdown: Final markdown with auto-corrections applied
        confidence: Overall confidence score
        processing_trace: Full glass box trace
        review_checklist: Human review interface
        created_at: When result was created
        processing_time_seconds: Total processing time

    Example:
        >>> result = ProcessingResult(
        ...     job_id="job-123",
        ...     status="needs_review",
        ...     markdown="# Document Title\\n\\n...",
        ...     confidence=0.87,
        ...     processing_trace=trace,
        ...     review_checklist=checklist,
        ...     processing_time_seconds=120.0
        ... )
    """

    job_id: str = Field(
        ...,
        description="Associated job ID"
    )
    status: Literal["completed", "needs_review", "failed"] = Field(
        ...,
        description="Processing outcome"
    )

    # The outputs
    markdown: str = Field(
        ...,
        description="Final markdown with auto-corrections applied"
    )
    confidence: float = Field(
        ...,
        ge=0.0,
        le=1.0,
        description="Overall confidence score"
    )

    # Glass box: Full transparency
    processing_trace: ProcessingTrace = Field(
        ...,
        description="Full glass box trace"
    )

    # Human review interface
    review_checklist: ReviewChecklist = Field(
        ...,
        description="Human review interface"
    )

    # Metadata
    created_at: datetime = Field(
        default_factory=lambda: datetime.now(UTC),
        description="When result was created"
    )
    processing_time_seconds: float = Field(
        ...,
        ge=0.0,
        description="Total processing time"
    )

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "job_id": "abc-123",
                "status": "needs_review",
                "markdown": "# Document Title\n\n...",
                "confidence": 0.87,
                "processing_trace": {},
                "review_checklist": {},
                "created_at": "2024-12-10T10:35:00Z",
                "processing_time_seconds": 120.0
            }
        }
    )


__all__ = [
    "AnalysisSummary",
    "ExtractionSummary",
    "StructureSummary",
    "ProcessingTrace",
    "ProcessingResult",
]