"""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": "", "position-down": ""}.get(prop, f"") reset_xml = "" if prop.startswith("position") else f"" styles, ps, rs, direct = "", "", "", "" if location == "direct": direct = value elif location == "defaults": styles = f"{value}" else: kind = "character" if "character" in location else "paragraph" styles = f"{value}" name = "Base" if location.startswith("inherited"): styles += f"" name = "Child" if location != "unused": if kind == "paragraph": ps = f"" else: rs = f"" if reset: direct = reset_xml body = f"{ps}{rs}{direct}10 3 not abc" return document(body, styles) def document(body, styles=""): extras = {"word/styles.xml": f"{styles}".encode()} if styles else None return docx_bytes(extras, f"{body}".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"" if level else "" return f"{props}{text}" STYLES = "".join(f"" for i in range(1, 5)) def table(text): return "" + p(text) + "" 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(""+paragraphs+""); 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(""+(p("Question: What?")+p("Answer: ordinary visible text"))*100+"") 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 = "10"+f""+"3 abc" 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("Rule one.", "Rule one."), 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("e\u0301")}[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)