-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathconversation_tab.py
More file actions
1437 lines (1270 loc) Β· 44.5 KB
/
Copy pathconversation_tab.py
File metadata and controls
1437 lines (1270 loc) Β· 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Implements the conversation tab interface for the BasiliskLLM chat application.
This module provides the ConversationTab class, which handles all UI and logic for individual
chat conversations. It manages message display, user input, audio recording, image attachments,
and interaction with AI providers.
Features:
- Text input/output with markdown support
- attachment handling
- Audio recording and transcription
- Message navigation and searching
- Accessible output integration
- Streaming message support
"""
from __future__ import annotations
import datetime
import logging
import re
import threading
import time
from multiprocessing import Process
from typing import TYPE_CHECKING, Any, Optional
import wx
from httpx import HTTPError
from more_itertools import first, locate
from upath import UPath
import basilisk.config as config
from basilisk import global_vars
from basilisk.accessible_output import get_accessible_output
from basilisk.conversation import (
PROMPT_TITLE,
URL_PATTERN,
AttachmentFile,
Conversation,
ImageFile,
Message,
MessageBlock,
MessageRoleEnum,
SystemMessage,
build_from_url,
get_mime_type,
parse_supported_attachment_formats,
)
from basilisk.decorators import ensure_no_task_running
from basilisk.provider_ai_model import ProviderAIModel
from basilisk.provider_capability import ProviderCapability
from basilisk.sound_manager import play_sound, stop_sound
from .base_conversation import BaseConversation
from .history_msg_text_ctrl import HistoryMsgTextCtrl
from .ocr_handler import OCRHandler
from .read_only_message_dialog import ReadOnlyMessageDialog
if TYPE_CHECKING:
from basilisk.provider_engine.base_engine import BaseEngine
from basilisk.recording_thread import RecordingThread
from .main_frame import MainFrame
log = logging.getLogger(__name__)
accessible_output = get_accessible_output()
CHECK_TASK_DELAY = 100 # ms
class ConversationTab(wx.Panel, BaseConversation):
"""A tab panel that manages a single conversation with an AI assistant.
This class provides a complete interface for interacting with AI models, including:
- Text input and output
- attachment handling
- Audio recording and transcription
- Message history navigation
- Accessible output integration
- Stream mode for real-time responses
Attributes:
title: The title of the conversation
conversation: The conversation object
attachment_files: List of attachment files
"""
@staticmethod
def conv_storage_path() -> UPath:
"""Generate a unique storage path for a conversation based on the current timestamp.
Returns:
A memory-based URL path with a timestamp-specific identifier for storing conversation attachments.
"""
return UPath(
f"memory://conversation_{datetime.datetime.now().isoformat(timespec='seconds')}"
)
@classmethod
def open_conversation(
cls, parent: wx.Window, file_path: str, default_title: str
) -> ConversationTab:
"""Open a conversation from a file and create a new ConversationTab instance.
This class method loads a conversation from a specified file path, generates a unique storage path,
and initializes a new ConversationTab with the loaded conversation details.
Args:
parent: The parent window for the conversation tab.
file_path: The path to the conversation file to be opened.
default_title: A fallback title to use if the conversation has no title.
Returns:
A new ConversationTab instance with the loaded conversation.
Raises:
IOError: If the conversation file cannot be read or parsed.
Example:
conversation_tab = ConversationTab.open_conversation(
parent_window, "/path/to/conversation.json", "My Conversation"
)
"""
log.debug(f"Opening conversation from {file_path}")
storage_path = cls.conv_storage_path()
conversation = Conversation.open(file_path, storage_path)
title = conversation.title or default_title
return cls(
parent,
conversation=conversation,
title=title,
conv_storage_path=storage_path,
bskc_path=file_path,
)
def __init__(
self,
parent: wx.Window,
title: str = _("Untitled conversation"),
profile: Optional[config.ConversationProfile] = None,
conversation: Optional[Conversation] = None,
conv_storage_path: Optional[UPath] = None,
bskc_path: Optional[str] = None,
):
"""Initialize a new conversation tab in the chat application.
Initializes the conversation tab by:
- Setting up the wx.Panel and BaseConversation base classes
- Configuring conversation metadata and storage
- Preparing UI components and data structures
- Initializing recording and message management resources
Args:
parent: The parent window containing this conversation tab.
title: The title of the conversation. Defaults to "Untitled conversation".
profile: The conversation profile to apply. Defaults to None.
conversation: An existing conversation to load. Defaults to a new Conversation.
conv_storage_path: Unique storage path for the conversation. Defaults to a generated path.
bskc_path: Path to a specific configuration file. Defaults to None.
"""
wx.Panel.__init__(self, parent)
BaseConversation.__init__(self)
self.title = title
self.SetStatusText = self.TopLevelParent.SetStatusText
self.bskc_path = bskc_path
self.conv_storage_path = conv_storage_path or self.conv_storage_path()
self.conversation = conversation or Conversation()
self.attachment_files: list[AttachmentFile | ImageFile] = []
self.last_time = 0
self.recording_thread: Optional[RecordingThread] = None
self.task = None
self.process: Optional[Process] = None
self._stop_completion = False
self.ocr_handler = OCRHandler(self)
self.init_ui()
self.init_data(profile)
self.adjust_advanced_mode_setting()
def init_ui(self):
"""Initialize and layout all UI components of the conversation tab.
Creates and configures:
- Account selection combo box
- System prompt input
- Message history display
- User prompt input
- Attachment list display
- Model selection
- Generation parameters
- Control buttons
"""
sizer = wx.BoxSizer(wx.VERTICAL)
label = self.create_account_widget()
sizer.Add(label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.account_combo, proportion=0, flag=wx.EXPAND)
label = self.create_system_prompt_widget()
sizer.Add(label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.system_prompt_txt, proportion=1, flag=wx.EXPAND)
label = wx.StaticText(
self,
# Translators: This is a label for user prompt in the main window
label=_("&Messages:"),
)
sizer.Add(label, proportion=0, flag=wx.EXPAND)
self.messages = HistoryMsgTextCtrl(self, size=(800, 400))
sizer.Add(self.messages, proportion=1, flag=wx.EXPAND)
label = wx.StaticText(
self,
# Translators: This is a label for user prompt in the main window
label=_("&Prompt:"),
)
sizer.Add(label, proportion=0, flag=wx.EXPAND)
self.prompt = wx.TextCtrl(
self,
size=(800, 100),
style=wx.TE_MULTILINE | wx.TE_WORDWRAP | wx.HSCROLL,
)
self.prompt.Bind(wx.EVT_KEY_DOWN, self.on_prompt_key_down)
self.prompt.Bind(wx.EVT_CONTEXT_MENU, self.on_prompt_context_menu)
self.prompt.Bind(wx.EVT_TEXT_PASTE, self.on_prompt_paste)
sizer.Add(self.prompt, proportion=1, flag=wx.EXPAND)
self.prompt.SetFocus()
self.attachments_list_label = wx.StaticText(
self,
# Translators: This is a label for models in the main window
label=_("&Attachments:"),
)
sizer.Add(self.attachments_list_label, proportion=0, flag=wx.EXPAND)
self.attachments_list = wx.ListCtrl(
self, size=(800, 100), style=wx.LC_REPORT
)
self.attachments_list.Bind(
wx.EVT_CONTEXT_MENU, self.on_attachments_context_menu
)
self.attachments_list.Bind(
wx.EVT_KEY_DOWN, self.on_attachments_key_down
)
self.attachments_list.InsertColumn(
0,
# Translators: This is a label for attachment name in the main window
_("Name"),
)
self.attachments_list.InsertColumn(
1,
# Translators: This is a label for attachment size in the main window
_("Size"),
)
self.attachments_list.InsertColumn(
2,
# Translators: This is a label for attachment location in the main window
_("Location"),
)
self.attachments_list.SetColumnWidth(0, 200)
self.attachments_list.SetColumnWidth(1, 100)
self.attachments_list.SetColumnWidth(2, 500)
sizer.Add(self.attachments_list, proportion=0, flag=wx.ALL | wx.EXPAND)
self.ocr_button = self.ocr_handler.create_ocr_widget(self)
sizer.Add(self.ocr_button, proportion=0, flag=wx.EXPAND)
label = self.create_model_widget()
sizer.Add(label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.model_list, proportion=0, flag=wx.ALL | wx.EXPAND)
self.create_web_search_widget()
sizer.Add(self.web_search_mode, proportion=0, flag=wx.EXPAND)
self.create_max_tokens_widget()
sizer.Add(self.max_tokens_spin_label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.max_tokens_spin_ctrl, proportion=0, flag=wx.EXPAND)
self.create_temperature_widget()
sizer.Add(self.temperature_spinner_label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.temperature_spinner, proportion=0, flag=wx.EXPAND)
self.create_top_p_widget()
sizer.Add(self.top_p_spinner_label, proportion=0, flag=wx.EXPAND)
sizer.Add(self.top_p_spinner, proportion=0, flag=wx.EXPAND)
self.create_stream_widget()
sizer.Add(self.stream_mode, proportion=0, flag=wx.EXPAND)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.submit_btn = wx.Button(
self,
# Translators: This is a label for submit button in the main window
label=_("Submit") + " (Ctrl+Enter)",
)
self.submit_btn.Bind(wx.EVT_BUTTON, self.on_submit)
self.submit_btn.SetDefault()
btn_sizer.Add(self.submit_btn, proportion=0, flag=wx.EXPAND)
self.stop_completion_btn = wx.Button(
self,
# Translators: This is a label for stop completion button in the main window
label=_("Stop completio&n"),
)
self.stop_completion_btn.Bind(wx.EVT_BUTTON, self.on_stop_completion)
btn_sizer.Add(self.stop_completion_btn, proportion=0, flag=wx.EXPAND)
self.stop_completion_btn.Hide()
self.toggle_record_btn = wx.Button(
self,
# Translators: This is a label for record button in the main window
label=_("Record") + " (Ctrl+R)",
)
btn_sizer.Add(self.toggle_record_btn, proportion=0, flag=wx.EXPAND)
self.toggle_record_btn.Bind(wx.EVT_BUTTON, self.toggle_recording)
self.apply_profile_btn = wx.Button(
self,
# Translators: This is a label for apply profile button in the main window
label=_("Apply profile") + " (Ctrl+P)",
)
self.apply_profile_btn.Bind(wx.EVT_BUTTON, self.on_choose_profile)
btn_sizer.Add(self.apply_profile_btn, proportion=0, flag=wx.EXPAND)
sizer.Add(btn_sizer, proportion=0, flag=wx.EXPAND)
self.SetSizerAndFit(sizer)
self.Bind(wx.EVT_CHAR_HOOK, self.on_char_hook)
def init_data(self, profile: Optional[config.ConversationProfile]):
"""Initialize the conversation data with an optional profile.
Args:
profile: Configuration profile to apply
"""
self.refresh_attachments_list()
self.apply_profile(profile, True)
self.refresh_messages(need_clear=False)
def on_choose_profile(self, event: wx.KeyEvent | None):
"""Displays a context menu for selecting a conversation profile.
This method triggers the creation of a profile selection menu from the main application frame
and shows it as a popup menu at the current cursor position. After the user makes a selection,
the menu is automatically destroyed.
Args:
event: The event that triggered the profile selection menu.
"""
main_frame: MainFrame = wx.GetTopLevelParent(self)
menu = main_frame.build_profile_menu(
main_frame.on_apply_conversation_profile
)
self.PopupMenu(menu)
menu.Destroy()
def on_char_hook(self, event: wx.KeyEvent):
"""Handle keyboard shortcuts for the conversation tab.
Args:
event: The keyboard event
"""
shortcut = (event.GetModifiers(), event.GetKeyCode())
actions = {(wx.MOD_CONTROL, ord('P')): self.on_choose_profile}
action = actions.get(shortcut, wx.KeyEvent.Skip)
action(event)
def on_account_change(self, event: wx.CommandEvent | None):
"""Handle account selection changes in the conversation tab.
Updates the model list based on the selected account's.
Enables/disables the record button based on the selected account's capabilities.
Args:
event: The account selection event
"""
account = super().on_account_change(event)
if not account:
return
self.set_model_list(None)
self.toggle_record_btn.Enable(
ProviderCapability.STT in account.provider.engine_cls.capabilities
)
self.ocr_button.Enable(
ProviderCapability.OCR in account.provider.engine_cls.capabilities
)
self.web_search_mode.Enable(
ProviderCapability.WEB_SEARCH
in account.provider.engine_cls.capabilities
)
def on_attachments_context_menu(self, event: wx.ContextMenuEvent):
"""Display context menu for the attachments list.
Provides options for:
- Removing selected attachment
- Copying attachment location
- Pasting attachments
- Adding files
- Adding image URLs
Args:
event (wx.ContextMenuEvent): The context menu trigger event
"""
selected = self.attachments_list.GetFirstSelected()
menu = wx.Menu()
if selected != wx.NOT_FOUND:
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for show details in the context menu
_("Show details") + " Enter",
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_show_attachment_details, item)
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for remove selected attachment in the context menu
_("Remove selected attachment") + " Shift+Del",
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_attachments_remove, item)
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for copy location in the context menu
_("Copy location") + " Ctrl+C",
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_copy_attachment_location, item)
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for paste in the context menu
_("Paste (file or text)") + " Ctrl+V",
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_attachments_paste, item)
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for add files in the context menu
_("Add files..."),
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.add_attachments_dlg, item)
item = wx.MenuItem(
menu,
wx.ID_ANY,
# Translators: This is a label for add attachment URL in the context menu
_("Add attachment URL...") + " Ctrl+U",
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.add_attachment_url_dlg, item)
self.attachments_list.PopupMenu(menu)
menu.Destroy()
def on_attachments_key_down(self, event: wx.KeyEvent):
"""Handle keyboard shortcuts for the attachments list.
Supports:
- Ctrl+C: Copy file location
- Ctrl+V: Paste attachments
- Delete: Remove selected attachment
Args:
event: The keyboard event
"""
key_code = event.GetKeyCode()
modifiers = event.GetModifiers()
if modifiers == wx.MOD_CONTROL and key_code == ord("C"):
self.on_copy_attachment_location(None)
if modifiers == wx.MOD_CONTROL and key_code == ord("V"):
self.on_attachments_paste(None)
if modifiers == wx.MOD_NONE and key_code == wx.WXK_DELETE:
self.on_attachments_remove(None)
if modifiers == wx.MOD_NONE and key_code in (
wx.WXK_RETURN,
wx.WXK_NUMPAD_ENTER,
):
self.on_show_attachment_details(None)
event.Skip()
def on_attachments_paste(self, event: wx.CommandEvent):
"""Handles pasting content from the clipboard into the conversation interface.
Supports multiple clipboard data types:
- Files: Adds files directly to the conversation
- Text:
- If a valid URL is detected, adds the attachmentURL
- Otherwise, pastes text into the prompt input
- Bitmap images: Saves the image to a temporary file and adds it to the conversation
Args:
event: The clipboard paste event
"""
with wx.TheClipboard as clipboard:
if clipboard.IsSupported(wx.DataFormat(wx.DF_FILENAME)):
log.debug("Pasting files from clipboard")
file_data = wx.FileDataObject()
clipboard.GetData(file_data)
paths = file_data.GetFilenames()
self.add_attachments(paths)
elif clipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
log.debug("Pasting text from clipboard")
text_data = wx.TextDataObject()
clipboard.GetData(text_data)
text = text_data.GetText()
if re.fullmatch(URL_PATTERN, text):
log.info("Pasting URL from clipboard, adding attachment")
self.add_attachment_url_thread(text)
else:
log.info("Pasting text from clipboard")
self.prompt.WriteText(text)
self.prompt.SetFocus()
elif clipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)):
log.debug("Pasting bitmap from clipboard")
bitmap_data = wx.BitmapDataObject()
success = clipboard.GetData(bitmap_data)
if not success:
log.error("Failed to get bitmap data from clipboard")
return
img = bitmap_data.GetBitmap().ConvertToImage()
path = (
self.conv_storage_path
/ f"clipboard_{datetime.datetime.now().isoformat(timespec='seconds')}.png"
)
with path.open("wb") as f:
img.SaveFile(f, wx.BITMAP_TYPE_PNG)
self.add_attachments([ImageFile(location=path)])
else:
log.info("Unsupported clipboard data")
def add_attachments_dlg(self, event: wx.CommandEvent = None):
"""Open a file dialog to select and add files to the conversation.
Args:
event: Event triggered by the add files action
"""
wildcard = parse_supported_attachment_formats(
self.current_engine.supported_attachment_formats
)
if not wildcard:
wx.MessageBox(
# Translators: This message is displayed when there are no supported attachment formats.
_("This provider does not support any attachment formats."),
_("Error"),
wx.OK | wx.ICON_ERROR,
)
return
wildcard = _("All supported formats") + f" ({wildcard})|{wildcard}"
file_dialog = wx.FileDialog(
self,
# Translators: This is a label for select files in conversation tab
message=_("Select one or more files to attach"),
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
wildcard=wildcard,
)
if file_dialog.ShowModal() == wx.ID_OK:
paths = file_dialog.GetPaths()
self.add_attachments(paths)
file_dialog.Destroy()
def add_attachment_url_dlg(self, event: wx.CommandEvent | None):
"""Open a dialog to input an attachment URL and add it to the conversation.
Args:
event: Event triggered by the add attachment URL action
"""
url_dialog = wx.TextEntryDialog(
self,
# Translators: This is a label for enter URL in add attachment dialog
message=_("Enter the URL of the file to attach:"),
caption=_("Add attachment from URL"),
)
if url_dialog.ShowModal() != wx.ID_OK:
return
url = url_dialog.GetValue()
if not url:
return
if not re.fullmatch(URL_PATTERN, url):
wx.MessageBox(
_("Invalid URL, bad format."), _("Error"), wx.OK | wx.ICON_ERROR
)
return
self.add_attachment_url_thread(url)
url_dialog.Destroy()
def add_attachment_from_url(self, url: str):
"""Add an attachment to the conversation from a URL.
Args:
url: The URL of the file to attach
"""
attachment_file = None
try:
attachment_file = build_from_url(url)
except HTTPError as err:
wx.CallAfter(
wx.MessageBox,
# Translators: This message is displayed when the HTTP error occurs while adding a file from a URL.
_("HTTP error %s.") % err,
_("Error"),
wx.OK | wx.ICON_ERROR,
)
return
except BaseException as err:
log.error(err, exc_info=True)
wx.CallAfter(
wx.MessageBox,
# Translators: This message is displayed when an error occurs while adding a file from a URL.
_("Error adding attachment from URL: %s") % err,
_("Error"),
wx.OK | wx.ICON_ERROR,
)
return
wx.CallAfter(self.add_attachments, [attachment_file])
self.task = None
@ensure_no_task_running
def add_attachment_url_thread(self, url: str):
"""Start a thread to add an attachment to the conversation from a URL.
Args:
url: The URL of the file to attach
"""
self.task = threading.Thread(
target=self.add_attachment_from_url, args=(url,)
)
self.task.start()
def on_show_attachment_details(self, event: wx.CommandEvent):
"""Show details of the selected attachment in a read-only dialog.
Args:
event: Event triggered by the show attachment details action
"""
selected = self.attachments_list.GetFirstSelected()
if selected == wx.NOT_FOUND:
return
attachment_file = self.attachment_files[selected]
details = {
_("Name"): attachment_file.name,
_("Size"): attachment_file.display_size,
_("Location"): attachment_file.location,
}
mime_type = attachment_file.mime_type
if mime_type:
details[_("MIME type")] = mime_type
if mime_type.startswith("image/"):
details[_("Dimensions")] = attachment_file.display_dimensions
details_str = "\n".join(
_("%s: %s") % (k, v) for k, v in details.items()
)
ReadOnlyMessageDialog(
self, _("Attachment details"), details_str
).ShowModal()
def on_attachments_remove(self, event: wx.CommandEvent):
"""Remove the selected attachment from the conversation.
Args:
event: Event triggered by the remove attachment action
"""
selection = self.attachments_list.GetFirstSelected()
if selection == wx.NOT_FOUND:
return
self.attachment_files.pop(selection)
self.refresh_attachments_list()
if selection >= self.attachments_list.GetItemCount():
selection -= 1
if selection >= 0:
self.attachments_list.SetItemState(
selection, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED
)
else:
self.prompt.SetFocus()
def on_copy_attachment_location(self, event: wx.CommandEvent):
"""Copy the location of the selected attachment to the clipboard.
Args:
event: Event triggered by the copy attachment location action
"""
selected = self.attachments_list.GetFirstSelected()
if selected == wx.NOT_FOUND:
return
location = "\"%s\"" % str(self.attachment_files[selected].location)
with wx.TheClipboard as clipboard:
clipboard.SetData(wx.TextDataObject(location))
def refresh_accounts(self):
"""Update the account selection combo box with current accounts.
Preserves the current selection if possible, otherwise selects the first account.
"""
account_index = self.account_combo.GetSelection()
account_id = None
if account_index != wx.NOT_FOUND:
account_id = config.accounts()[account_index].id
self.account_combo.Clear()
self.account_combo.AppendItems(self.get_display_accounts(True))
account_index = first(
locate(config.accounts(), lambda a: a.id == account_id),
wx.NOT_FOUND,
)
if account_index != wx.NOT_FOUND:
self.account_combo.SetSelection(account_index)
elif self.account_combo.GetCount() > 0:
self.account_combo.SetSelection(0)
self.account_combo.SetFocus()
def refresh_attachments_list(self):
"""Update the attachments list display based on the current attachment files.
Shows/hides the attachments list based on the number of attachments.
Updates all attachment details in the list.
"""
self.attachments_list.DeleteAllItems()
if not self.attachment_files:
self.attachments_list_label.Hide()
self.attachments_list.Hide()
self.ocr_button.Hide()
self.Layout()
return
self.attachments_list_label.Show()
self.attachments_list.Show()
self.ocr_button.Show()
for attachment in self.attachment_files:
self.attachments_list.Append(attachment.get_display_info())
last_index = len(self.attachment_files) - 1
self.attachments_list.SetItemState(
last_index, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED
)
self.attachments_list.EnsureVisible(last_index)
self.Layout()
def add_attachments(self, paths: list[str | AttachmentFile | ImageFile]):
"""Add one or more attachments to the conversation.
Args:
paths: List of attachment file paths
"""
log.debug(f"Adding attachments: {paths}")
for path in paths:
if isinstance(path, (AttachmentFile, ImageFile)):
self.attachment_files.append(path)
else:
mime_type = get_mime_type(path)
supported_attachment_formats = (
self.current_engine.supported_attachment_formats
)
if mime_type not in supported_attachment_formats:
wx.MessageBox(
# Translators: This message is displayed when there are no supported attachment formats.
_(
"This attachment format is not supported by the current provider. Source:"
)
+ f"\n{path}",
_("Error"),
wx.OK | wx.ICON_ERROR,
)
continue
if mime_type.startswith("image/"):
file = ImageFile(location=path)
else:
file = AttachmentFile(location=path)
self.attachment_files.append(file)
self.refresh_attachments_list()
self.attachments_list.SetFocus()
def on_config_change(self):
"""Handle configuration changes in the conversation tab.
Update account, model list and advanced mode settings.
"""
self.refresh_accounts()
self.on_account_change(None)
self.on_model_change(None)
self.adjust_advanced_mode_setting()
def add_standard_context_menu_items(
self, menu: wx.Menu, include_paste: bool = True
):
"""Add standard context menu items to a menu.
Args:
menu: The menu to add items to
include_paste: Whether to include the paste item
"""
menu.Append(wx.ID_UNDO)
menu.Append(wx.ID_REDO)
menu.Append(wx.ID_CUT)
menu.Append(wx.ID_COPY)
if include_paste:
menu.Append(wx.ID_PASTE)
menu.Append(wx.ID_SELECTALL)
def on_prompt_context_menu(self, event: wx.ContextMenuEvent):
"""Display context menu for the prompt text control.
Provides options for:
- Inserting the previous prompt
- Submitting the current prompt
- Pasting content from the clipboard
- Copying content from the prompt
- Cutting content from the prompt
- Selecting all content in the prompt
Args:
event: The context menu trigger event
"""
menu = wx.Menu()
item = wx.MenuItem(
menu, wx.ID_ANY, _("Insert previous prompt") + " Ctrl+Up"
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.insert_previous_prompt, item)
item = wx.MenuItem(menu, wx.ID_ANY, _("Submit") + " (Ctrl+Enter)")
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_submit, item)
item = wx.MenuItem(
menu, wx.ID_ANY, _("Paste (file or text)") + " Ctrl+V"
)
menu.Append(item)
self.Bind(wx.EVT_MENU, self.on_prompt_paste, item)
self.add_standard_context_menu_items(menu, include_paste=False)
self.prompt.PopupMenu(menu)
menu.Destroy()
def on_prompt_key_down(self, event: wx.KeyEvent):
"""Handle keyboard shortcuts for the prompt text control.
Supports:
- Ctrl+Up: Insert previous prompt
- Ctrl+Enter: Submit the current prompt
- Ctrl+V: Paste content from the clipboard
- Ctrl+C: Copy content from the prompt
- Ctrl+X: Cut content from the prompt
- Ctrl+A: Select all content in the prompt
Args:
event: The keyboard event
"""
modifiers = event.GetModifiers()
key_code = event.GetKeyCode()
match (modifiers, key_code):
case (wx.MOD_NONE, wx.WXK_RETURN) | (
wx.MOD_NONE,
wx.WXK_NUMPAD_ENTER,
):
if config.conf().conversation.shift_enter_mode:
self.on_submit(event)
event.StopPropagation()
else:
event.Skip()
case (wx.MOD_CONTROL, wx.WXK_UP):
if not self.prompt.GetValue():
self.insert_previous_prompt()
case (wx.MOD_CONTROL, wx.WXK_RETURN) | (
wx.MOD_CONTROL,
wx.WXK_NUMPAD_ENTER,
):
self.on_submit(event)
case _:
event.Skip()
def on_prompt_paste(self, event):
"""Handle pasting content from the clipboard into the prompt text control.
Supports pasting text and files from the clipboard.
Args:
event: The paste event
"""
self.on_attachments_paste(event)
def insert_previous_prompt(self, event: wx.CommandEvent = None):
"""Insert the last user message from the conversation history into the prompt text control.
This method retrieves the content of the most recent user message from the conversation
and sets it as the current value of the prompt input field. If no messages exist in
the conversation, no action is taken.
Args:
event: The wxPython event that triggered this method. Defaults to None and is not used in the method's logic.
"""
if self.conversation.messages:
last_user_message = self.conversation.messages[-1].request.content
self.prompt.SetValue(last_user_message)
def extract_text_from_message(self, content: str) -> str:
"""Extracts the text content from a message.
Args:
content: The message content to extract text from.
Returns:
The extracted text content of the message.
"""
if isinstance(content, str):
return content
def refresh_messages(self, need_clear: bool = True):
"""Refreshes the messages displayed in the conversation tab.
This method updates the conversation display by optionally clearing existing content and then
re-displaying all messages from the current conversation. It performs the following steps:
- Optionally clears the messages list, message segment manager, and attachment files
- Refreshes the attachments list display
- Iterates through all message blocks in the conversation and displays them
Args:
need_clear: If True, clears existing messages, message segments, and attachments. Defaults to True.
"""
if need_clear:
self.messages.Clear()
self.attachment_files.clear()
self.refresh_attachments_list()
for block in self.conversation.messages:
self.messages.display_new_block(block)
def transcribe_audio_file(self, audio_file: str = None):
"""Transcribe an audio file using the current provider's STT capabilities.
Args:
audio_file: Path to audio file. If None, starts recording. Defaults to None.
"""
if not self.recording_thread:
module = __import__(
"basilisk.recording_thread", fromlist=["RecordingThread"]
)
recording_thread_cls = getattr(module, "RecordingThread")
else:
recording_thread_cls = self.recording_thread.__class__
self.recording_thread = recording_thread_cls(
provider_engine=self.current_engine,
recordings_settings=config.conf().recordings,
conversation_tab=self,
audio_file_path=audio_file,
)
self.recording_thread.start()
def on_transcribe_audio_file(self):
"""Transcribe an audio file using the current provider's STT capabilities."""
cur_provider = self.current_engine
if ProviderCapability.STT not in cur_provider.capabilities:
wx.MessageBox(
_("The selected provider does not support speech-to-text"),
_("Error"),
wx.OK | wx.ICON_ERROR,
)
return
dlg = wx.FileDialog(
self,
# Translators: This is a label for audio file in the main window
message=_("Select an audio file to transcribe"),
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
wildcard=_("Audio files")
+ " (*.mp3;*.mp4;*.mpeg;*.mpga;*.m4a;*.wav;*.webm)|*.mp3;*.mp4;*.mpeg;*.mpga;*.m4a;*.wav;*.webm",
)
if dlg.ShowModal() == wx.ID_OK:
audio_file = dlg.GetPath()
dlg.Destroy()
self.transcribe_audio_file(audio_file)
else:
dlg.Destroy()
def on_recording_started(self):
"""Handle the start of audio recording."""
play_sound("recording_started")
self.SetStatusText(_("Recording..."))
def on_recording_stopped(self):
"""Handle the end of audio recording."""
play_sound("recording_stopped")
self.SetStatusText(_("Recording stopped"))
def on_transcription_started(self):
"""Handle the start of audio transcription."""
play_sound("progress", loop=True)
self.SetStatusText(_("Transcribing..."))
def on_transcription_received(self, transcription):
"""Handle the receipt of a transcription result.
Args:
transcription: The transcription result
"""
stop_sound()
self.SetStatusText(_("Ready"))
self.prompt.AppendText(transcription.text)
if self.prompt.HasFocus() and self.GetTopLevelParent().IsShown():
self._handle_accessible_output(transcription.text)
self.prompt.SetInsertionPointEnd()
self.prompt.SetFocus()