polish-dynaword / src /html_text.py
Maggio33's picture ppuzio's picture
Add in-tree PII scrub (no new parquet) (#20)
a916ede
Raw History Blame Contribute Delete
737 Bytes
"""Shared HTML → text for fetchers. Block tags become newlines; inline tags drop."""
from __future__ import annotations
import re
from html import unescape
_SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
_BLOCK_END = re.compile(
r"(?i)</(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|<br\s*/?>"
)
_TAG = re.compile(r"<[^>]+>")
def html_to_text(html: str) -> str:
if not html:
return ""
html = _SCRIPT.sub("", html)
html = _BLOCK_END.sub("\n", html)
html = _TAG.sub("", html)
text = unescape(html).replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r" *\n *", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()