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
+192
View File
@@ -0,0 +1,192 @@
"""OpenRouter REST multimodal vision adapter."""
import base64
from io import BytesIO
import json
import math
import re
import time
from queue import Queue, Empty
from threading import Thread, BoundedSemaphore
from urllib.request import Request, HTTPRedirectHandler, build_opener
from urllib.error import HTTPError, URLError
from pydantic import BaseModel, ConfigDict
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError, unreadable
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.types import ExtractedBlock
from app.infrastructure.gemini_vision import Transcription, INSTRUCTION, _TRANSPORT_CAPACITY
class _NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
class OpenRouterVision:
def __init__(self, *, endpoint, model, api_key, timeout_seconds, provider="openrouter"):
if provider != "openrouter" or not model or not model.strip():
raise ValueError("Explicit OpenRouter provider and model identity required")
if not endpoint.startswith("https://") or "?" in endpoint or "#" in endpoint:
raise ValueError("OpenRouter endpoint requires HTTPS without query/fragment")
if not api_key or not api_key.strip() or not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
raise ValueError("Vision credentials and bounded timeout required")
self.endpoint = endpoint.rstrip("/")
self.model = model
self._key = api_key
self.timeout = timeout_seconds
self._transport_capacity = _TRANSPORT_CAPACITY
def transcribe(self, image, *, page, section, processing_profile):
from PIL import Image
extraction = processing_profile["extraction"]
frozen = extraction["vision"]
if (frozen["provider"] != "openrouter" or frozen["endpoint"].rstrip("/") != self.endpoint
or frozen["model"] != self.model or frozen["timeout_seconds"] != self.timeout):
raise ExtractionError("Vision adapter differs from frozen identity or timeout")
if len(image) > processing_profile["limits"]["max_original_bytes"]:
raise ExtractionError("Vision image byte limit exceeded")
with Image.open(BytesIO(image)) as decoded:
if decoded.width * decoded.height > extraction["max_rendered_page_pixels"]:
raise ExtractionError("Vision image exceeds pixel limit")
mime = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(decoded.format)
if mime is None:
raise ExtractionError("Vision requires PNG/JPEG")
context = json.dumps(dict(page=page, source_locator_prefix=section + "/",
section=section, actual_model=self.model))
prompt_text = INSTRUCTION + "\nRequired location/identity: " + context
b64_data = base64.b64encode(image).decode()
payload = json.dumps({
"model": self.model,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64_data}"}}
]
}
],
"response_format": {"type": "json_object"},
"temperature": 0
}).encode()
request = Request(
self.endpoint + "/chat/completions",
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + self._key
}
)
limit = extraction["max_extraction_artifact_bytes"]
deadline = time.monotonic() + self.timeout
def remaining():
duration = deadline - time.monotonic()
if duration <= 0:
raise ExtractionProviderError("Vision request deadline exceeded", retryable=True)
return duration
def collect():
try:
with build_opener(_NoRedirect()).open(request, timeout=remaining()) as response:
remaining()
content = bytearray()
while True:
remaining()
part = response.read(min(65536, limit + 1 - len(content)))
remaining()
if not part:
break
content.extend(part)
if len(content) > limit:
raise ExtractionError("Vision response byte limit exceeded")
return bytes(content)
except HTTPError as exc:
try:
exc.close()
except Exception:
remaining()
raise ExtractionProviderError("Vision provider cleanup failed", retryable=True) from None
remaining()
raise ExtractionProviderError(
"Vision provider request failed",
retryable=exc.code in (408, 429) or 500 <= exc.code < 600
) from None
except (URLError, TimeoutError, OSError):
raise ExtractionProviderError("Vision provider request failed", retryable=True) from None
outcome = Queue(maxsize=1)
def request_once():
try:
result = (True, collect())
except Exception as exc:
result = (False, exc)
finally:
self._transport_capacity.release()
outcome.put(result)
if not self._transport_capacity.acquire(blocking=False):
raise ExtractionProviderError("Vision transport capacity occupied", retryable=True)
thread = Thread(target=request_once, name="openrouter-vision-request", daemon=True)
try:
thread.start()
except Exception:
self._transport_capacity.release()
raise ExtractionProviderError("Vision transport unavailable", retryable=True) from None
try:
success, result = outcome.get(timeout=remaining())
except Empty:
raise ExtractionProviderError("Vision request deadline exceeded", retryable=True) from None
remaining()
if not success:
raise result
content = result
try:
native = json.loads(content)
choices = native.get("choices")
if not choices or not isinstance(choices, list):
raise ExtractionError("Vision transcription incomplete or blocked")
message = choices[0].get("message", {})
raw_text = message.get("content", "")
raw_dict = json.loads(raw_text)
valid_types = {"paragraph", "heading", "table", "question", "answer", "visual_group", "caption"}
type_map = {"text": "paragraph", "body": "paragraph", "header": "heading", "title": "heading", "list": "paragraph"}
for i, b in enumerate(raw_dict.get("blocks", [])):
if b.get("block_type") not in valid_types:
b["block_type"] = type_map.get(str(b.get("block_type", "")).lower(), "paragraph")
if b.get("method") not in ("ocr", "vision"):
b["method"] = "vision"
if not b.get("actual_model"):
b["actual_model"] = self.model
if not b.get("block_id"):
b["block_id"] = f"b_{i}"
if "ordinal" not in b or type(b["ordinal"]) is not int:
b["ordinal"] = i
transcript = Transcription.model_validate(raw_dict)
if not transcript.complete or transcript.warnings or not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain")
if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = []
for index, block in enumerate(transcript.blocks):
locator = block.source_locator if block.source_locator and block.source_locator.startswith(section + "/") else f"{section}/block/{index + 1}"
if unreadable(block.text) or any("unreadable" in w.lower() or "ناخوانا" in w for w in block.warnings):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={
"ordinal": index,
"method": "vision",
"actual_model": self.model,
"page": page,
"source_locator": locator,
"search_text": normalize_search_text(block.text, processing_profile["normalizer"])
}))
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
raise
raise ExtractionError("Invalid vision transcription response") from None