Skip to content

Commit

Permalink
add wa markdown formating
Browse files Browse the repository at this point in the history
  • Loading branch information
milovate committed Jan 14, 2025
1 parent c38c952 commit 74d2d21
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
13 changes: 12 additions & 1 deletion daras_ai/text_format.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ast

import re
import parse
from markdown_it import MarkdownIt

Expand Down Expand Up @@ -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
4 changes: 3 additions & 1 deletion daras_ai_v2/facebook_bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion daras_ai_v2/text_splitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
Expand Down

0 comments on commit 74d2d21

Please sign in to comment.