fix(ingestion): accept observed OCR text alias in partial mode
This commit is contained in:
@@ -159,7 +159,16 @@ class OpenRouterVision:
|
|||||||
raw_dict = json.loads(raw_text)
|
raw_dict = json.loads(raw_text)
|
||||||
valid_types = {"paragraph", "heading", "table", "question", "answer", "visual_group", "caption"}
|
valid_types = {"paragraph", "heading", "table", "question", "answer", "visual_group", "caption"}
|
||||||
type_map = {"text": "paragraph", "body": "paragraph", "header": "heading", "title": "heading", "list": "paragraph"}
|
type_map = {"text": "paragraph", "body": "paragraph", "header": "heading", "title": "heading", "list": "paragraph"}
|
||||||
|
text_alias_used = False
|
||||||
for i, b in enumerate(raw_dict.get("blocks", [])):
|
for i, b in enumerate(raw_dict.get("blocks", [])):
|
||||||
|
# Observed provider field alias, only in explicit partial admission.
|
||||||
|
# Transfer verbatim text; conflicting fields must never be guessed.
|
||||||
|
if allow_partial_extraction(processing_profile) and "text_content" in b:
|
||||||
|
alias = b["text_content"]
|
||||||
|
if not isinstance(alias, str) or ("text" in b and b["text"] != alias):
|
||||||
|
raise ExtractionError("Conflicting vision text fields")
|
||||||
|
b["text"] = b.pop("text_content")
|
||||||
|
text_alias_used = True
|
||||||
if b.get("block_type") not in valid_types:
|
if b.get("block_type") not in valid_types:
|
||||||
b["block_type"] = type_map.get(str(b.get("block_type", "")).lower(), "paragraph")
|
b["block_type"] = type_map.get(str(b.get("block_type", "")).lower(), "paragraph")
|
||||||
if b.get("method") not in ("ocr", "vision"):
|
if b.get("method") not in ("ocr", "vision"):
|
||||||
@@ -190,6 +199,8 @@ class OpenRouterVision:
|
|||||||
}))
|
}))
|
||||||
# Recognition diagnostics belong to the exact review candidate.
|
# Recognition diagnostics belong to the exact review candidate.
|
||||||
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
|
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
|
||||||
|
if text_alias_used:
|
||||||
|
warnings += ("Provider text_content field mapped verbatim to text",)
|
||||||
if warnings:
|
if warnings:
|
||||||
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
|
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
|
||||||
if allow_partial_extraction(processing_profile):
|
if allow_partial_extraction(processing_profile):
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ class ExtractionError(ValueError):
|
|||||||
# Only fixed categories enter logs; never exception/provider payload text.
|
# Only fixed categories enter logs; never exception/provider payload text.
|
||||||
self.reason_code = {
|
self.reason_code = {
|
||||||
"Invalid vision transcription response": "invalid_vision_schema",
|
"Invalid vision transcription response": "invalid_vision_schema",
|
||||||
|
"Conflicting vision text fields": "conflicting_vision_text_fields",
|
||||||
"Vision reports unreadable source regions": "unreadable_vision_regions",
|
"Vision reports unreadable source regions": "unreadable_vision_regions",
|
||||||
"Vision evidence identity, location or readability mismatch": "invalid_vision_evidence",
|
"Vision evidence identity, location or readability mismatch": "invalid_vision_evidence",
|
||||||
"Vision transcription incomplete or blocked": "incomplete_or_blocked_vision",
|
"Vision transcription incomplete or blocked": "incomplete_or_blocked_vision",
|
||||||
|
|||||||
@@ -1612,3 +1612,21 @@ Executed validation:
|
|||||||
Limitations: Real hosted model compatibility, retrieval quality, and tokenizer
|
Limitations: Real hosted model compatibility, retrieval quality, and tokenizer
|
||||||
distributions remain unverified by mock and arithmetic tests. Phase 5 worker claim
|
distributions remain unverified by mock and arithmetic tests. Phase 5 worker claim
|
||||||
fencing and publication remain required before staged vectors can be published.
|
fencing and publication remain required before staged vectors can be published.
|
||||||
|
|
||||||
|
|
||||||
|
## OpenRouter text field alias repair (2026-10-14)
|
||||||
|
|
||||||
|
Photo f9d74e4c-8aeb-42e5-b99d-600d95e87686 repeatedly failed extraction after
|
||||||
|
successful manual retries. Bounded provider inspection identified 15 blocks with
|
||||||
|
text_content instead of the required text field; recognition content was not logged.
|
||||||
|
In explicit allow_partial_extraction mode only, OpenRouter now maps this observed
|
||||||
|
alias verbatim, retaining an artifact warning. Different simultaneous text fields,
|
||||||
|
non-string/empty content, unknown extra fields and malformed relationships remain
|
||||||
|
rejected; strict admission is unchanged. No profile rewrite or schema migration.
|
||||||
|
|
||||||
|
58 targeted provider-free extraction/admission regressions passed. The previous
|
||||||
|
worker image is retained as rag-worker-rollback:20261014. Only worker was rebuilt;
|
||||||
|
API and the preserved original rag-api container were untouched. Same-document,
|
||||||
|
same-job official retry generation 3 completed through extraction, chunking,
|
||||||
|
embedding and atomic publication: status ready, 7 chunks. This proves this upload's
|
||||||
|
runtime completion, not complete OCR accuracy. Selection still requires activation.
|
||||||
|
|||||||
@@ -136,3 +136,42 @@ def test_openrouter_fatal_output_stays_fatal(settings,monkeypatch,failure):
|
|||||||
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener',lambda *a:Opener())
|
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener',lambda *a:Opener())
|
||||||
with pytest.raises(ExtractionError):
|
with pytest.raises(ExtractionError):
|
||||||
OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',api_key='fixture',timeout_seconds=60).transcribe(image_bytes(),page=None,section='image',processing_profile=profile)
|
OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',api_key='fixture',timeout_seconds=60).transcribe(image_bytes(),page=None,section='image',processing_profile=profile)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("partial,variant,accepted", [
|
||||||
|
(True, "alias", True), (False, "alias", False),
|
||||||
|
(True, "same", True), (True, "conflict", False),
|
||||||
|
(True, "empty", False), (True, "wrong_type", False),
|
||||||
|
(True, "unknown_extra", False),
|
||||||
|
])
|
||||||
|
def test_openrouter_observed_text_alias_preserves_text_and_rejects_ambiguity(
|
||||||
|
settings, monkeypatch, partial, variant, accepted):
|
||||||
|
from io import BytesIO
|
||||||
|
from app.infrastructure.openrouter_vision import OpenRouterVision
|
||||||
|
from app.modules.documents.extraction import ExtractionError
|
||||||
|
profile = settings.model_copy(update={"allow_partial_extraction":partial,
|
||||||
|
"vision_provider":"openrouter", "vision_endpoint":"https://example.invalid/v1beta",
|
||||||
|
"vision_model":"fixture-flash"}).processing_profile()
|
||||||
|
transcript = json.loads(native(profile)["candidates"][0]["content"]["parts"][0]["text"])
|
||||||
|
original = [b["text"] for b in transcript["blocks"]]
|
||||||
|
for b in transcript["blocks"]:
|
||||||
|
b["text_content"] = b.pop("text")
|
||||||
|
if variant == "same": b["text"] = b["text_content"]
|
||||||
|
if variant == "conflict": b["text"] = "DIFFERENT SOURCE"
|
||||||
|
if variant == "empty": b["text_content"] = ""
|
||||||
|
if variant == "wrong_type": b["text_content"] = ["not a string"]
|
||||||
|
if variant == "unknown_extra": b["unknown_content"] = "unexpected"
|
||||||
|
class Opener:
|
||||||
|
def open(self, request, *, timeout):
|
||||||
|
return BytesIO(json.dumps({"choices":[{"message":{"content":json.dumps(transcript)}}]}).encode())
|
||||||
|
monkeypatch.setattr("app.infrastructure.openrouter_vision.build_opener", lambda *a: Opener())
|
||||||
|
adapter = OpenRouterVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
|
||||||
|
api_key="fixture-only", timeout_seconds=60)
|
||||||
|
if not accepted:
|
||||||
|
with pytest.raises(ExtractionError):
|
||||||
|
adapter.transcribe(image_bytes(),page=None,section="image",processing_profile=profile)
|
||||||
|
else:
|
||||||
|
blocks = adapter.transcribe(image_bytes(),page=None,section="image",processing_profile=profile)
|
||||||
|
assert [b.text for b in blocks] == original
|
||||||
|
assert all("Provider text_content field mapped verbatim to text" in b.warnings for b in blocks)
|
||||||
|
assert blocks[1].parent_block_id == blocks[0].block_id
|
||||||
|
|||||||
Reference in New Issue
Block a user