import html import re from html.parser import HTMLParser class HTMLToTextParser(HTMLParser): def __init__(self): super().__init__() self._parts: list[str] = [] self._skip_depth = 0 self._current_href: str | None = None def handle_starttag(self, tag, attrs): if tag in ("script", "style", "head", "meta", "link"): self._skip_depth += 1 if tag == "a": for name, value in attrs: if name == "href": self._current_href = value break def handle_endtag(self, tag): if tag in ("script", "style", "head", "meta", "link") and self._skip_depth > 0: self._skip_depth -= 1 if tag in ("p", "br", "li", "div", "tr", "h1", "h2", "h3", "h4", "h5", "h6"): self._parts.append("\n") if tag == "a" and self._current_href: self._parts.append(f" ({self._current_href})") self._current_href = None def handle_data(self, data): if self._skip_depth == 0: self._parts.append(data) def get_text(self) -> str: return "".join(self._parts).strip() def html_to_text(html_body: str) -> str: parser = HTMLToTextParser() parser.feed(html_body) return parser.get_text() def markdown_to_html(md_text: str) -> str: text = html.escape(md_text) text = re.sub(r"```(\w+)?\n?(.*?)```", r"
\2", text, flags=re.DOTALL)
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
text = re.sub(r"\*(.+?)\*", r"\1", text)
text = re.sub(r"~~(.+?)~~", r"{heading_match.group(1)}
") continue if not stripped: result.append("