from __future__ import annotations
import re
def markdown_to_viber(md_text: str) -> str:
text = md_text
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
text = re.sub(r"__([^_]+)__", r"\1", text)
text = re.sub(r"\*([^*\n]+)\*", r"\1", text)
text = re.sub(r"(?\1", text)
text = re.sub(r"`([^`\n]+)`", r"\1", text)
text = re.sub(r"~~(.+?)~~", r"", text)
text = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", text)
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1", text)
text = re.sub(r"^#{1,6}\s+(.+)$", r"\1", text, flags=re.MULTILINE)
text = re.sub(r"^>\s+(.+)$", r"\1", text, flags=re.MULTILINE)
text = re.sub(r"^-{3,}$", "────────────", text, flags=re.MULTILINE)
text = re.sub(r"^[*-]\s+(.+)$", r"• \1", text, flags=re.MULTILINE)
return text.strip()
def escape_viber_html(text: str) -> str:
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
return text
def chunk_text(text: str, limit: int = 7000) -> list[str]:
if len(text) <= limit:
return [text]
chunks: list[str] = []
while len(text) > limit:
split_point = text.rfind("\n", 0, limit)
if split_point == -1 or split_point < limit // 2:
split_point = text.rfind(". ", 0, limit)
if split_point == -1 or split_point < limit // 2:
split_point = text.rfind(" ", 0, limit)
if split_point == -1 or split_point < limit // 2:
split_point = limit
chunks.append(text[:split_point].strip())
text = text[split_point:].strip()
if text:
chunks.append(text)
return chunks