ForcePilot/backend/package/yuxi/channel/extensions/twitch/markdown.py

42 lines
1.5 KiB
Python
Raw Normal View History

import re
def strip_markdown_for_twitch(markdown: str) -> str:
text = markdown
text = re.sub(r"!\[[^\]]*\]\([^)]+\)", "", text)
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"\1", text)
text = re.sub(r"(?<!_)_([^_]+)_(?!_)", r"\1", text)
text = re.sub(r"~~([^~]+)~~", r"\1", text)
text = re.sub(r"```[\s\S]*?```", lambda m: m.group(0).replace("```", "").strip(), text)
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE)
text = re.sub(r"^\s*[-*+]\s+", "", text, flags=re.MULTILINE)
text = re.sub(r"^\s*\d+\.\s+", "", text, flags=re.MULTILINE)
text = text.replace("\n", " ")
text = re.sub(r"[ \t]{2,}", " ", text)
return text.strip()
def chunk_text_for_twitch(text: str, limit: int = 500) -> list[str]:
cleaned = strip_markdown_for_twitch(text)
if len(cleaned) <= limit:
return [cleaned] if cleaned else []
chunks = []
remaining = cleaned
while len(remaining) > limit:
window = remaining[:limit]
last_space = window.rfind(" ")
if last_space == -1:
chunks.append(window)
remaining = remaining[limit:]
else:
chunks.append(window[:last_space])
remaining = remaining[last_space + 1 :]
if remaining:
chunks.append(remaining)
return chunks