Files
rag-technical-docs-assistant/app/modules/documents/normalization.py
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

36 lines
1.5 KiB
Python

"""Existing v1 canonical Unicode and line-ending normalization only."""
import unicodedata
from collections.abc import Mapping
from .types import ExtractionEnvelope
NORMALIZATION_POLICY = "unicode-line-endings-v1"
def normalize_search_text(text: str, policy: str = NORMALIZATION_POLICY) -> str:
if policy != NORMALIZATION_POLICY:
raise ValueError("Unsupported normalization policy; migration/reindex design required")
return unicodedata.normalize("NFC", text.replace("\r\n", "\n").replace("\r", "\n"))
def normalized_inputs(envelope: ExtractionEnvelope, processing_profile: Mapping) -> tuple[str, ...]:
"""Check/rederive all inputs and aggregate character budget before consumption.
Faithful evidence is never mutated; missing search_text is derived on demand.
No partial collection is returned if any block or the total fails validation.
"""
policy = processing_profile["normalizer"]
if envelope.normalization_policy != policy:
raise ValueError("Artifact normalization identity mismatch")
limit = processing_profile["limits"]["max_normalized_characters"]
total, inputs = 0, []
for block in envelope.blocks:
derived = normalize_search_text(block.text, policy)
if block.search_text is not None and block.search_text != derived:
raise ValueError("Stored search text is not a valid faithful-text derivation")
total += len(derived)
if total > limit:
raise ValueError("Normalized input exceeds character budget")
inputs.append(derived)
return tuple(inputs)