feat(ingestion): implement Phase 3 text extraction, OCR, and human review

- Add direct text, DOCX, and PDF text extraction with visual OCR fallback
- Implement Gemini and OpenRouter vision adapters with strict bounded retry
- Implement extraction envelopes, artifacts, and Unicode/Persian normalization
- Add human review workflow, candidate staging, and review repositories
- Add migration 0003_extraction_review for audit events and review tracking
- Add comprehensive unit and integration tests covering extraction and review contracts
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:21:01 +03:30
parent b036912293
commit 5ef02d39a9
20 changed files with 4048 additions and 0 deletions
+114
View File
@@ -0,0 +1,114 @@
"""Trusted review identity, validated decisions and manifest-aware preparation."""
from dataclasses import dataclass
import hashlib
import json
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from .chunking import chunk_extraction, factual_context_units
from .embeddings import validate_database_string
from .extraction import ExtractionError, PLACEHOLDER, REVIEW_CHECKS
FACTUAL_CHECKS = ("factual_authority", "whole_pair_association", "behavioral_separation", "placeholders")
@dataclass(frozen=True)
class AdministratorIdentity:
"""Only a trusted backend authentication/operator boundary supplies this value."""
user_id: UUID
organization_id: UUID
class ReviewDecision(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
evidence_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
decision: Literal["approve", "reject"]
checked: tuple[str, ...] = Field(max_length=16)
note: str = Field(min_length=1, max_length=2000)
excluded_group_ids: tuple[str, ...] = Field(default=(), max_length=10000)
@field_validator("note")
@classmethod
def valid_note(cls, value):
validate_database_string(value)
value = value.strip()
if not value:
raise ValueError("A nonblank review note is required")
return value
@model_validator(mode="after")
def unique_sets(self):
for values in (self.checked, self.excluded_group_ids):
if len(set(values)) != len(values):
raise ValueError("Duplicate checks or groups")
for value in values:
validate_database_string(value)
if not value.strip() or len(value) > 500:
raise ValueError("Invalid check/group identifier")
return self
def request_hash(self):
value = self.model_dump(mode="json")
value["checked"] = sorted(value["checked"])
value["excluded_group_ids"] = sorted(value["excluded_group_ids"])
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
ensure_ascii=False).encode()).hexdigest()
def factual_groups(envelope):
return {b.group_id for b in envelope.blocks if b.block_type in ("question", "answer")}
def factual_digest(artifact_sha256, envelope):
return hashlib.sha256(json.dumps(
dict(artifact_sha256=artifact_sha256, groups=sorted(factual_groups(envelope))),
sort_keys=True, separators=(",", ":")).encode()).hexdigest()
class FactualReviewRequired(ExtractionError):
code = "EXTRACTION_REVIEW_REQUIRED"
def pending_review(state):
return any(item.get("decision") is None for item in state.get("candidates", ()))
def reviews_approved(state):
items = state.get("candidates", ())
return bool(items) and all((item.get("decision") or {}).get("decision") == "approve"
for item in items)
def included_groups(envelope, manifest, artifact_sha256):
groups = factual_groups(envelope)
if (not isinstance(manifest, dict) or manifest.get("decision") != "approve"
or manifest.get("artifact_sha256") != artifact_sha256
or manifest.get("evidence_sha256") != factual_digest(artifact_sha256, envelope)
or not manifest.get("reviewer")):
raise FactualReviewRequired("Factual authority approval required")
excluded = manifest.get("excluded_group_ids")
if (not isinstance(excluded, list) or any(not isinstance(g, str) for g in excluded)
or len(set(excluded)) != len(excluded) or not set(excluded) <= groups):
raise ExtractionError("Invalid factual group inclusion")
included = groups - set(excluded)
if not included:
raise ExtractionError("No eligible factual groups")
if any(PLACEHOLDER.search(b.text) for group, blocks, _ in factual_context_units(envelope.blocks)
if group in included for b in blocks):
raise ExtractionError("Placeholder groups cannot be approved as factual evidence")
return included
def prepare_chunks(envelope, processing_profile, state, artifact_sha256):
"""One boundary for worker staging and publication; faithful artifact stays whole."""
if not factual_groups(envelope):
return chunk_extraction(envelope, processing_profile)
included = included_groups(envelope, state.get("factual_inclusion"), artifact_sha256)
return chunk_extraction(envelope, processing_profile, corpus_purpose="approved_factual",
included_group_ids=included)
def required_checks(kind):
return REVIEW_CHECKS if kind == "extraction" else FACTUAL_CHECKS