Skip to content

Commit

Permalink
Improve markdown formatting - 2
Browse files Browse the repository at this point in the history
  • Loading branch information
yorevs committed Mar 27, 2024
1 parent 7deb5f3 commit 33e164b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 37 deletions.
21 changes: 7 additions & 14 deletions src/main/askai/core/processor/instances/summary_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,22 +107,15 @@ def process(self, query_response: ProcessorResponse) -> Tuple[bool, Optional[str
def _qna(self) -> str:
"""Questions and Answers about the summarized content."""
display_text(
f"%CYAN%{'-=' * 40}%EOL%"
f" {msg.enter_qna()} %EOL%"
f" {summarizer.sum_path} %EOL%"
f"{msg.press_esc_enter()} %EOL%"
f"{'-=' * 40}%NC%",
markdown=False
f"#  {msg.enter_qna()} %EOL%"
f"> Content:  {summarizer.sum_path} %EOL%%EOL%"
f"`{msg.press_esc_enter()}` %EOL%"
)
AskAiEvents.ASKAI_BUS.events.reply.emit(message=msg.qna_welcome())
while question := shared.input_text(f"{shared.username}: %CYAN%"):
while question := shared.input_text(f"{shared.username}: %GREEN%"):
if not (output := self._ask_and_reply(question)):
break
AskAiEvents.ASKAI_BUS.events.reply.emit(message=f"%CYAN%{output}%NC%")
display_text(
f"%CYAN%{'-=' * 40}%EOL%"
f" {msg.leave_qna()}%EOL%"
f"{'-=' * 40}%NC%",
markdown=False
)
AskAiEvents.ASKAI_BUS.events.reply.emit(message=f"%GREEN%{output}%NC%")
display_text(f"#  {msg.leave_qna()} %EOL%")

return msg.welcome_back()
42 changes: 20 additions & 22 deletions src/main/askai/core/support/text_formatter.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import re
from random import randint
from textwrap import dedent
from typing import Any

from hspylib.core.metaclass.singleton import Singleton
from hspylib.core.tools.commons import sysout
from hspylib.core.tools.dict_tools import get_or_default
from hspylib.modules.cli.vt100.vt_code import VtCode
from hspylib.modules.cli.vt100.vt_color import VtColor
from rich.console import Console
from rich.highlighter import RegexHighlighter, Highlighter
from rich.markdown import Markdown
from rich.text import Text


class TextFormatter(metaclass=Singleton):
Expand All @@ -28,7 +27,7 @@ class TextFormatter(metaclass=Singleton):
}

def __init__(self):
self._console: Console = Console(soft_wrap=True)
self._console: Console = Console(emoji=True, soft_wrap=True, markup=True)

@property
def console(self) -> Console:
Expand All @@ -52,35 +51,24 @@ def beautify(self, text: Any) -> str:
text = re.sub(r"[Ff]un [Ff]acts?[-:\s]\s+", self.CHAT_ICONS[''], text)
text = re.sub(r"([Jj]oke( [Tt]ime)?)[-:\s]\s+", self.CHAT_ICONS[''], text)
text = re.sub(r"[Aa]dvice[-:\s]\s+", self.CHAT_ICONS[''], text)
mat = re.search(r"%\w+%", text)
fg = mat.group() if mat else ''
text = re.sub(re_url, r' \1', text)
fg = get_or_default(re.findall(r"%\w+%", text), 0, '%NC%')
text = re.sub(re_url, r'%CYAN% \1' + fg, text)
# fmt: on

return text.strip()

def display_markdown(self, text: str) -> None:
colorized: str = VtColor.colorize(VtCode.decode(self.beautify(text)))
self.console.print(Markdown(colorized), highlight=True)
self.console.print(Markdown(colorized))

def display_text(self, text: str) -> None:
sysout(self.beautify(text))
colorized: str = VtColor.colorize(VtCode.decode(self.beautify(text)))
self.console.print(Text.from_ansi(colorized))


assert (text_formatter := TextFormatter().INSTANCE) is not None


class RainbowHighlighter(Highlighter):
def highlight(self, text):
for index in range(len(text)):
text.stylize(f"color({randint(16, 255)})", index, index + 1)


class Highlighter(RegexHighlighter):
base_style = "help."
highlights = [r"(?P<cmd>!help\b)", r"(?P<cmd2>\'|\"[\w]+\"|\')"]


if __name__ == '__main__':
s = dedent("""
Error: This should be red
Expand All @@ -89,8 +77,18 @@ class Highlighter(RegexHighlighter):
Joke: This should be magenta
Analysis: This should be yellow
This is not OK because it has failed to be a success!
# H1
## H2
### H3
#### H4
##### H5
`This is not OK because it has failed to be a success!`
```bash
$ ls -lht ~/Downloads
```
For more details access: https://askai.github.io/askai Enjoy!
For more details access: https://askai.github.io/askai. Enjoy!
""")
text_formatter.display_markdown(s)
4 changes: 3 additions & 1 deletion src/main/askai/core/support/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ def extract_command(markdown_text: str, flags: int = re.IGNORECASE | re.MULTILIN
## you can find the code at https://github.com/yorevs
:poop: POOOP
### Emailto: yorevs@example.com
"""
display_text(s)
display_text(s, markdown=False)

0 comments on commit 33e164b

Please sign in to comment.