diff --git a/daras_ai/text_format.py b/daras_ai/text_format.py index a7f4eac23..f832f1047 100644 --- a/daras_ai/text_format.py +++ b/daras_ai/text_format.py @@ -1,5 +1,5 @@ import ast - +import re import parse from markdown_it import MarkdownIt @@ -48,3 +48,14 @@ def format_number_with_suffix(num: int) -> str: def unmarkdown(text: str) -> str: """markdown to plaintext""" return MarkdownIt(renderer_cls=RendererPlain).render(text) + +def wa_markdown(text: str) -> str: + patterns = [ + (re.compile(r'^(#+)\s+(.*)$', flags=re.MULTILINE), lambda m: f"*{m.group(2)}*"), # "# headings" -> "*headings*" + (re.compile(r'\*\*(.+?)\*\*'), lambda m: f"*{m.group(1)}*") # "**bold**"" -> "*bold*" + ] + + for pattern, repl in patterns: + text = pattern.sub(repl, text) + + return text \ No newline at end of file diff --git a/daras_ai_v2/facebook_bots.py b/daras_ai_v2/facebook_bots.py index e4e9b93a6..5911c1d47 100644 --- a/daras_ai_v2/facebook_bots.py +++ b/daras_ai_v2/facebook_bots.py @@ -10,6 +10,7 @@ from daras_ai_v2.bots import BotInterface, ReplyButton, ButtonPressed from daras_ai_v2.exceptions import raise_for_status from daras_ai_v2.text_splitter import text_splitter +from daras_ai.text_format import wa_markdown WA_MSG_MAX_SIZE = 1024 @@ -136,7 +137,8 @@ def send_msg_to( access_token: str | None = None, ) -> str | None: # see https://developers.facebook.com/docs/whatsapp/api/messages/media/ - + + text=wa_markdown(text) # split text into chunks if too long if text and len(text) > WA_MSG_MAX_SIZE: splits = text_splitter( diff --git a/daras_ai_v2/text_splitter.py b/daras_ai_v2/text_splitter.py index 9e6079200..2124a4aa3 100644 --- a/daras_ai_v2/text_splitter.py +++ b/daras_ai_v2/text_splitter.py @@ -32,7 +32,7 @@ re.compile(sentence_end + new_para), re.compile(new_para), re.compile(sentence_end + new_line), - re.compile(sentence_end + whitespace), + # re.compile(sentence_end + whitespace), re.compile(new_line), re.compile(whitespace), )