Fabelous-Ai-Chat/scripts/Message.py

78 lines
3.2 KiB
Python
Raw Normal View History

import re
import tkinter as tk
CODE_PREFIX = "[1337]"
class Reply(tk.Frame):
def __init__(self, master, message,reply_type, font_size=12, background="#252525", text_color="white"):
super().__init__(master)
self.font = ("Helvetica", font_size)
self.background = background
self.text_color = text_color
self.reply_type = reply_type
self.message = self.extract_code(message)
self.reply_scope = []
2024-05-20 11:24:41 +00:00
# change background of message
self.configure(background=self.background)
label = tk.Label(master=self, text=self.reply_type, background=background, foreground="#a51c30",
font=self.font, wraplength=500 )
label.grid(row=0, column=0, padx=5, pady=5, sticky='ew')
row_index = 1 # Track the current grid row for widgets
for part in self.message:
2024-05-20 11:24:41 +00:00
# part is a code block
if part.startswith(CODE_PREFIX):
part = part[len(CODE_PREFIX):]
code = tk.Text(master=self, width=50, font=self.font,
bg=self.background, fg=self.text_color, wrap="word")
code.grid(row=row_index, column=0, padx=5, pady=5, sticky='ew')
code.insert("1.0", part)
line_count = int(code.index('end-1c').split('.')[0])
code.config(height=line_count, state="disabled")
self.reply_scope.append(code)
else:
label = tk.Label(master=self, text=part, background=background, foreground=text_color,
font=self.font, wraplength=500 )
label.grid(row=row_index, column=0, padx=5, pady=5, sticky='nsew')
self.reply_scope.append(label)
row_index += 1
2024-05-20 11:24:41 +00:00
def extract_code(self, input_string: str, replacement=CODE_PREFIX) -> list:
# Split the input string on the ``` delimiter
split_parts = re.split(r'(```)', input_string) # Include the delimiter in the results
2024-05-20 11:24:41 +00:00
# Initialize an empty list to store the output array
output_array = []
2024-05-20 11:24:41 +00:00
# Track whether the previous part was a ``` delimiter
previously_delimiter = False
for part in split_parts:
# Check if the current part is a ``` delimiter
if part == "```":
previously_delimiter = True # Set flag if a delimiter is found
continue # Skip adding the delimiter to the output
# If the previous part was a delimiter, replace the first word with the specified string
if previously_delimiter:
part = re.sub(r'^\b\w+\b', replacement, part, count=1) # Replace the programming Language
previously_delimiter = False # Reset the flag
# Only add non-empty parts to the output array
if part.strip():
output_array.append(part)
return output_array