Skip to content

Commit 186d7a2

Browse files
committed
add wa markdown formating
1 parent c38c952 commit 186d7a2

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

daras_ai/text_format.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import ast
2-
2+
import re
33
import parse
44
from markdown_it import MarkdownIt
55

@@ -48,3 +48,21 @@ def format_number_with_suffix(num: int) -> str:
4848
def unmarkdown(text: str) -> str:
4949
"""markdown to plaintext"""
5050
return MarkdownIt(renderer_cls=RendererPlain).render(text)
51+
52+
53+
def wa_markdown(text: str) -> str:
54+
patterns = [
55+
(
56+
re.compile(r"^(#+)\s+(.*)$", flags=re.MULTILINE),
57+
lambda m: f"*{m.group(2)}*",
58+
), # "# headings" -> "*headings*"
59+
(
60+
re.compile(r"\*\*(.+?)\*\*"),
61+
lambda m: f"*{m.group(1)}*",
62+
), # "**bold**"" -> "*bold*"
63+
]
64+
65+
for pattern, repl in patterns:
66+
text = pattern.sub(repl, text)
67+
68+
return text

daras_ai_v2/facebook_bots.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from daras_ai_v2.bots import BotInterface, ReplyButton, ButtonPressed
1111
from daras_ai_v2.exceptions import raise_for_status
1212
from daras_ai_v2.text_splitter import text_splitter
13+
from daras_ai.text_format import wa_markdown
1314

1415
WA_MSG_MAX_SIZE = 1024
1516

@@ -137,6 +138,7 @@ def send_msg_to(
137138
) -> str | None:
138139
# see https://developers.facebook.com/docs/whatsapp/api/messages/media/
139140

141+
text = wa_markdown(text)
140142
# split text into chunks if too long
141143
if text and len(text) > WA_MSG_MAX_SIZE:
142144
splits = text_splitter(

daras_ai_v2/text_splitter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
re.compile(sentence_end + new_para),
3333
re.compile(new_para),
3434
re.compile(sentence_end + new_line),
35-
re.compile(sentence_end + whitespace),
35+
# re.compile(sentence_end + whitespace),
3636
re.compile(new_line),
3737
re.compile(whitespace),
3838
)

0 commit comments

Comments
 (0)