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:
@@ -0,0 +1,232 @@
|
||||
"""Trusted admin review services; HTTP authentication/Origin/CSRF is not implemented."""
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy import text
|
||||
|
||||
from .database import check_compatibility
|
||||
from .intake_repository import administrator
|
||||
from .review_candidates import LocalReviewCandidates
|
||||
from app.modules.documents.errors import IntakeError
|
||||
from app.modules.documents.review import (
|
||||
AdministratorIdentity, ReviewDecision, factual_groups, included_groups,
|
||||
pending_review, required_checks,
|
||||
)
|
||||
from app.modules.documents.worker import read_original, validate_source
|
||||
from app.modules.documents.chunking import factual_review_blocks
|
||||
|
||||
|
||||
class SqlReviewRepository:
|
||||
def __init__(self, engine, settings, candidates, store):
|
||||
self.engine, self.settings, self.candidates, self.store = engine, settings, candidates, store
|
||||
self.reviews = LocalReviewCandidates(candidates)
|
||||
|
||||
def _authorize(self, connection, identity):
|
||||
if not isinstance(identity, AdministratorIdentity):
|
||||
raise IntakeError("ADMINISTRATOR_REQUIRED", "Trusted administrator identity required")
|
||||
org = administrator(connection, identity.user_id)
|
||||
if org != identity.organization_id:
|
||||
raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
|
||||
return org
|
||||
|
||||
def _document(self, connection, identity, document_id, *, lock=False):
|
||||
org = self._authorize(connection, identity)
|
||||
row = connection.execute(text("""
|
||||
SELECT * FROM documents WHERE id=:id AND organization_id=:org
|
||||
""" + (" FOR UPDATE" if lock else "")), dict(id=document_id, org=org)).mappings().one_or_none()
|
||||
if row is None or row["deleted_at"] is not None or row["content_purged_at"] is not None:
|
||||
raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
|
||||
return dict(row)
|
||||
|
||||
def _snapshot(self, identity, document_id):
|
||||
with self.engine.begin() as connection:
|
||||
check_compatibility(connection, self.settings.embedding_profile, require_worker=True)
|
||||
return self._document(connection, identity, document_id)
|
||||
|
||||
def _body(self, pointer, document):
|
||||
try:
|
||||
content = read_original(self.store, document)
|
||||
body = self.reviews.inspect(pointer, document)
|
||||
if body["review_kind"] == "extraction":
|
||||
image = base64.b64decode(body["image"], validate=True)
|
||||
if body["locator"] == "image":
|
||||
if image != content:
|
||||
raise ValueError("Review image differs from original")
|
||||
else:
|
||||
import pymupdf
|
||||
from app.modules.documents.extraction import PageBlockExtractor
|
||||
page = int(body["locator"].rsplit("/", 1)[1])
|
||||
with pymupdf.open(stream=content, filetype="pdf") as source:
|
||||
if not 1 <= page <= source.page_count:
|
||||
raise ValueError("Review source page missing")
|
||||
extractor = PageBlockExtractor()
|
||||
extractor.profile = document["processing_profile"]
|
||||
if extractor._render(source[page - 1]) != image:
|
||||
raise ValueError("Retained preview differs from source rendering")
|
||||
else:
|
||||
artifact = document["extraction_state"].get("complete_artifact")
|
||||
if artifact is None or artifact["sha256"] != body["artifact_sha256"]:
|
||||
raise ValueError("Factual extraction identity changed")
|
||||
envelope = self.candidates.inspect_pointer(artifact, document=document)
|
||||
validate_source(envelope, document, content)
|
||||
contextual = [b.model_dump(mode="json") for b in factual_review_blocks(envelope)]
|
||||
legacy = [b.model_dump(mode="json") for b in envelope.blocks
|
||||
if b.group_id in factual_groups(envelope)]
|
||||
if body["blocks"] != contextual and body["blocks"] != legacy:
|
||||
raise ValueError("Factual evidence differs from retained extraction")
|
||||
# Old immutable candidates remain valid; expose context from the
|
||||
# same digest-bound complete artifact without rewriting files.
|
||||
body = dict(body, blocks=contextual)
|
||||
return body
|
||||
except (OSError, ValueError, KeyError, TypeError, IndexError):
|
||||
raise IntakeError("REVIEW_STALE", "Retained evidence or source is unavailable or incompatible") from None
|
||||
|
||||
def read(self, identity, document_id, *, limit=10, after=None):
|
||||
if type(limit) is not int or not 1 <= limit <= 20:
|
||||
raise IntakeError("VALIDATION_ERROR", "Review page limit must be 1-20")
|
||||
document = self._snapshot(identity, document_id)
|
||||
pointers = [p for p in document["extraction_state"].get("candidates", []) if p.get("decision") is None]
|
||||
start = 0
|
||||
if after is not None:
|
||||
matches = [i for i, p in enumerate(pointers) if p["evidence_sha256"] == after]
|
||||
if not matches:
|
||||
raise IntakeError("REVIEW_STALE", "Review cursor no longer available")
|
||||
start = matches[0] + 1
|
||||
from app.modules.documents.extraction_artifacts import bounded_json_size
|
||||
remaining = document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"]
|
||||
items = []
|
||||
for pointer in pointers[start:start + limit]:
|
||||
body = self._body(pointer, document)
|
||||
items.append(dict(evidence_sha256=body["evidence_sha256"], review_kind=body["review_kind"],
|
||||
location=dict(page=body["blocks"][0]["page"], section=body["locator"]),
|
||||
blocks=body["blocks"], required_checks=list(required_checks(body["review_kind"])),
|
||||
decision=pointer.get("decision"), preview_path=None,
|
||||
preview_available=body["review_kind"] == "extraction"))
|
||||
remaining -= bounded_json_size(items[-1], remaining)
|
||||
# Recheck revocation/deletion before releasing retained data.
|
||||
current = self._snapshot(identity, document_id)
|
||||
self._still_current(current, document, pointers[start:start + limit])
|
||||
response = dict(document_id=str(document_id), status=document["status"],
|
||||
review_required=pending_review(document["extraction_state"]), items=items,
|
||||
next_cursor=(items[-1]["evidence_sha256"] if items and start + limit < len(pointers) else None))
|
||||
from app.modules.documents.extraction_artifacts import bounded_json_bytes
|
||||
bounded_json_bytes(response, document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"])
|
||||
return response
|
||||
|
||||
def preview(self, identity, document_id, evidence_sha256):
|
||||
document = self._snapshot(identity, document_id)
|
||||
pointer = next((p for p in document["extraction_state"].get("candidates", [])
|
||||
if p["evidence_sha256"] == evidence_sha256), None)
|
||||
if pointer is None:
|
||||
raise IntakeError("REVIEW_STALE", "Review evidence no longer available")
|
||||
body = self._body(pointer, document)
|
||||
if body["review_kind"] != "extraction":
|
||||
raise IntakeError("REVIEW_STALE", "Candidate has no preview")
|
||||
current = self._snapshot(identity, document_id)
|
||||
self._still_current(current, document, [pointer])
|
||||
image = base64.b64decode(body["image"], validate=True)
|
||||
return image, "image/png" if image.startswith(b"\x89PNG") else "image/jpeg"
|
||||
|
||||
def _still_current(self, current, document, pointers):
|
||||
fields = ("processing_profile", "file_sha256", "storage_key", "size_bytes", "mime_type")
|
||||
attached = {(p["key"], p["sha256"]) for p in current["extraction_state"].get("candidates", ())}
|
||||
if (any(current[k] != document[k] for k in fields)
|
||||
or any((p["key"], p["sha256"]) not in attached for p in pointers)):
|
||||
raise IntakeError("REVIEW_STALE", "Review source or candidate changed")
|
||||
|
||||
def _replay(self, connection, identity, document_id, request_id, request_hash):
|
||||
row = connection.execute(text("""
|
||||
SELECT request_hash,response_json FROM audit_events
|
||||
WHERE organization_id=:org AND actor_user_id=:actor AND action='extraction_review'
|
||||
AND target_id=:document AND idempotency_key=:request
|
||||
"""), dict(org=identity.organization_id, actor=identity.user_id, document=document_id,
|
||||
request=request_id)).mappings().one_or_none()
|
||||
if row is not None:
|
||||
if row["request_hash"] != request_hash:
|
||||
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different decision")
|
||||
return dict(replayed=True, **row["response_json"])
|
||||
return None
|
||||
|
||||
def decide(self, identity, document_id, *, request_id, payload):
|
||||
# Authorize before parsing or replaying caller input.
|
||||
document = self._snapshot(identity, document_id)
|
||||
try:
|
||||
decision = ReviewDecision.model_validate(payload)
|
||||
request_id = UUID(str(request_id))
|
||||
except (ValueError, TypeError, ValidationError):
|
||||
raise IntakeError("VALIDATION_ERROR", "Invalid review decision") from None
|
||||
request_hash = decision.request_hash()
|
||||
with self.engine.begin() as connection:
|
||||
self._document(connection, identity, document_id)
|
||||
replay = self._replay(connection, identity, document_id, request_id, request_hash)
|
||||
if replay is not None:
|
||||
return replay
|
||||
pointer = next((p for p in document["extraction_state"].get("candidates", [])
|
||||
if p["evidence_sha256"] == decision.evidence_sha256), None)
|
||||
if pointer is None:
|
||||
raise IntakeError("REVIEW_STALE", "Review evidence no longer available")
|
||||
body = self._body(pointer, document)
|
||||
checks = set(required_checks(body["review_kind"]))
|
||||
if (not set(decision.checked) <= checks
|
||||
or (decision.decision == "approve" and set(decision.checked) != checks)
|
||||
or (body["review_kind"] == "extraction" and decision.excluded_group_ids)):
|
||||
raise IntakeError("VALIDATION_ERROR", "Required checks or excluded groups are invalid")
|
||||
manifest = None
|
||||
if body["review_kind"] == "factual_corpus":
|
||||
artifact = document["extraction_state"]["complete_artifact"]
|
||||
envelope = self.candidates.inspect_pointer(artifact, document=document)
|
||||
groups = factual_groups(envelope)
|
||||
if not set(decision.excluded_group_ids) <= groups:
|
||||
raise IntakeError("VALIDATION_ERROR", "Excluded groups must be existing whole Q&A groups")
|
||||
manifest = dict(decision=decision.decision, artifact_sha256=artifact["sha256"],
|
||||
evidence_sha256=decision.evidence_sha256, reviewer=str(identity.user_id),
|
||||
excluded_group_ids=list(decision.excluded_group_ids), note=decision.note)
|
||||
if decision.decision == "approve":
|
||||
try:
|
||||
included_groups(envelope, manifest, artifact["sha256"])
|
||||
except ValueError:
|
||||
raise IntakeError("VALIDATION_ERROR", "Approval must leave factual groups and exclude placeholders") from None
|
||||
with self.engine.begin() as connection:
|
||||
current = self._document(connection, identity, document_id, lock=True)
|
||||
replay = self._replay(connection, identity, document_id, request_id, request_hash)
|
||||
if replay is not None:
|
||||
return replay
|
||||
job = connection.execute(text("SELECT * FROM ingestion_jobs WHERE document_id=:id FOR UPDATE"),
|
||||
dict(id=document_id)).mappings().one()
|
||||
state = current["extraction_state"]
|
||||
index = next((i for i, p in enumerate(state.get("candidates", []))
|
||||
if p["evidence_sha256"] == decision.evidence_sha256), None)
|
||||
if (current["status"] != "failed" or job["status"] != "failed" or index is None
|
||||
or current["processing_profile"] != document["processing_profile"]
|
||||
or any(current[k] != document[k] for k in ("file_sha256", "storage_key", "size_bytes", "mime_type"))
|
||||
or {k: v for k, v in state["candidates"][index].items() if k != "decision"}
|
||||
!= {k: v for k, v in pointer.items() if k != "decision"}
|
||||
or state.get("complete_artifact") != document["extraction_state"].get("complete_artifact")):
|
||||
raise IntakeError("REVIEW_STALE", "Review candidate or source changed")
|
||||
if state["candidates"][index].get("decision") is not None:
|
||||
raise IntakeError("REVIEW_ALREADY_DECIDED", "Evidence already has a decision")
|
||||
state["candidates"][index]["decision"] = dict(
|
||||
decision=decision.decision, checked=list(decision.checked),
|
||||
note=decision.note, reviewer=str(identity.user_id), evidence_sha256=decision.evidence_sha256)
|
||||
if manifest is not None:
|
||||
state["factual_inclusion"] = manifest
|
||||
from app.modules.documents.extraction_artifacts import bounded_json_bytes
|
||||
encoded = bounded_json_bytes(state, current["processing_profile"]["extraction"]["max_extraction_artifact_bytes"])
|
||||
connection.execute(text("UPDATE documents SET extraction_state=CAST(:state AS jsonb), updated_at=clock_timestamp() WHERE id=:id"),
|
||||
dict(state=encoded.decode(), id=document_id))
|
||||
if decision.decision == "reject":
|
||||
connection.execute(text("""
|
||||
UPDATE ingestion_jobs SET error_code='EXTRACTION_REVIEW_REJECTED',error_retryable=false,
|
||||
error_message='Retained evidence was rejected.',updated_at=clock_timestamp() WHERE id=:id
|
||||
"""), dict(id=job["id"]))
|
||||
response = dict(document_id=str(document_id), evidence_sha256=decision.evidence_sha256,
|
||||
decision=decision.decision, review_required=pending_review(state))
|
||||
connection.execute(text("""
|
||||
INSERT INTO audit_events
|
||||
(id,organization_id,actor_user_id,action,target_id,idempotency_key,request_hash,response_json)
|
||||
VALUES (:id,:org,:actor,'extraction_review',:document,:request,:hash,CAST(:response AS jsonb))
|
||||
"""), dict(id=uuid4(), org=identity.organization_id, actor=identity.user_id,
|
||||
document=document_id, request=request_id, hash=request_hash, response=json.dumps(response)))
|
||||
return dict(replayed=False, **response)
|
||||
Reference in New Issue
Block a user