"""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.extraction_artifacts import allow_partial_extraction 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 isinstance(choices, list) or len(choices) != 1: raise ExtractionError("Vision transcription incomplete or blocked") if choices[0].get("finish_reason") not in (None, "stop"): 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.blocks: raise ExtractionError("Vision transcription has no candidate blocks") 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) and not (allow_partial_extraction(processing_profile) and any(c.isalnum() for c in block.text)): 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"]) })) # Recognition diagnostics belong to the exact review candidate. warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",)) if warnings: blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks] if allow_partial_extraction(processing_profile): blocks = [b.model_copy(update={"warnings": b.warnings + (("Unrecognized characters retained",) if unreadable(b.text) else ())}) for b in blocks] return tuple(blocks) except (KeyError, TypeError, ValueError, AttributeError) as exc: if isinstance(exc, ExtractionError): raise raise ExtractionError("Invalid vision transcription response") from None