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*<(?Pp|h1|h2|h3)\b[^>]*>(?P.*?)\s*(?P.*)$", 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)}" if heading else "" return re.sub(r"<(h[1-6])\b[^>]*>(.*?)", replace_heading, html, flags=re.I | re.S) def replace_figcaption(figure_html: str, caption: str) -> str: caption_html = f"
{escape(caption)}
" if re.search(r"", figure_html, flags=re.I | re.S): return re.sub( r"]*>.*?", caption_html, figure_html, count=1, flags=re.I | re.S, ) return re.sub(r"", f"{caption_html}", 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"]*>.*?" 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"(]*>(?P.*?)\s*)(?P
{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)