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
+834
View File
@@ -0,0 +1,834 @@
"""Bounded faithful extraction and immediate QC. No database/provider initialization."""
from collections.abc import Mapping
from dataclasses import dataclass
import hashlib
from io import BytesIO
import json
import math
import re
from types import SimpleNamespace
import unicodedata
from uuid import UUID
from zipfile import ZipFile
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact
from .formats import DOCX_MIME, validate_docx, validate_image
from .normalization import normalize_search_text, normalized_inputs
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
class ExtractionError(ValueError):
"""Permanent, redacted processing failure; later worker maps to existing failed state."""
code = "EXTRACTION_QUALITY_FAILED"
retryable = False
class ExtractionProviderError(ExtractionError):
code = "EXTRACTION_PROVIDER_FAILED"
def __init__(self, message, *, retryable):
super().__init__(message)
self.retryable = retryable
@dataclass(frozen=True)
class ReviewApproval:
"""Precompleted manual inspection, bound to source, profile and exact candidate."""
evidence_sha256: str
reviewer: str
note: str
checked: tuple[str, ...]
approved: bool = True
REVIEW_CHECKS = ("readability", "order", "completeness", "numbers", "dates",
"negation", "exceptions")
QUESTION = re.compile(r"^\s*(?:#{1,6}\s+)?(?:\*\*)?(?:سؤال|سوال|پرسش|question|q)\s*(?:\*\*)?[::]", re.I)
ANSWER = re.compile(r"^\s*(?:#{1,6}\s+)?(?:\*\*)?(?:پاسخ|جواب|answer|a)\s*(?:\*\*)?[::]", re.I)
RULE = re.compile(r"^\s*(?:#{1,6}\s+|ماده\s*\d|بند\s|Article\s+\d|Clause\s+\d|Circular\s+\S|Decision\s+\d|بخشنامه\s+\S|تصمیم\s+\d)", re.I)
PLACEHOLDER = re.compile(r"<[^>]*(?:placeholder|verified|approved|current|مقدار)[^>]*>|"
r"\[(?:TODO|TBD|placeholder|مقدار|تکمیل)[^\]]*\]|"
r"\{\{[^}]+\}\}", re.I)
HEADING = re.compile(r"^\s*(#{1,6})\s+")
FAQ_HEADING = re.compile(r"^\s*#{1,6}\s+(Question|Answer|سؤال|سوال|پرسش|پاسخ|جواب)\s*$", re.I)
def faq_role(line):
if QUESTION.match(line):
return "question"
if ANSWER.match(line):
return "answer"
match = FAQ_HEADING.match(line)
if match:
return "question" if match[1].lower() in {"question", "سؤال", "سوال", "پرسش"} else "answer"
return None
def unreadable(text):
return (not text.strip() or "\ufffd" in text or "(cid:" in text
or any(unicodedata.category(c) in {"Cc", "Cs"} and c not in "\n\r\t" for c in text))
def review_digest(*, original_sha256, profile_digest, locator, image, blocks):
payload = dict(original=original_sha256, profile=profile_digest, locator=locator,
image_sha256=hashlib.sha256(image).hexdigest(),
blocks=[b.model_dump(mode="json") for b in blocks])
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
separators=(",", ":")).encode()).hexdigest()
class RejectedReview(ExtractionError):
pass
class ReviewRequired(ExtractionError):
"""Carries inspection evidence; never a successful/indexable extraction."""
def __init__(self, evidence_sha256, locator, image, blocks, reasons):
super().__init__("Manual extraction inspection required; no indexable output")
self.evidence_sha256 = evidence_sha256
self.locator = locator
self.image = image
self.blocks = tuple(blocks)
self.reasons = tuple(reasons)
class _ConstructionBudget:
"""Count each completed block once; pending text is checked before assembly."""
def __init__(self, extractor):
self.profile = extractor.profile
self.count = self.characters = 0
self.limit = self.profile["extraction"]["max_extraction_artifact_bytes"]
data = dict(artifact_schema=1, document_id=str(extractor.document_id),
title=extractor.title, original_sha256=extractor.original_hash,
extraction_profile_sha256=extractor.profile_digest,
normalization_policy=self.profile["normalizer"], complete=True,
quality_decision="passed", warnings=[], review_annotations=[], blocks=[])
self.bytes = bounded_json_size(data, self.limit)
def size(self, block, ordinal):
return bounded_json_size(dict(block.model_dump(mode="json"), ordinal=ordinal), self.limit)
def add(self, block):
byte_count = self.size(block, self.count) + bool(self.count)
self.check(1, len(block.search_text), byte_count)
self.count += 1
self.characters += len(block.search_text)
self.bytes += byte_count
def remove(self, block):
self.count -= 1
self.bytes -= self.size(block, self.count) + bool(self.count)
self.characters -= len(block.search_text)
def check(self, count, characters, byte_count):
if self.count + count > self.profile["extraction"]["max_extracted_blocks"]:
raise ExtractionError("Extracted block limit exceeded")
if self.characters + characters > self.profile["limits"]["max_normalized_characters"]:
raise ExtractionError("Normalized input exceeds character budget")
if self.bytes + byte_count > self.limit:
raise ExtractionError("Extraction artifact exceeds byte limit")
class _TextCounter:
"""Streaming NFC/LF length and JSON-byte counter, including cross-run seams."""
def __init__(self, budget):
self.budget = budget
self.faithful_bytes = self.stable_bytes = self.stable_characters = 0
self.tail = ""
self.pending_cr = False
def add(self, text):
# JSON quoting overhead is excluded; only string contents contribute here.
self.faithful_bytes += bounded_json_size(text, self.budget.limit) - 2
pending_cr = text.endswith("\r") if text else self.pending_cr
if self.pending_cr and text.startswith("\n"):
text = text[1:]
self.pending_cr = pending_cr
normalized = normalize_search_text(self.tail + text, self.budget.profile["normalizer"])
# Retain the last starter and its combining sequence. This also handles
# Hangul composition when the next fragment begins with another Jamo.
split = len(normalized)
while split and unicodedata.combining(normalized[split - 1]):
split -= 1
split = max(0, split - 1)
stable, self.tail = normalized[:split], normalized[split:]
self.stable_characters += len(stable)
self.stable_bytes += bounded_json_size(stable, self.budget.limit) - 2
self.budget.check(0, self.stable_characters + len(self.tail),
self.faithful_bytes + self.stable_bytes
+ bounded_json_size(self.tail, self.budget.limit) - 2)
class PageBlockExtractor:
def __init__(self, vision=None, *, reviews=(), retained=None, owned=None, factual_retention=False):
self.retained, self.owned = retained, owned or (lambda: None)
self.factual_retention = factual_retention
self.vision = vision
self.reviews = {r.evidence_sha256: r for r in reviews}
def _review(self, blocks, image, locator, reasons):
self._budget(blocks)
digest = review_digest(original_sha256=self.original_hash,
profile_digest=self.profile_digest, locator=locator,
image=image, blocks=blocks)
approval = self.reviews.get(digest)
if (approval is None or not approval.reviewer.strip() or not approval.note.strip()
or set(approval.checked) != set(REVIEW_CHECKS)):
raise ReviewRequired(digest, locator, image, blocks, reasons)
if not approval.approved:
raise RejectedReview("Manual inspection rejected extraction")
self.reviewed = True
self.annotations.append(ExtractionReviewAnnotation(evidence_sha256=digest, locator=locator,
reviewer=approval.reviewer, checked=approval.checked, note=approval.note))
reviewed = [b.model_copy(update={"warnings": b.warnings + tuple(reasons)}) for b in blocks]
self._budget(reviewed)
return reviewed
def _block(self, text, locator, method, *, page=None, **kwargs):
block = ExtractedBlock(ordinal=0, block_id=locator, text=text,
search_text=normalize_search_text(text, self.profile["normalizer"]),
source_locator=locator, section=locator, page=page, method=method, **kwargs)
if self.construction is not None:
self.construction.add(block)
return block
def extract(self, *, document_id: UUID, title: str, original_sha256: str,
content: bytes, mime_type: str, processing_profile: Mapping) -> ExtractionEnvelope:
# A fresh session avoids sharing mutable per-document state across calls.
session = PageBlockExtractor(self.vision, reviews=self.reviews.values(),
retained=self.retained, owned=self.owned, factual_retention=self.factual_retention)
return session._extract(document_id, title, original_sha256, content, mime_type, processing_profile)
def extract_for_review(self, *, retained=None, owned=None, **kwargs):
session = PageBlockExtractor(self.vision, retained=retained, owned=owned, factual_retention=True)
return session.extract(**kwargs)
def _resume(self, locator):
self.owned()
if self.retained is None:
return None
retained = self.retained(locator)
if retained is None:
return None
body, decision = retained
if (decision.get("decision") != "approve" or set(decision.get("checked", ())) != set(REVIEW_CHECKS)
or decision.get("evidence_sha256") != body["evidence_sha256"]
or not decision.get("reviewer") or not decision.get("note")):
raise ExtractionError("Retained output is not approved")
blocks = tuple(ExtractedBlock.model_validate(b) for b in body["blocks"])
self.annotations.append(ExtractionReviewAnnotation(evidence_sha256=body["evidence_sha256"],
locator=locator, reviewer=decision["reviewer"], checked=tuple(decision["checked"]),
note=decision["note"]))
self.reviewed = True
result = [b.model_copy(update={"warnings": b.warnings + tuple(body["reasons"])}) for b in blocks]
self._budget(result)
self.owned()
return result
def _extract(self, document_id, title, original_hash, content, mime_type, profile):
self.owned()
self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider
self.original_hash, self.profile, self.reviewed = original_hash, profile, False
self.document_id, self.title = document_id, title
self.annotations = []
extraction = profile["extraction"]
self.construction = _ConstructionBudget(self) if mime_type in ("text/markdown", "text/plain", DOCX_MIME) else None
if (extraction["strategy"] != "direct-quality-fallback-v1"
or extraction["quality_policy"] != "bounded-checks-manual-review-v1"
or extraction["fallback_policy"] != "affected-pages-v1"):
raise ExtractionError("Unsupported frozen extraction policy")
if len(content) > profile["limits"]["max_original_bytes"]:
raise ExtractionError("Original byte limit exceeded")
if hashlib.sha256(content).hexdigest() != original_hash:
raise ExtractionError("Original checksum mismatch")
if mime_type in ("text/markdown", "text/plain"):
try:
text = content.decode("utf-8-sig")
except UnicodeError:
raise ExtractionError("Readable text must be UTF-8") from None
if unreadable(text):
raise ExtractionError("Unreadable source text")
blocks = self._text(text)
elif mime_type == DOCX_MIME:
blocks = self._docx(content)
elif mime_type == "application/pdf":
blocks = self._pdf(content)
elif mime_type in ("image/jpeg", "image/png"):
validate_image(".png" if mime_type == "image/png" else ".jpg", content,
SimpleNamespace(**profile["intake"]))
blocks = self._vision(content, None, "image")
else:
raise ExtractionError("Unsupported extraction MIME")
if not blocks or len(blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Empty extraction or block limit exceeded")
if any(unreadable(b.text) for b in blocks):
raise ExtractionError("Unreadable extracted evidence")
faq_groups = {b.group_id for b in blocks if b.block_type in ("question", "answer")}
if any(PLACEHOLDER.search(b.text) and not (self.factual_retention and b.group_id
and b.group_id in faq_groups) for b in blocks):
raise ExtractionError("Live-data placeholder cannot be authoritative evidence")
if self.construction is None:
self._budget(blocks)
blocks = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate(blocks))
envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"],
complete=True, quality_decision="reviewed" if self.reviewed else "passed",
review_annotations=tuple(self.annotations), blocks=blocks)
normalized_inputs(envelope, profile)
payload = serialize_artifact(envelope, profile)
return validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(),
document_id=document_id, original_sha256=original_hash,
processing_profile=profile)
def _text(self, text):
if any(faq_role(line) for line in text.splitlines()):
return self._text_faq(text)
# Preserve every character, including separators and leading/trailing spacing.
def pieces():
start = 0
for boundary in re.finditer(r"(?<=\n)(?=[ \t]*(?:\r\n|\r|\n))|(?<=\r)(?!\n)(?=[ \t]*(?:\r\n|\r|\n))", text):
yield text[start:boundary.start()]
start = boundary.start()
yield text[start:]
result, section, prefix = [], None, ""
for index, piece in enumerate(pieces()):
if not piece.strip() and result:
last = result[-1]
combined = last.text + piece
self.construction.remove(last)
result[-1] = last.model_copy(update={"text": combined,
"search_text": normalize_search_text(combined, self.profile["normalizer"])})
self.construction.add(result[-1])
continue
if not piece.strip():
prefix += piece
continue
piece, prefix = prefix + piece, ""
if RULE.match(piece):
section = piece.splitlines()[0]
counter = _TextCounter(self.construction)
counter.add(piece)
block = self._block(piece, f"text/paragraph/{index + 1}", "readable_text")
if section:
self.construction.remove(block)
block = block.model_copy(update={"section": section})
self.construction.add(block)
result.append(block)
return result
def _text_faq(self, text):
result, pending, role, group, answered = [], [], None, None, False
start_line, pair_level = 1, None
pending_counter = _TextCounter(self.construction)
def flush():
nonlocal pending, pending_counter
if pending:
result.append(self._block("".join(pending), f"text/line/{start_line}", "readable_text",
block_type=role or "paragraph", group_id=group))
pending = []
pending_counter = _TextCounter(self.construction)
for index, line in enumerate(text.splitlines(keepends=True), 1):
detected = faq_role(line)
match = HEADING.match(line)
level = len(match[1]) if match else None
heading = RULE.match(line) and detected is None
if detected or heading:
flush()
start_line = index
if detected == "question":
if group and not answered:
raise ExtractionError("FAQ question has no corresponding answer")
if group and pair_level is not None and level is not None and level > pair_level:
raise ExtractionError("Ambiguous nested FAQ question")
group, role, answered = f"text/line/{index}/qa", "question", False
pair_level = level
elif detected == "answer":
if group is None:
raise ExtractionError("FAQ answer has no corresponding question")
if level != pair_level:
raise ExtractionError("Ambiguous FAQ question/answer heading hierarchy")
role, answered = "answer", True
elif group and level is not None and pair_level is not None and level > pair_level:
# Source hierarchy explicitly keeps subsections under this answer.
# A subsection under an unanswered question is not an answer.
if not answered:
raise ExtractionError("Incomplete FAQ before answer subsection")
else:
if group and not answered:
raise ExtractionError("Incomplete FAQ before heading")
group, role, pair_level = None, None, None
pending_counter.add(line)
pending.append(line)
flush()
if group and not answered:
raise ExtractionError("FAQ question has no corresponding answer")
return result
def _docx(self, content):
document = validate_docx(content, SimpleNamespace(**self.profile["intake"]))
ns = document.tag.split("}")[0] + "}"
body = document.find(ns + "body")
# Fail unsupported visible sources instead of quietly losing them.
with ZipFile(BytesIO(content)) as package:
if any(re.match(r"word/(?:header|footer|footnotes|endnotes|comments|media/)", n)
for n in package.namelist()):
raise ExtractionError("DOCX auxiliary or visual content requires explicit extraction support")
revision_names = {"del", "ins", "pPrChange", "rPrChange", "sectPrChange",
"tblPrChange", "tblPrExChange", "tblGridChange", "trPrChange", "tcPrChange",
"cellIns", "cellDel", "cellMerge", "numberingChange"}
if any(e.tag.split("}")[-1] in revision_names | {"drawing", "pict", "object", "altChunk", "sdt", "customXml", "AlternateContent"}
or "moveFrom" in e.tag.split("}")[-1] or "moveTo" in e.tag.split("}")[-1]
or "MoveFrom" in e.tag.split("}")[-1] or "MoveTo" in e.tag.split("}")[-1]
or e.tag.split("}")[-1].startswith(("customXmlIns", "customXmlDel"))
for e in body.iter()):
raise ExtractionError("Unsupported DOCX visual or revision content")
# Validate structural children before direct findall can omit wrappers.
structural = {"tbl": {"tblPr", "tblGrid", "tr", "bookmarkStart", "bookmarkEnd"},
"tr": {"trPr", "tc", "bookmarkStart", "bookmarkEnd"},
"tc": {"tcPr", "p"}}
for element in body.iter():
allowed = structural.get(element.tag.split("}")[-1])
if allowed and any(child.tag not in {ns + name for name in allowed} for child in element):
raise ExtractionError("Unsupported DOCX table structure")
self._reject_docx_numbering(content, body, ns)
self._reject_docx_semantic_formatting(content, body, ns)
result, current, role, answered = [], None, None, False
pair_level = None
heading_stack = []
table_index, paragraph_index = 0, 0
from defusedxml.ElementTree import fromstring
styles = {}
with ZipFile(BytesIO(content)) as package:
if "word/styles.xml" in package.namelist():
root = fromstring(package.read("word/styles.xml"), forbid_dtd=True,
forbid_entities=True, forbid_external=True)
styles = {e.get(ns + "styleId"): e for e in root.findall(ns + "style")}
def heading_level(paragraph):
props = paragraph.find(ns + "pPr")
ref = props.find(ns + "pStyle") if props is not None else None
identity = ref.get(ns + "val") if ref is not None else next((key for key, style in styles.items()
if style.get(ns + "type") == "paragraph" and style.get(ns + "default") in ("1", "true", "on")), None)
seen = set()
while True:
outline = props.find(ns + "outlineLvl") if props is not None else None
if outline is not None:
value = outline.get(ns + "val", "")
if not value.isdecimal() or not 0 <= int(value) <= 9:
raise ExtractionError("Unsupported DOCX heading hierarchy")
return int(value) + 1 if int(value) < 9 else None
if identity is None:
return None
if identity in seen or identity not in styles:
raise ExtractionError("Unresolved DOCX heading hierarchy")
seen.add(identity)
style = styles[identity]
props = style.find(ns + "pPr")
base = style.find(ns + "basedOn")
identity = base.get(ns + "val") if base is not None else None
def append(text, locator, heading=None, force_role=None, table=False):
nonlocal current, role, answered, pair_level
if not text.strip():
return
detected = force_role or faq_role(text) or (faq_role("# " + text) if heading is not None else None)
if detected == "question":
if current and not answered:
raise ExtractionError("FAQ question has no corresponding answer")
if current and pair_level is not None and heading is not None and heading > pair_level:
raise ExtractionError("Ambiguous nested FAQ question")
heading_stack.clear()
current, role, answered = locator + "/qa", "question", False
pair_level = heading
elif detected == "answer":
if not current:
raise ExtractionError("FAQ answer has no corresponding question")
if answered:
raise ExtractionError("Ambiguous duplicate FAQ answer")
if heading != pair_level:
raise ExtractionError("Ambiguous FAQ question/answer heading hierarchy")
role, answered = "answer", True
elif heading is not None:
if current and not answered:
raise ExtractionError("Incomplete FAQ before heading")
if pair_level is None or heading <= pair_level:
current, role, pair_level = None, None, None
heading_stack.clear()
block_type = role if current else ("heading" if heading else "table" if table else "paragraph")
if heading is not None:
while heading_stack and heading_stack[-1][0] >= heading:
heading_stack.pop()
parent = heading_stack[-1][1] if current and heading_stack else None
result.append(self._block(text, locator, "docx", block_type=block_type,
group_id=current, parent_block_id=parent,
heading=text.rstrip("\n") if heading else None))
if current and heading is not None:
heading_stack.append((heading, locator))
def paragraph_text(element):
# Only supported WordprocessingML containers may carry source runs.
# In particular m:t is mathematical structure, not ordinary w:t.
containers = {
"p": {"pPr", "r", "hyperlink", "bookmarkStart", "bookmarkEnd", "proofErr", "permStart", "permEnd"},
"hyperlink": {"r", "bookmarkStart", "bookmarkEnd", "proofErr", "permStart", "permEnd"},
}
for node in element.iter():
if not node.tag.startswith(ns):
raise ExtractionError("Unsupported DOCX equation or paragraph namespace")
local = node.tag[len(ns):]
if local in containers and any(child.tag not in {ns + name for name in containers[local]} for child in node):
raise ExtractionError("Unsupported DOCX paragraph structure")
if local in {"pPr", "rPr", "bookmarkStart", "bookmarkEnd", "proofErr", "permStart", "permEnd"}:
if any(desc.tag in {ns + name for name in ("t", "r", "tab", "br", "cr")}
for desc in node.iter() if desc is not node):
raise ExtractionError("Unsupported DOCX text inside paragraph metadata")
allowed = {"rPr", "t", "tab", "br", "cr", "noBreakHyphen", "softHyphen", "lastRenderedPageBreak"}
for run in element.iter(ns + "r"):
if any(child.tag not in {ns + name for name in allowed} for child in run):
raise ExtractionError("Unsupported DOCX text-bearing run element")
parts = []
counter = _TextCounter(self.construction)
for e in element.iter():
local = e.tag.split("}")[-1]
if local == "t":
parts.append(e.text or "")
elif local == "tab":
parts.append("\t")
elif local == "noBreakHyphen":
parts.append("\u2011")
elif local == "softHyphen":
parts.append("\u00ad")
elif local in ("br", "cr"):
parts.append("\n")
if local in ("t", "tab", "noBreakHyphen", "softHyphen", "br", "cr"):
counter.add(parts[-1])
if local in ("sym", "fldChar", "instrText", "txbxContent"):
raise ExtractionError("Unsupported DOCX text representation")
counter.add("\n")
return "".join(parts) + "\n"
for item in body:
if item.tag == ns + "p":
paragraph_index += 1
style = item.find(".//" + ns + "pStyle")
heading = heading_level(item)
append(paragraph_text(item), f"docx/paragraph/{paragraph_index}", heading)
elif item.tag == ns + "tbl":
table_index += 1
# Adjacent tables can split a labelled Q/A pair (supplied sample).
header_columns = None
for row_index, row in enumerate(item.findall(ns + "tr"), 1):
cells = row.findall(ns + "tc")
texts, cell_paragraphs = [], []
planned_blocks = 0
for cell in cells:
if cell.find(".//" + ns + "tbl") is not None:
raise ExtractionError("Nested DOCX tables require explicit support")
paragraphs = []
if cell is cells[0]:
row_counter = _TextCounter(self.construction)
labelled = 0
for paragraph in cell.findall(ns + "p"):
value = paragraph_text(paragraph)
row_counter.add(value)
if QUESTION.match(value) or ANSWER.match(value):
labelled += 1
# A later label forces per-paragraph output for this cell.
# Stop before constructing the remainder of an oversized row.
proposed = len(paragraphs) + 1 if labelled > 1 else 1
self.construction.check(planned_blocks + proposed, 0, 0)
paragraphs.append(value)
planned_blocks += len(paragraphs) if labelled > 1 else 1
cell_paragraphs.append(paragraphs)
texts.append("".join(paragraphs))
labels = [t.strip().rstrip("::").lower() for t in texts]
if labels in (["سؤال", "پاسخ"], ["سوال", "پاسخ"], ["question", "answer"]):
header_columns = True
for col, value in enumerate(texts, 1):
result.append(self._block(value, f"docx/table/{table_index}/row/{row_index}/cell/{col}",
"docx", block_type="table"))
continue
for col, value in enumerate(texts, 1):
forced = ("question" if col == 1 else "answer") if header_columns and len(texts) == 2 else None
# Explicitly labelled Q/A work in both adjacent rows and cells.
locator = f"docx/table/{table_index}/row/{row_index}/cell/{col}"
paragraphs = cell_paragraphs[col - 1]
if any(QUESTION.match(p) or ANSWER.match(p) for p in paragraphs[1:]) or any(heading_level(p) is not None for p in cells[col - 1].findall(ns + "p")):
for index, paragraph in enumerate(paragraphs, 1):
append(paragraph, locator + f"/paragraph/{index}", heading=heading_level(cells[col - 1].findall(ns + "p")[index - 1]), force_role=forced if index == 1 else None, table=True)
else:
append(value, locator, force_role=forced, table=True)
elif item.tag != ns + "sectPr":
raise ExtractionError("Unsupported DOCX body content")
if current and not answered:
raise ExtractionError("FAQ question has no corresponding answer")
return result
def _reject_docx_semantic_formatting(self, content, body, ns):
"""Reject effective formatting that plain text cannot faithfully retain.
Visibility/strike/case toggles and absolute vertical positioning are
resolved through used styles/defaults. Direct properties set absolute values, including explicit resets.
Harmless formatting is outside this conservative semantic-format check.
"""
from defusedxml.ElementTree import fromstring
styles, defaults, default_styles = {}, None, {}
with ZipFile(BytesIO(content)) as package:
if "word/styles.xml" in package.namelist():
root = fromstring(package.read("word/styles.xml"), forbid_dtd=True,
forbid_entities=True, forbid_external=True)
defaults = root.find(ns + "docDefaults/" + ns + "rPrDefault/" + ns + "rPr")
for style in root.findall(ns + "style"):
key, kind = style.get(ns + "styleId"), style.get(ns + "type")
if key in styles:
raise ExtractionError("Ambiguous DOCX visibility style")
styles[key] = style
if style.get(ns + "default") in ("1", "true", "on"):
if kind in default_styles:
raise ExtractionError("Ambiguous DOCX default visibility style")
default_styles[kind] = key
semantic_names = ("vanish", "strike", "dstrike", "vertAlign", "position",
"caps", "smallCaps", "webHidden", "specVanish")
def formatting(properties):
values = {}
if properties is None:
return values
for name in semantic_names:
elements = properties.findall(ns + name)
if len(elements) > 1:
raise ExtractionError("Ambiguous DOCX semantic formatting")
if not elements:
continue
value = elements[0].get(ns + "val", "true")
if name == "position":
if not re.fullmatch(r"[+-]?\d+", value):
raise ExtractionError("Unsupported DOCX semantic position")
values[name] = int(value) != 0
elif name == "vertAlign":
if value not in ("baseline", "superscript", "subscript"):
raise ExtractionError("Unsupported DOCX vertical alignment")
values[name] = value != "baseline"
else:
if value not in ("0", "false", "off", "1", "true", "on"):
raise ExtractionError("Unsupported DOCX semantic formatting")
values[name] = value in ("1", "true", "on")
return values
def applied(inherited, properties, *, style=False):
result = dict(inherited)
for name, value in formatting(properties).items():
if style and name in ("vanish", "strike", "caps", "smallCaps"):
if value:
result[name] = not result.get(name, False)
else:
result[name] = value
return result
def chain(style_id, kind):
result, seen = [], set()
while style_id is not None:
if style_id in seen or style_id not in styles:
raise ExtractionError("Unresolved DOCX visibility style")
seen.add(style_id)
style = styles[style_id]
if style.get(ns + "type") != kind:
raise ExtractionError("Incompatible DOCX visibility style")
result.append(style)
base = style.find(ns + "basedOn")
style_id = base.get(ns + "val") if base is not None else None
return reversed(result)
def reference(properties, name, kind):
ref = properties.find(ns + name) if properties is not None else None
return ref.get(ns + "val") if ref is not None else default_styles.get(kind)
def styled(value, style_id, kind):
for style in chain(style_id, kind):
properties = style.find(ns + "rPr")
value = applied(value, properties, style=True)
# Used styles may also carry conditional/paragraph-mark hiding.
supported = set(properties) if properties is not None else set()
for parent in style.iter():
if any(child not in supported and child.tag in {ns + n for n in semantic_names}
for child in parent) and any(formatting(parent).values()):
raise ExtractionError("Unsupported DOCX contextual semantic formatting")
return value
# Table/conditional style visibility cannot be inferred from plain cell text.
for table in body.iter(ns + "tbl"):
properties = table.find(ns + "tblPr")
style_id = reference(properties, "tblStyle", "table")
for style in chain(style_id, "table"):
if any(any(formatting(parent).values()) for parent in style.iter()):
raise ExtractionError("Unsupported DOCX table semantic formatting")
default_formatting = applied({}, defaults)
for paragraph in body.iter(ns + "p"):
properties = paragraph.find(ns + "pPr")
paragraph_formatting = styled(default_formatting, reference(properties, "pStyle", "paragraph"), "paragraph")
mark = properties.find(ns + "rPr") if properties is not None else None
if any(formatting(mark).values()):
raise ExtractionError("Unsupported DOCX paragraph-mark semantic formatting")
for run in paragraph.iter(ns + "r"):
properties = run.find(ns + "rPr")
effective = styled(paragraph_formatting, reference(properties, "rStyle", "character"), "character")
effective = applied(effective, properties)
if any(effective.values()):
raise ExtractionError("Unsupported DOCX semantic formatting requires faithful extraction/QC")
def _reject_docx_numbering(self, content, body, ns):
"""Reject effective automatic numbering; never fabricate displayed identifiers."""
from defusedxml.ElementTree import fromstring
styles, default, defaults = {}, None, None
with ZipFile(BytesIO(content)) as package:
if "word/styles.xml" in package.namelist():
root = fromstring(package.read("word/styles.xml"), forbid_dtd=True,
forbid_entities=True, forbid_external=True)
defaults = root.find(ns + "docDefaults/" + ns + "pPrDefault/" + ns + "pPr")
for style in root.findall(ns + "style"):
if style.get(ns + "type") == "paragraph":
key = style.get(ns + "styleId")
if key in styles:
raise ExtractionError("Ambiguous DOCX paragraph style")
styles[key] = style
if style.get(ns + "default") in ("1", "true", "on"):
if default is not None:
raise ExtractionError("Ambiguous DOCX default paragraph style")
default = key
def numbering(properties):
if properties is None:
return None
num = properties.find(ns + "numPr")
if num is None:
return None
identity = num.find(ns + "numId")
return identity is None or identity.get(ns + "val") != "0"
for paragraph in body.iter(ns + "p"):
properties = paragraph.find(ns + "pPr")
numbered = numbering(properties)
style_ref = properties.find(ns + "pStyle") if properties is not None else None
style_id = style_ref.get(ns + "val") if style_ref is not None else default
seen = set()
while numbered is None and style_id is not None:
if style_id in seen or style_id not in styles:
raise ExtractionError("Unresolved DOCX paragraph style")
seen.add(style_id)
style = styles[style_id]
numbered = numbering(style.find(ns + "pPr"))
base = style.find(ns + "basedOn")
style_id = base.get(ns + "val") if base is not None else None
if numbered is None:
numbered = numbering(defaults)
if numbered:
raise ExtractionError("Automatic DOCX numbering requires explicit extraction support")
def _render(self, page):
dpi = self.profile["extraction"]["render_dpi"]
width, height = math.ceil(page.rect.width * dpi / 72), math.ceil(page.rect.height * dpi / 72)
if width * height > self.profile["extraction"]["max_rendered_page_pixels"]:
raise ExtractionError("Rendered page pixel limit exceeded")
return page.get_pixmap(dpi=dpi, alpha=False).tobytes("png")
def _pdf(self, content):
import pymupdf
try:
document = pymupdf.open(stream=content, filetype="pdf")
except Exception:
raise ExtractionError("Cannot parse PDF original") from None
with document:
if document.needs_pass or not 0 < document.page_count <= min(
self.profile["extraction"]["max_pdf_pages"], self.profile["limits"]["max_pdf_pages"]):
raise ExtractionError("Encrypted, empty or oversized PDF")
result = []
for page in document:
self.owned()
number, locator = page.number + 1, f"pdf/page/{page.number + 1}"
resumed = self._resume(locator)
if resumed is not None:
result.extend(resumed)
self._budget(result)
continue
raw = page.get_text("blocks", sort=False)
text_blocks = [b for b in raw if b[6] == 0 and b[4].strip()]
direct_text = "".join(b[4] for b in text_blocks)
# A text layer with images, invisible text or missing glyphs cannot establish coverage.
invisible = any(t.get("type") == 3 for t in page.get_texttrace())
fallback = (unreadable(direct_text) or bool(page.get_images(full=True))
or invisible or bool(page.get_drawings()))
if fallback:
image = self._render(page)
result.extend(self._vision(image, number, locator,
("Direct PDF coverage/readability uncertain; affected-page fallback",)))
self._budget(result)
continue
blocks = [self._block(b[4], locator + f"/block/{i + 1}", "direct_pdf", page=number)
for i, b in enumerate(text_blocks)]
self._budget(result + blocks)
# Visual confirmation establishes completeness/order; never reverse Persian digits.
image = self._render(page)
try:
blocks = self._review(blocks, image, locator,
("PDF page checked against rendering: order, coverage and critical fields",))
except RejectedReview:
blocks = self._vision(image, number, locator, ("Manual review rejected direct extraction",))
result.extend(blocks)
self._budget(result)
return result
def _budget(self, blocks):
if len(blocks) > self.profile["extraction"]["max_extracted_blocks"]:
raise ExtractionError("Extracted block limit exceeded")
if sum(len(normalize_search_text(b.text, self.profile["normalizer"])) for b in blocks
) > self.profile["limits"]["max_normalized_characters"]:
raise ExtractionError("Normalized input exceeds character budget")
data = {"artifact_schema": 1, "document_id": str(self.document_id), "title": self.title,
"original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest,
"normalization_policy": self.profile["normalizer"], "complete": True,
"quality_decision": "reviewed" if self.reviewed else "passed", "warnings": [],
"review_annotations": [a.model_dump(mode="json") for a in self.annotations],
"blocks": [dict(b.model_dump(mode="json"), ordinal=i) for i, b in enumerate(blocks)]}
bounded_json_size(data, self.profile["extraction"]["max_extraction_artifact_bytes"])
def _vision(self, image, page, locator, reasons=()):
resumed = self._resume(locator)
if resumed is not None:
return resumed
self.owned()
identity = self.profile["extraction"]["vision"]
if self.vision is None or not all(isinstance(identity.get(k), str) and identity[k].strip()
for k in ("provider", "endpoint", "model")):
raise ExtractionError("Affected page requires configured vision identity and adapter")
if len(image) > self.profile["limits"]["max_original_bytes"]:
raise ExtractionError("Vision image byte limit exceeded")
response = self.vision.transcribe(image, page=page, section=locator, processing_profile=self.profile)
self.owned()
if len(response) > self.profile["extraction"]["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = list(response)
self._budget(blocks)
if not blocks:
raise ExtractionError("Vision returned no complete transcription")
for index, b in enumerate(blocks):
if (b.ordinal != index or b.method not in ("vision", "ocr") or b.actual_model != identity["model"]
or b.page != page or not b.source_locator.startswith(locator + "/")
or unreadable(b.text)):
raise ExtractionError("Vision evidence identity, location or readability mismatch")
if any("unreadable" in w.lower() or "ناخوانا" in w for w in b.warnings):
raise ExtractionError("Vision reports unreadable source regions")
# Validate local source relationships before manually attesting to the result.
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
complete=True, quality_decision="passed",
blocks=tuple(blocks))
return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))