Freeze temporary partial-extraction admission in new uploads. Bypass manual approval, retain recognition warnings, and accept ambiguous legal references during bounded chunking. Preserve strict defaults, immutable evidence and atomic publication. Expose effective policy and safe failure categories with regression coverage.
403 lines
20 KiB
Python
403 lines
20 KiB
Python
"""Deterministic faithful chunk drafts; atomic semantic groups never lose exceptions."""
|
||
import hashlib
|
||
import re
|
||
import unicodedata
|
||
|
||
from .extraction import ExtractionError, RULE, PLACEHOLDER, HEADING
|
||
from .extraction_artifacts import validate_artifact, serialize_artifact, allow_partial_extraction
|
||
from .normalization import normalize_search_text
|
||
from .types import ChunkDraft
|
||
|
||
|
||
DEPENDENT_HEADING = re.compile(
|
||
r"^\s*(?:#{1,6}\s*)?(?:Notes?|Exceptions?|Conditions?|Exclusions?|"
|
||
r"(?:تبصره|یادداشت)(?:(?:| )?ها(?:ی)?)?|استثنا(?:?ها|ئات|ء)?|شرایط|شروط|ملاحظات)"
|
||
r"(?=\s|[::]|$)", re.I)
|
||
RULE_LABELS = r"Articles?|Clauses?|Circulars?|Decisions?|مواد|ماده|بند|بخشنامه|تصمیم"
|
||
# A date qualifier introduces metadata, not an identifier (e.g. Decision dated).
|
||
NOT_DATE_QUALIFIER = r"(?![ \t]+(?:dated|مورخ)(?=[ \t]|$))"
|
||
GOVERNING_RULE = re.compile(
|
||
r"^\s*(?:#{1,6}\s*)?(?:" + RULE_LABELS + r")" + NOT_DATE_QUALIFIER + r"(?=[ \t]|\d|$)", re.I)
|
||
|
||
|
||
DEPENDENT_PROSE = re.compile(
|
||
r"^\s*(?:Except|Unless|Provided(?:\s+that)?|Only\s+(?:if|when)|به\s+شرط|مشروط|مگر)"
|
||
r"(?=\s|[::]|$)", re.I)
|
||
|
||
|
||
def dependent_content(text):
|
||
return bool(DEPENDENT_HEADING.match(text) or DEPENDENT_PROSE.match(text))
|
||
|
||
|
||
REFERENCE = re.compile(r"(?<!\w)(?P<label>" + RULE_LABELS + r")" + NOT_DATE_QUALIFIER + r"(?=[ \t]|\d|$)[ \t]*", re.I)
|
||
IDENTIFIER = re.compile(r"\d+(?:[./]\d+)*(?:\((?:\d+|[^\W\d_]+)\))*")
|
||
REFERENCE_KINDS = {"article": 0, "ماده": 0, "clause": 1, "بند": 1,
|
||
"circular": 2, "بخشنامه": 2, "decision": 3, "تصمیم": 3,
|
||
"articles": 0, "مواد": 0, "clauses": 1, "circulars": 2, "decisions": 3}
|
||
INCIDENTAL_CITATION = re.compile(
|
||
r"^\s*(?:See\b|Refer\s+to\b|According\s+to\b|For\s+background\b|"
|
||
r"مطابق\s|طبق\s|رجوع\s|مراجعه\s|ارجاع\s)", re.I)
|
||
# A citation sentence is incidental only when it does not also state applicability.
|
||
APPLICABILITY = re.compile(
|
||
r"\b(?:appl(?:y|ies|icable)|governs?|only|except|unless)\b|"
|
||
r"فقط|صرفاً|تنها|اعمال|شامل|مربوط", re.I)
|
||
|
||
|
||
def reference_identity(match, text):
|
||
# Read the entire token, then validate it: a valid numeric prefix is not an ID.
|
||
token = re.match(r"[^\s::,،;؛!?؟]+", text[match.end():])
|
||
identifier = token[0] if token else ""
|
||
if token and re.match(r"[ \t]+(?:\.|/|\(|\[|-|–|—|ـ)", text[match.end() + token.end():]):
|
||
raise ExtractionError("Unsupported spaced governing-rule identifier")
|
||
if identifier.endswith("."):
|
||
identifier = identifier[:-1] # One sentence-final stop, not an internal dot.
|
||
if not IDENTIFIER.fullmatch(identifier):
|
||
raise ExtractionError("Unsupported governing-rule identifier")
|
||
# Digit-script equivalence is local to association; faithful/search text is untouched.
|
||
identifier = "".join(str(unicodedata.decimal(c)) if c.isdecimal() else c for c in identifier)
|
||
return REFERENCE_KINDS[match["label"].lower()], identifier
|
||
|
||
|
||
CONNECTOR = re.compile(r"[ \t]*(?:(?P<list>,|،|and\b|or\b|&|و(?=\s)|یا(?=\s))|(?P<range>through\b|to\b|تا(?=\s)|الی(?=\s)))[ \t]*", re.I)
|
||
ORDINARY_DECISION = re.compile(r"(?:is|was|will|shall|has|remains|must)\b|نهایی|قطعی|است", re.I)
|
||
|
||
|
||
def rule_references(text):
|
||
references = set()
|
||
for match in REFERENCE.finditer(text):
|
||
rest = text[match.end():]
|
||
if match["label"].lower() == "decision" and ORDINARY_DECISION.match(rest):
|
||
continue
|
||
first = reference_identity(match, text)
|
||
references.add(first)
|
||
token = re.match(r"[^\s::,،;؛!?؟]+", rest)
|
||
offset = match.end() + token.end()
|
||
previous = first
|
||
while connector := CONNECTOR.match(text, offset):
|
||
offset = connector.end()
|
||
labelled = REFERENCE.match(text, offset)
|
||
if labelled:
|
||
current = reference_identity(labelled, text)
|
||
token_start = labelled.end()
|
||
else:
|
||
synthetic = REFERENCE.match(match["label"] + " ")
|
||
current = reference_identity(synthetic, match["label"] + " " + text[offset:])
|
||
token_start = offset
|
||
token = re.match(r"[^\s::,،;؛!?؟]+", text[token_start:])
|
||
offset = token_start + token.end()
|
||
if connector["range"]:
|
||
if current[0] != previous[0] or not previous[1].isdigit() or not current[1].isdigit():
|
||
raise ExtractionError("Unsupported governing-rule identifier range")
|
||
if int(current[1]) < int(previous[1]):
|
||
raise ExtractionError("Unsupported governing-rule identifier range")
|
||
references.add(current)
|
||
previous = current
|
||
return references
|
||
|
||
|
||
def governing_lines(blocks):
|
||
lines = [line for b in blocks for line in b.text.splitlines()
|
||
if GOVERNING_RULE.match(line) and rule_references(line)]
|
||
for line in lines:
|
||
rule_references(line) # Reject unsupported forms even without a dependent unit.
|
||
return lines
|
||
|
||
|
||
def validate_reference_line(line, governing):
|
||
expected = {reference_identity(REFERENCE.search(governing), governing)}
|
||
rule_references(line) # Validate complete tokens before sentence segmentation.
|
||
for sentence in re.split(r"\.(?=\s|$)|[;؛]", line):
|
||
references = rule_references(sentence)
|
||
if not references:
|
||
continue
|
||
if INCIDENTAL_CITATION.match(sentence) and not APPLICABILITY.search(sentence):
|
||
continue
|
||
if references != expected:
|
||
raise ExtractionError("Ambiguous explicit governing rule reference")
|
||
|
||
|
||
def validate_dependency_references(blocks, governing):
|
||
"""Inspect every dependent line, including dependencies inside a source group."""
|
||
in_dependency = False
|
||
for block in blocks:
|
||
for line in block.text.splitlines():
|
||
if GOVERNING_RULE.match(line):
|
||
in_dependency = False
|
||
elif dependent_content(line):
|
||
in_dependency = True
|
||
if in_dependency:
|
||
validate_reference_line(line, governing)
|
||
|
||
|
||
def validate_faq_rule_scopes(blocks):
|
||
"""Heading ancestry bounds FAQ dependencies regardless of rule count."""
|
||
stack = []
|
||
governing, dependent = None, False
|
||
for block in blocks:
|
||
for line in block.text.splitlines():
|
||
heading = HEADING.match(line)
|
||
rule = GOVERNING_RULE.match(line)
|
||
if heading:
|
||
level = len(heading[1])
|
||
while stack and stack[-1][0] >= level:
|
||
stack.pop()
|
||
governing, dependent = stack[-1][1:] if stack else (None, False)
|
||
if rule:
|
||
if dependent:
|
||
raise ExtractionError("Ambiguous rule inside FAQ dependency")
|
||
governing, dependent = line, False
|
||
else:
|
||
dependent = dependent or dependent_content(line)
|
||
stack.append((level, governing, dependent))
|
||
elif rule:
|
||
raise ExtractionError("Multiple FAQ rules require explicit heading hierarchy")
|
||
elif dependent_content(line):
|
||
dependent = True
|
||
if stack:
|
||
stack[-1] = (stack[-1][0], governing, dependent)
|
||
if dependent:
|
||
if governing is None:
|
||
raise ExtractionError("Ambiguous governing rule in FAQ hierarchy")
|
||
validate_reference_line(line, governing)
|
||
|
||
|
||
def validate_visual_rule_scopes(blocks, *, faq=False):
|
||
"""Resolve a dependency through its explicit ancestor, never a sibling."""
|
||
contexts = {}
|
||
for index, block in enumerate(blocks):
|
||
parent = block.parent_block_id
|
||
if index and parent not in contexts and not (faq and parent is None):
|
||
raise ExtractionError("Visual dependencies require explicit parent links")
|
||
governing, dependent = contexts[parent] if parent is not None else (None, False)
|
||
own_rules = governing_lines([block])
|
||
if len(own_rules) > 1 or (dependent and own_rules):
|
||
raise ExtractionError("Ambiguous rule inside visual dependency")
|
||
if own_rules:
|
||
governing, dependent = own_rules[0], False
|
||
for line in block.text.splitlines():
|
||
if dependent_content(line):
|
||
dependent = True
|
||
if dependent:
|
||
if governing is None:
|
||
raise ExtractionError("Ambiguous governing rule in visual hierarchy")
|
||
validate_reference_line(line, governing)
|
||
contexts[block.block_id] = (governing, dependent)
|
||
|
||
|
||
def associate_dependencies(units):
|
||
"""Only an explicit adjacent governing rule can receive a separate note unit."""
|
||
associated = []
|
||
for group, blocks, atomic in units:
|
||
faq = any(b.block_type == "question" for b in blocks) and any(b.block_type == "answer" for b in blocks)
|
||
dependent = dependent_content(blocks[0].text) and not faq
|
||
own_rules = governing_lines(blocks)
|
||
if dependent and own_rules:
|
||
raise ExtractionError("Ambiguous governing rule inside dependent source group")
|
||
if any(dependent_content(line) for b in blocks for line in b.text.splitlines()):
|
||
if own_rules:
|
||
if faq and any(b.parent_block_id is not None for b in blocks):
|
||
validate_visual_rule_scopes(blocks, faq=True)
|
||
elif faq and (len(own_rules) > 1 or any(HEADING.match(line) for line in own_rules)):
|
||
validate_faq_rule_scopes(blocks)
|
||
elif blocks[0].block_type == "visual_group":
|
||
validate_visual_rule_scopes(blocks)
|
||
elif len(own_rules) == 1:
|
||
validate_dependency_references(blocks, own_rules[0])
|
||
else:
|
||
raise ExtractionError("Ambiguous governing rule inside dependent source group")
|
||
elif not dependent and not faq and not (blocks[0].block_type == "visual_group"
|
||
and all(b.parent_block_id == blocks[0].block_id for b in blocks[1:])):
|
||
raise ExtractionError("Ambiguous governing rule for dependent source content")
|
||
if dependent:
|
||
if not associated:
|
||
raise ExtractionError("Ambiguous governing rule for dependent source content")
|
||
previous = associated[-1]
|
||
rule_lines = governing_lines(previous[1])
|
||
if len(rule_lines) != 1:
|
||
raise ExtractionError("Ambiguous governing rule for dependent source content")
|
||
validate_dependency_references(blocks, rule_lines[0])
|
||
previous[1].extend(blocks)
|
||
previous[2] = True
|
||
else:
|
||
if associated and not semantic_boundary(blocks[0]):
|
||
previous_rules = [line for b in associated[-1][1] for line in b.text.splitlines()
|
||
if GOVERNING_RULE.match(line)]
|
||
own_rules = [line for b in blocks for line in b.text.splitlines()
|
||
if GOVERNING_RULE.match(line)]
|
||
own_heading = (blocks[0].block_type in ("heading", "visual_group")
|
||
and bool(blocks[0].heading))
|
||
if previous_rules and not own_rules and not own_heading:
|
||
raise ExtractionError("Ambiguous unlabelled rule continuation across source groups")
|
||
associated.append([group, list(blocks), atomic])
|
||
return associated
|
||
|
||
|
||
def semantic_boundary(block):
|
||
return (bool(RULE.match(block.text) or GOVERNING_RULE.match(block.text)) or block.block_type == "heading") and not DEPENDENT_HEADING.match(block.text)
|
||
|
||
|
||
def factual_context_units(blocks):
|
||
"""Resolve full FAQ source structure before inclusion; never infer prose scope."""
|
||
source_units, seen = [], set()
|
||
for block in blocks:
|
||
if block.group_id is not None:
|
||
if source_units and source_units[-1][0] == block.group_id:
|
||
source_units[-1][1].append(block)
|
||
else:
|
||
if block.group_id in seen:
|
||
raise ExtractionError("Noncontiguous source group")
|
||
seen.add(block.group_id)
|
||
source_units.append([block.group_id, [block], True])
|
||
else:
|
||
source_units.append([None, [block], False])
|
||
scopes, resolved, preamble = [], [], []
|
||
|
||
def close_scope():
|
||
scope = scopes.pop()
|
||
if not scope["used"]:
|
||
raise ExtractionError("Governing FAQ context has no associated pairs")
|
||
|
||
for group, unit, _ in source_units:
|
||
if group is not None:
|
||
if not any(b.block_type == "question" for b in unit):
|
||
raise ExtractionError("Unresolved non-FAQ source group")
|
||
# Validate every group, including excluded groups, before selection.
|
||
associate_dependencies([(group, unit, True)])
|
||
context = preamble + [b for scope in scopes for b in scope["blocks"]]
|
||
for scope in scopes:
|
||
scope["used"] = True
|
||
resolved.append([group, context + unit, True])
|
||
continue
|
||
block = unit[0]
|
||
lines = [line for line in block.text.splitlines() if line.strip()]
|
||
heading = HEADING.match(lines[0]) if lines else None
|
||
if heading:
|
||
if sum(bool(HEADING.match(line)) for line in lines) != 1:
|
||
raise ExtractionError("Ambiguous FAQ context heading structure")
|
||
level = len(heading[1])
|
||
while scopes and scopes[-1]["level"] >= level:
|
||
close_scope()
|
||
scopes.append(dict(level=level, blocks=[block], used=False))
|
||
elif not scopes and not resolved and block.parent_block_id is None:
|
||
# Initial source prose is document-wide context, never pair-local.
|
||
preamble.append(block)
|
||
elif scopes and not scopes[-1]["used"] and block.parent_block_id is None:
|
||
scopes[-1]["blocks"].append(block)
|
||
else:
|
||
# Prose after pairs still has no reliable association.
|
||
raise ExtractionError("Ambiguous governing context for factual FAQ")
|
||
while scopes:
|
||
close_scope()
|
||
# Run the established dependency checks with each pair's complete context.
|
||
return associate_dependencies(resolved)
|
||
|
||
|
||
def factual_review_blocks(envelope):
|
||
"""Expose each retained context block once, in its real source order."""
|
||
units = factual_context_units(envelope.blocks)
|
||
identities = {b.block_id for _, blocks, _ in units for b in blocks}
|
||
return tuple(b for b in envelope.blocks if b.block_id in identities)
|
||
|
||
|
||
def chunk_extraction(envelope, processing_profile, *, corpus_purpose="source_document", included_group_ids=None):
|
||
# Treat even an in-memory envelope as untrusted consumption input.
|
||
payload = serialize_artifact(envelope, processing_profile)
|
||
envelope = validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(),
|
||
document_id=envelope.document_id, original_sha256=envelope.original_sha256,
|
||
processing_profile=processing_profile)
|
||
if corpus_purpose not in ("source_document", "approved_factual"):
|
||
raise ExtractionError("Behavioral evaluation and live-data placeholders are not knowledge")
|
||
if any(b.block_type in ("question", "answer") for b in envelope.blocks) and corpus_purpose != "approved_factual":
|
||
raise ExtractionError("FAQ requires separately approved factual corpus")
|
||
profile = processing_profile
|
||
if profile["chunker"] not in ("paragraph-v1", "semantic-boundaries-v1") or profile["size_unit"] != "characters":
|
||
raise ExtractionError("Unsupported frozen chunk policy or size unit")
|
||
size, overlap = profile["chunk_size"], profile["overlap"]
|
||
if size <= 0 or not 0 <= overlap < size:
|
||
raise ExtractionError("Invalid frozen chunk bounds")
|
||
# Source groups must be contiguous; regrouping distant blocks would reorder evidence.
|
||
blocks_to_chunk = envelope.blocks
|
||
if included_group_ids is not None:
|
||
groups = {b.group_id for b in envelope.blocks if b.block_type in ("question", "answer")}
|
||
if (corpus_purpose != "approved_factual" or not included_group_ids
|
||
or not set(included_group_ids) <= groups):
|
||
raise ExtractionError("Invalid whole-group factual inclusion")
|
||
context_units = factual_context_units(envelope.blocks)
|
||
blocks_to_chunk = ()
|
||
units, seen_groups = [], set()
|
||
for block in blocks_to_chunk:
|
||
if PLACEHOLDER.search(block.text):
|
||
raise ExtractionError("Placeholder is not authoritative knowledge")
|
||
if block.group_id:
|
||
if units and units[-1][0] == block.group_id:
|
||
units[-1][1].append(block)
|
||
else:
|
||
if block.group_id in seen_groups:
|
||
raise ExtractionError("Noncontiguous source group")
|
||
units.append([block.group_id, [block], True])
|
||
seen_groups.add(block.group_id)
|
||
elif units and units[-1][0] is None and not semantic_boundary(block) and not dependent_content(block.text):
|
||
# A circular decision, conditions and exclusions remain together until an
|
||
# explicit article/clause/heading boundary. PDF page breaks do not split rules.
|
||
units[-1][1].append(block)
|
||
else:
|
||
units.append([None, [block], False])
|
||
if included_group_ids is not None:
|
||
units = [unit for unit in context_units if unit[0] in included_group_ids]
|
||
for _, blocks, _ in units:
|
||
if any(PLACEHOLDER.search(b.text) for b in blocks):
|
||
raise ExtractionError("Placeholder is not authoritative knowledge")
|
||
chunks = []
|
||
# Temporary admission keeps source order without rejecting ambiguous legal references.
|
||
associated = units if allow_partial_extraction(profile) else associate_dependencies(units)
|
||
for group, blocks, atomic in associated:
|
||
parts = []
|
||
for index, block in enumerate(blocks):
|
||
if (index and not blocks[index - 1].text.endswith(("\n", "\r"))
|
||
and not block.text.startswith(("\n", "\r"))):
|
||
parts.append("\n")
|
||
parts.append(block.text)
|
||
text = "".join(parts)
|
||
if not text.strip():
|
||
continue
|
||
sections = list(dict.fromkeys(value for b in blocks for value in (b.section, b.source_locator) if value))
|
||
pages = list(dict.fromkeys(b.page for b in blocks))
|
||
section = " | ".join(sections)
|
||
page = pages[0] if len(pages) == 1 else None
|
||
# Keep page ranges in section when a semantic rule spans pages.
|
||
if len(pages) > 1:
|
||
section = "pages/" + ",".join(str(p) for p in pages if p is not None) + " | " + section
|
||
# FAQ, visual groups, regulations and conditional circulars are indivisible.
|
||
protected = atomic or any(RULE.match(b.text) or GOVERNING_RULE.match(b.text) for b in blocks) or bool(re.search(
|
||
r"تبصره|استثنا|مگر|مشروط|به\s+شرط|نمی|نباید|نیست|"
|
||
r"\b(?:except|unless|provided|condition|not|exclusion|note)\b", text, re.I))
|
||
normalized = normalize_search_text(text, profile["normalizer"])
|
||
if protected and len(normalized) > size and not allow_partial_extraction(profile):
|
||
raise ExtractionError("Semantic group exceeds chunk bound; cannot separate required context")
|
||
if len(normalized) <= size:
|
||
chunks.append(ChunkDraft(len(chunks), text, page, section))
|
||
else:
|
||
# Faithful character windows, bounded by actual normalized length; no trim.
|
||
start = 0
|
||
while start < len(text):
|
||
end = min(len(text), start + size)
|
||
while len(normalize_search_text(text[start:end], profile["normalizer"])) > size:
|
||
end -= 1
|
||
if end <= start:
|
||
raise ExtractionError("Chunk cannot fit character bound")
|
||
if end < len(text):
|
||
boundary = text.rfind("\n", start + size // 2, end)
|
||
if boundary >= 0:
|
||
end = boundary + 1
|
||
chunks.append(ChunkDraft(len(chunks), text[start:end], page, section))
|
||
if len(chunks) > profile["limits"]["max_chunks"]:
|
||
raise ExtractionError("Chunk count limit exceeded")
|
||
if end == len(text):
|
||
break
|
||
start = max(start + 1, end - min(overlap, end - start - 1))
|
||
if len(chunks) > profile["limits"]["max_chunks"]:
|
||
raise ExtractionError("Chunk count limit exceeded")
|
||
if not chunks:
|
||
raise ExtractionError("No indexable chunks")
|
||
return tuple(chunks)
|