dzen.nstarikov.ru/app/captions.py

95 lines
3.2 KiB
Python
Raw Permalink Normal View History

2026-06-27 14:07:10 +03:00
import re
from html import escape, unescape
def clean_caption_text(value: str) -> str:
text = re.sub(r"<.*?>", "", value, flags=re.S)
text = unescape(text)
text = re.sub(r"\s+", " ", text).strip()
return re.sub(r"^(?:#{1,6}\s*)+", "", text).strip()
def normalized_plain_text(value: str) -> str:
return clean_caption_text(value).lower().replace("ё", "е")
def strip_leading_duplicate_title(html: str, article_title: str) -> str:
title = normalized_plain_text(article_title)
if not html or not title:
return html
def remove_if_duplicate(match: re.Match[str]) -> str:
text = normalized_plain_text(match.group("content"))
if text == title:
return match.group("tail").lstrip()
return match.group(0)
return re.sub(
r"^\s*<(?P<tag>p|h1|h2|h3)\b[^>]*>(?P<content>.*?)</(?P=tag)>\s*(?P<tail>.*)$",
remove_if_duplicate,
html,
count=1,
flags=re.I | re.S,
).strip()
def normalize_heading_tags(html: str) -> str:
def replace_heading(match: re.Match[str]) -> str:
tag = match.group(1).lower()
heading = clean_caption_text(match.group(2))
return f"<{tag}>{escape(heading)}</{tag}>" if heading else ""
return re.sub(r"<(h[1-6])\b[^>]*>(.*?)</\1>", replace_heading, html, flags=re.I | re.S)
def replace_figcaption(figure_html: str, caption: str) -> str:
caption_html = f"<figcaption>{escape(caption)}</figcaption>"
if re.search(r"<figcaption\b.*?</figcaption>", figure_html, flags=re.I | re.S):
return re.sub(
r"<figcaption\b[^>]*>.*?</figcaption>",
caption_html,
figure_html,
count=1,
flags=re.I | re.S,
)
return re.sub(r"</figure>", f"{caption_html}</figure>", figure_html, count=1, flags=re.I)
def normalize_article_captions(html: str, article_title: str) -> str:
title = clean_caption_text(article_title)
if not html or not title:
return html
html = normalize_heading_tags(html)
figure_pattern = r"<figure\b[^>]*>.*?</figure>"
def normalize_cover(match: re.Match[str]) -> str:
figure = match.group(0)
if "article-cover" not in figure:
return figure
return replace_figcaption(figure, title)
html = re.sub(figure_pattern, normalize_cover, html, flags=re.I | re.S)
def normalize_uncaptioned_or_generic(match: re.Match[str]) -> str:
figure = match.group(0)
if "premium-cover" in figure:
return figure
return replace_figcaption(figure, title)
html = re.sub(figure_pattern, normalize_uncaptioned_or_generic, html, flags=re.I | re.S)
heading_with_figure_pattern = rf"(<h2\b[^>]*>(?P<heading>.*?)</h2>\s*)(?P<figure>{figure_pattern})"
def normalize_section_figure(match: re.Match[str]) -> str:
prefix = match.group(1)
figure = match.group("figure")
if "premium-cover" in figure or "article-cover" in figure:
return match.group(0)
heading = clean_caption_text(match.group("heading"))
if not heading:
heading = title
return f"{prefix}{replace_figcaption(figure, heading)}"
return re.sub(heading_with_figure_pattern, normalize_section_figure, html, flags=re.I | re.S)