Files
amirhosein mazaheri 5ef02d39a9 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
2026-10-07 16:21:01 +03:30

194 lines
12 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Bounded Phase 3 closure regressions; generated sources, no providers."""
from copy import deepcopy
import pytest
from app.modules.documents.extraction import ExtractionError, PageBlockExtractor
from app.modules.documents.chunking import chunk_extraction, rule_references
from app.modules.documents.formats import DOCX_MIME
from tests.support.formats import docx_bytes
from tests.support.extraction import extract
NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@pytest.fixture
def profile(settings):
return settings.processing_profile()
def formatted(prop, location, reset=False):
value = {"position-up": "<w:position w:val='6'/>", "position-down": "<w:position w:val='-6'/>"}.get(prop, f"<w:{prop}/>")
reset_xml = "<w:position w:val='0'/>" if prop.startswith("position") else f"<w:{prop} w:val='false'/>"
styles, ps, rs, direct = "", "", "", ""
if location == "direct":
direct = value
elif location == "defaults":
styles = f"<w:docDefaults><w:rPrDefault><w:rPr>{value}</w:rPr></w:rPrDefault></w:docDefaults>"
else:
kind = "character" if "character" in location else "paragraph"
styles = f"<w:style w:type='{kind}' w:styleId='Base'><w:rPr>{value}</w:rPr></w:style>"
name = "Base"
if location.startswith("inherited"):
styles += f"<w:style w:type='{kind}' w:styleId='Child'><w:basedOn w:val='Base'/></w:style>"
name = "Child"
if location != "unused":
if kind == "paragraph": ps = f"<w:pStyle w:val='{name}'/>"
else: rs = f"<w:rStyle w:val='{name}'/>"
if reset: direct = reset_xml
body = f"<w:p><w:pPr>{ps}</w:pPr><w:r><w:rPr>{rs}{direct}</w:rPr><w:t>10 3 not abc</w:t></w:r></w:p>"
return document(body, styles)
def document(body, styles=""):
extras = {"word/styles.xml": f"<w:styles xmlns:w='{NS}'>{styles}</w:styles>".encode()} if styles else None
return docx_bytes(extras, f"<w:document xmlns:w='{NS}'><w:body>{body}</w:body></w:document>".encode())
@pytest.mark.parametrize("prop", ["position-up", "position-down", "caps", "smallCaps", "webHidden", "specVanish"])
@pytest.mark.parametrize("location", ["direct", "defaults", "paragraph", "inherited-paragraph", "character", "inherited-character"])
def test_semantic_transforms(profile, prop, location):
with pytest.raises(ExtractionError, match="semantic"):
extract(formatted(prop, location), profile, DOCX_MIME)
@pytest.mark.parametrize("prop", ["position-up", "caps", "smallCaps", "webHidden", "specVanish"])
@pytest.mark.parametrize("location", ["direct", "defaults", "inherited-paragraph", "inherited-character"])
def test_semantic_resets(profile, prop, location):
assert extract(formatted(prop, location, True), profile, DOCX_MIME).blocks[0].text == "10 3 not abc\n"
@pytest.mark.parametrize("prop", ["position-up", "caps", "smallCaps", "webHidden", "specVanish", "b", "i"])
def test_unused_and_harmless(profile, prop):
assert extract(formatted(prop, "unused"), profile, DOCX_MIME).complete
if prop in ("b", "i"):
assert extract(formatted(prop, "direct"), profile, DOCX_MIME).complete
def p(text, level=None):
props = f"<w:pPr><w:pStyle w:val='Heading{level}'/></w:pPr>" if level else ""
return f"<w:p>{props}<w:r><w:t>{text}</w:t></w:r></w:p>"
STYLES = "".join(f"<w:style w:type='paragraph' w:styleId='Heading{i}'><w:pPr><w:outlineLvl w:val='{i-1}'/></w:pPr></w:style>" for i in range(1, 5))
def table(text):
return "<w:tbl><w:tr><w:tc>" + p(text) + "</w:tc></w:tr></w:tbl>"
def faq_source():
return p("Question: What?", 2) + p("Answer: Rule.", 2) + p("Required documents", 3) + p("Passport.") + table("Proof.") + p("Exceptions", 4) + p("Unless exempt.") + table("No guessed numbers.") + p("Second paragraph.") + p("Question: When?", 2) + p("Answer: Now.", 2) + p("Background", 1) + p("Separate.")
def test_docx_answer_hierarchy_and_tables(profile):
envelope = extract(document(faq_source(), STYLES), profile, DOCX_MIME)
group = envelope.blocks[0].group_id
expected = ["Question: What?\n", "Answer: Rule.\n", "Required documents\n", "Passport.\n", "Proof.\n", "Exceptions\n", "Unless exempt.\n", "No guessed numbers.\n", "Second paragraph.\n"]
assert [b.text for b in envelope.blocks if b.group_id == group] == expected
assert all(b.page is None for b in envelope.blocks)
assert "table/1/row/1/cell/1" in envelope.blocks[4].source_locator
chunks = chunk_extraction(envelope, profile, corpus_purpose="approved_factual")
assert chunks[0].text == "".join(expected)
assert len(chunks) == 3
assert [c.ordinal for c in chunks] == list(range(3))
small = deepcopy(profile); small["chunk_size"] = 80; small["overlap"] = 0
with pytest.raises(ExtractionError, match="Semantic group"):
chunk_extraction(envelope, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("body", [p("Question: What?", 2)+p("Required documents", 3), p("Question: What?", 2)+p("Answer: Now.", 3), p("Question: What?", 2)+p("Answer: Now.", 2)+p("Question: nested?", 3)])
def test_docx_ambiguous_pairs_rejected(profile, body):
with pytest.raises(ExtractionError, match="FAQ"):
extract(document(body, STYLES), profile, DOCX_MIME)
@pytest.mark.parametrize("phrase", ["Articles 13 and 14", "Article 12 and 13", "Article 12, 13", "Article 12 through 13", "مواد ۱۳ و ۱۴", "ماده ۱۲ و ۱۳", "Clauses 1(a), 1(b)", "Circulars 1403/100 and 1403/200"])
def test_complete_dependency_targets(profile, phrase):
envelope = extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".\n").encode(), profile)
with pytest.raises(ExtractionError, match="reference|identifier"):
chunk_extraction(envelope, profile)
@pytest.mark.parametrize("phrase", ["Article 12 and 12", "Article ۱۲, 12", "ماده ۱۲ و 12", "Article 12 through 12"])
def test_matching_list_targets(profile, phrase):
envelope = extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".\n").encode(), profile)
assert len(chunk_extraction(envelope, profile)) == 1
def test_incidental_lists_and_ordinary_decision(profile):
text = "Article 12\nThe decision is final.\n\n# Notes\nSee Articles 13 and 14.\n"
assert len(chunk_extraction(extract(text.encode(), profile), profile)) == 1
@pytest.mark.parametrize("phrase", ["Article XII", "Article 12-13", "Article 12 and XIII", "Article 12 through 13.1", "Articles", "ماده ۱۲ الی سیزده"])
def test_unsupported_targets(phrase):
with pytest.raises(ExtractionError, match="identifier"):
rule_references(phrase)
@pytest.mark.parametrize("source", ["plain", "faq", "docx", "cell"])
@pytest.mark.parametrize("limit", ["blocks", "characters", "bytes"])
def test_incremental_output_stops(profile, monkeypatch, source, limit):
if limit == "blocks": profile["extraction"]["max_extracted_blocks"] = 2
elif limit == "characters": profile["limits"]["max_normalized_characters"] = 65
else: profile["extraction"]["max_extraction_artifact_bytes"] = 1500
count = []
original = PageBlockExtractor._block
def observed(self, text, *args, **kwargs):
count.append(text)
return original(self, text, *args, **kwargs)
monkeypatch.setattr(PageBlockExtractor, "_block", observed)
if source == "plain": data = ("ordinary visible text\n\n"*100).encode(); mime="text/plain"
elif source == "faq": data = ("Question: What?\nAnswer: ordinary visible text\n"*100).encode(); mime="text/plain"
elif source == "docx": data=document(p("ordinary visible text")*100); mime=DOCX_MIME
else:
paragraphs = (p("Question: What?")+p("Answer: ordinary visible text"))*100 if limit == "blocks" else p("ordinary visible text")*100
data=document("<w:tbl><w:tr><w:tc>"+paragraphs+"</w:tc></w:tr></w:tbl>"); mime=DOCX_MIME
with pytest.raises(ValueError, match="limit|budget"):
extract(data, profile, mime)
assert len(count) <= 5
@pytest.mark.parametrize("limit", ["blocks", "characters", "bytes"])
def test_cell_block_budget_stops_before_later_paragraphs(profile, monkeypatch, limit):
from app.modules.documents import extraction
if limit == "blocks": profile["extraction"]["max_extracted_blocks"] = 2
elif limit == "characters": profile["limits"]["max_normalized_characters"] = 65
else: profile["extraction"]["max_extraction_artifact_bytes"] = 1500
calls = []
original = extraction._TextCounter.add
def observed(self, text):
calls.append(text)
return original(self, text)
monkeypatch.setattr(extraction._TextCounter, "add", observed)
source = document("<w:tbl><w:tr><w:tc>"+(p("Question: What?")+p("Answer: ordinary visible text"))*100+"</w:tc></w:tr></w:tbl>")
with pytest.raises(ValueError, match="limit|budget"):
extract(source, profile, DOCX_MIME)
assert len(calls) < 20 if limit == "blocks" else len(calls) < 100
@pytest.mark.parametrize("prop,value", [("position", "6"), ("position", "-6"), ("caps", "true")])
def test_actual_digit_and_case_evidence(profile, prop, value):
body = "<w:p><w:r><w:t>10</w:t></w:r><w:r><w:rPr>"+f"<w:{prop} w:val='{value}'/>"+"</w:rPr><w:t>3 abc</w:t></w:r></w:p>"
with pytest.raises(ExtractionError, match="semantic"):
extract(document(body), profile, DOCX_MIME)
def test_docx_structural_dependency_interactions(profile):
body = p("Question: What?",2)+p("Answer: Rules.",2)+p("Article 12",3)+p("Rule one.")+p("Conditions",4)+table("Applies only to Article ۱۲ and 12.")+p("Article 13",3)+p("Rule two.")+p("Exceptions",4)+p("Applies only to Article 13.")+p("Background",3)+p("Historical context concerns Article 99.")
value = extract(document(body, STYLES), profile, DOCX_MIME)
assert len({b.group_id for b in value.blocks}) == 1
assert value.blocks[5].parent_block_id == value.blocks[4].block_id
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 1 and chunks[0].text == "".join(b.text for b in value.blocks)
assert chunk_extraction(value, profile, corpus_purpose="approved_factual") == chunks
with pytest.raises(ExtractionError, match="reference"):
bad=extract(document(body.replace("Article ۱۲ and 12", "Article 12 and 13"), STYLES),profile,DOCX_MIME)
chunk_extraction(bad,profile,corpus_purpose="approved_factual")
with pytest.raises(ExtractionError,match="semantic"):
extract(document(body.replace("<w:t>Rule one.</w:t>", "<w:rPr><w:caps/></w:rPr><w:t>Rule one.</w:t>"), STYLES),profile,DOCX_MIME)
def test_heading_labels_without_colons(profile):
value = extract(document(p("Question",2)+p("What?")+p("Answer",2)+p("Now.")+table("No exceptions."), STYLES),profile,DOCX_MIME)
assert {b.block_type for b in value.blocks} == {"question", "answer"}
assert len(chunk_extraction(value,profile,corpus_purpose="approved_factual")) == 1
@pytest.mark.parametrize("source", ["plain","faq","docx"])
def test_exact_artifact_and_normalized_budgets(profile, source):
from app.modules.documents.extraction_artifacts import serialize_artifact
data = {"plain": "e\u0301\r\n Persian‌\r text".encode(), "faq": "Question: e\u0301?\r\nAnswer: ۱۲.۵ نیست‌\r".encode(), "docx": document("<w:p><w:r><w:t>e</w:t></w:r><w:r><w:t>\u0301</w:t></w:r></w:p>")}[source]
mime=DOCX_MIME if source=="docx" else "text/plain"
value=extract(data,profile,mime)
count=sum(len(b.search_text) for b in value.blocks)
exact=len(serialize_artifact(value,profile))
bounded=deepcopy(profile); bounded["limits"]["max_normalized_characters"]=count; bounded["extraction"]["max_extraction_artifact_bytes"]=exact
assert extract(data,bounded,mime).blocks == value.blocks
bounded["extraction"]["max_extraction_artifact_bytes"]-=1
with pytest.raises(ValueError,match="byte limit"):
extract(data,bounded,mime)
@pytest.mark.parametrize("phrase", ["Article 12 or 13", "ماده ۱۲ یا ۱۳"])
def test_alternative_targets_rejected(profile,phrase):
value=extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".").encode(),profile)
with pytest.raises(ExtractionError,match="reference|identifier"):
chunk_extraction(value,profile)