"""Conservative, provenance-preserving text normalization."""
from __future__ import annotations
import re
import unicodedata
from ..models import DocumentElement, ParsedDocument
[docs]
def normalize_text(
text: str,
*,
unicode_form: str = "NFC",
normalize_whitespace: bool = True,
dehyphenate: bool = True,
strip: bool = True,
) -> str:
"""Normalize Unicode and common extraction artefacts without flattening layout."""
if unicode_form not in {"NFC", "NFKC", "NFD", "NFKD"}:
raise ValueError("unicode_form must be NFC, NFKC, NFD or NFKD")
normalized = unicodedata.normalize(unicode_form, text)
normalized = normalized.replace("\u00ad", "")
if dehyphenate:
normalized = re.sub(r"(?<=\w)-\n(?=\w)", "", normalized)
normalized = normalized.replace("\r\n", "\n").replace("\r", "\n")
if normalize_whitespace:
normalized = "\n".join(
re.sub(r"[\t\f\v ]+", " ", line).rstrip() for line in normalized.split("\n")
)
normalized = re.sub(r"\n{3,}", "\n\n", normalized)
return normalized.strip() if strip else normalized
[docs]
def normalize_document(
document: ParsedDocument,
*,
unicode_form: str = "NFC",
normalize_whitespace: bool = True,
dehyphenate: bool = True,
strip: bool = True,
) -> ParsedDocument:
"""Return a normalized copy; the original document is never modified."""
elements = tuple(
DocumentElement(
text=normalize_text(
element.text,
unicode_form=unicode_form,
normalize_whitespace=normalize_whitespace,
dehyphenate=dehyphenate,
strip=strip,
),
element_type=element.element_type,
page_number=element.page_number,
bbox=element.bbox,
reading_order=element.reading_order,
confidence=element.confidence,
metadata={**element.metadata, "normalized": True},
)
for element in document.elements
)
if document.elements and (
"\n\n".join(element.text for element in document.elements if element.text)
== document.content
):
content = "\n\n".join(element.text for element in elements if element.text)
else:
content = normalize_text(
document.content,
unicode_form=unicode_form,
normalize_whitespace=normalize_whitespace,
dehyphenate=dehyphenate,
strip=strip,
)
return ParsedDocument(
source=document.source,
content=content,
metadata={
**document.metadata,
"normalization": {
"unicode_form": unicode_form,
"normalize_whitespace": normalize_whitespace,
"dehyphenate": dehyphenate,
"strip": strip,
},
},
elements=elements,
)