-
Notifications
You must be signed in to change notification settings - Fork 0
/
GUI.py
1397 lines (1284 loc) · 61 KB
/
GUI.py
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
import datetime
import threading
from threading import Thread
import winsound
from PySide6.QtCore import QTimer, QUrl, QCoreApplication
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput, QAudioDevice, QMediaDevices
import AIChatEnum
import event_type
import utils
from AIChatEnum import AIChat, TranslaterAPIType
from AIChatUI import *
from data import ConfigData, ChatBotDataList, ChatBotData, MessageData, UserConfigData, CharacterData, HistoryData
# main window class
class AppGUI(FramelessMainWindow):
"""Main window class"""
_instance = None
stopChat = Signal(str)
Resized = Signal(QSize) # signal emitted when the window is resized
ConfigSaved = Signal(ConfigData) # signal emitted when the config is saved
ChatBotUpdated = Signal(ChatBotData) # signal emitted when the chatbot config is updated
InitFinished = Signal() # signal emitted when the initialization is finished
onChatbotThreadStatusChanged = Signal(str,bool) # signal emitted when the chatbot thread status is changed
def __new__(cls, *args, **kwargs):
"""
The singleton.
:param args:
:param kwargs:
"""
if cls._instance is None:
cls._instance = super(AppGUI, cls).__new__(cls)
return cls._instance
def __init__(self, config_data: ConfigData, chatbots: ChatBotDataList):
super().__init__()
AppGUI._instance = self
# apply qss style sheet
with open('app.qss', 'r') as f:
self.setStyleSheet(f.read())
self.onChatbotThreadStatusChanged.connect(self.on_chatbot_thread_status_changed)
# set up the clipboard
self._clipboard = QApplication.clipboard()
# create a media player to play the audio
self._audio_output = QAudioOutput(QMediaDevices.defaultAudioOutput())
self._audio_output.setVolume(10)
self._media_player = QMediaPlayer()
self._media_player.setAudioOutput(self._audio_output)
self._set_up_ui()
self._chatbot_setting_dialog = ChatBotSettingDialog(config_data.openai_config.get_gpt_params(), self)
self.ConfigSaved.connect(self._chatbot_setting_dialog.update_config)
self._chatbot_setting_dialog.installEventFilter(self)
self._chatbot_setting_dialog.chatbotEdited.connect(self.on_chatbot_update)
self._global_setting_dialog = GlobalSettingDialog(config_data, self)
self._global_setting_dialog.installEventFilter(self)
self._global_setting_dialog.configSaved.connect(self.on_config_saved)
self._current_chatbot: ChatBotData | None = None
self._chatbot_data_list: ChatBotDataList = chatbots
self._config = config_data
self._load_chatbots(self._chatbot_data_list)
# set up ui
def _set_up_ui(self):
"""
set up the ui
"""
# the ui is divided into 3 parts:
# ===================================================================#
# # #
# # #
# # #
# # #
# # message area #
# # #
# # #===========# #
# left bar # # right bar # #
# # #===========# #
# # #
# # #
# #========================================================#
# # button area #
# #========================================================#
# # #
# # input area #
# # #
# ==========#========================================================#
self.setWindowTitle('ChatBot')
self.setMinimumSize(800, 600)
self.resize(950, 860)
# set the window in the center of the screen
self.move((self.screen().size().width() - self.size().width()) / 2,
(self.screen().size().height() - self.size().height()) / 2)
# set up the window widget
self._window_widget = QWidget()
self._window_widget.setObjectName('window_widget')
self.setCentralWidget(self._window_widget)
# create a QVBoxLayout for the window widget
self._window_layout = QSettableVLayout()
self._window_widget.setLayout(self._window_layout)
# set up the title bar
self._title_bar = QTitleBar(self)
self._title_bar.GlobalSettingClicked.connect(lambda: self._global_setting_dialog.show())
self.setTitleBar(self._title_bar)
self._window_layout.addWidget(self._title_bar)
# set up the main content widget
self._main_widget = QWidget()
self._main_widget.setObjectName('main_widget')
self._window_layout.addWidget(self._main_widget)
# set up the main widget's layout
self._main_layout = QSettableHLayout()
self._main_widget.setLayout(self._main_layout)
# create a QVBoxLayout for the left bar
self._left_bar = QWidget()
self._left_bar.setObjectName('left_bar')
self._left_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self._left_bar_layout = QSettableVLayout()
self._left_bar.setLayout(self._left_bar_layout)
# add a chatbot button list
self._chatbot_button_list = []
# add a spacer to the left bar
self._left_bar_spacer = QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
self._left_bar_layout.addItem(self._left_bar_spacer)
# add a QScrollArea to the left bar
self._left_bar_scroll_area = QNoBarScrollArea(self._left_bar)
self._main_layout.addWidget(self._left_bar_scroll_area)
# create a button group for the left bar buttons
self._left_bar_button_group = QButtonGroup()
self._left_bar_button_group.setExclusive(True)
# create a button into the left bar scroll area
self._add_button = QLeftBarAddButton()
self._add_button.setFixedSize(200, 80)
self._add_button.clicked.connect(lambda: self._chatbot_setting_dialog.show_dialogue())
self._left_bar_button_group.addButton(self._add_button, 0)
self._left_bar_layout.insertWidget(0, self._add_button)
# create a QVBoxLayout for the right bar
self._right_bar = QWidget()
self._right_bar.setObjectName('right_bar')
self._right_bar_layout = QVBoxLayout()
self._right_bar_layout.setContentsMargins(0, 0, 0, 0)
self._right_bar_layout.setSpacing(0)
self._right_bar.setLayout(self._right_bar_layout)
self._main_layout.addWidget(self._right_bar)
# create a message area for the right bar
self._message_area = MessageArea()
self._message_area.copyMessage.connect(
lambda: self.hint(AIChatEnum.HintType.Info, 'Message copied.', self._right_bar, 2000))
self._message_area.copyMessage.connect(lambda text: self._clipboard.setText(text))
self._message_area.playAudio.connect(
lambda message_data: self.play_audio(f'./download/sounds/{message_data.message_id}.wav'))
self._message_area.stopPlayAudio.connect(lambda: self._media_player.stop())
self._message_area.resendMessage.connect(self._resend_message)
self._message_area.speakIt.connect(lambda history_id, message_data: QApplication.sendEvent(self, SpeakMessageEvent(history_id, message_data)))
self._media_player.mediaStatusChanged.connect(self._message_area.on_media_status_changed)
self._message_area.installEventFilter(self)
self._right_bar_layout.addWidget(self._message_area)
# create a QScrollArea for the message area
self._message_area_scroll_area = QNoBarScrollArea(self._message_area)
self.ConfigSaved.connect(self._message_area.on_config_updated)
self.ChatBotUpdated.connect(self._message_area.on_chatbot_updated)
self._right_bar_layout.addWidget(self._message_area_scroll_area)
# create a button area for the right bar
self._button_area = QWidget()
self._button_area.setObjectName('button_area')
self._button_area.setContentsMargins(12, 0, 0, 0)
self._button_area.setMaximumHeight(50)
self._button_area.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
self._button_area_layout = QHBoxLayout()
self._button_area.setLayout(self._button_area_layout)
self._right_bar_layout.addWidget(self._button_area)
# crate buttons for the button area
# the send button
self._send_button = QPushButton('SEND')
self._send_button.setFixedSize(60, 30)
self._send_button.clicked.connect(self._send_message)
self._button_area_layout.addWidget(self._send_button)
# the retrieve button
self._retrieve_button = QPushButton('RETRIEVE')
self._retrieve_button.setFixedSize(90, 30)
self._retrieve_button.clicked.connect(self._retrieve_button_clicked)
self._button_area_layout.addWidget(self._retrieve_button)
# create an input area for the right bar
self._input_area = QWidget()
self._input_area.setObjectName('input_area')
self._input_area_layout = QSettableVLayout()
self._input_area.setLayout(self._input_area_layout)
self._right_bar_layout.addWidget(self._input_area)
# create an input box for the input area
self._input_box = QMessagePlainTextEdit(200)
self._input_box.SendMessage.connect(self._send_message)
self._input_area_layout.addWidget(self._input_box)
# create a chatbot running button
self._chatbot_running_button = LoadingAnimationButton(self)
self._chatbot_running_button.clicked.connect(lambda : QApplication.sendEvent(self, StopChatbotThreadEvent(self._current_chatbot.chatbot_id)))
# move it to the button area's center
self.Resized.connect(lambda size: self._chatbot_running_button.move(
int((size.width() - self._chatbot_running_button.width()) / 2 + 100),
int(size.height() - self._input_box.height() - 60)))
self._chatbot_running_button.hide()
def open_global_config_dialog(self, first_time=False):
"""
open the global config dialog
:param first_time: if this is the first time to open the app, that means the global config dialog should be
:return:
"""
if first_time:
self._global_setting_dialog.configSaved.connect(self.InitFinished)
self.InitFinished.connect(lambda: self._global_setting_dialog.configSaved.disconnect(self.InitFinished))
self._global_setting_dialog.first_show()
else:
self._global_setting_dialog.show()
def on_config_saved(self):
"""
the slot for the ConfigSaved signal
:return:
"""
self.ConfigSaved.emit(self._config)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.Config))
@Slot()
def _send_message(self):
"""
the slot for the send button
:return:
"""
if not self._current_chatbot:
self.hint(AIChatEnum.HintType.Warning, 'Please select a chatbot first.', self._right_bar, 2000)
return
if self._input_box.toPlainText().rstrip('\n') == '':
self.hint(AIChatEnum.HintType.Warning, 'Please input something', self._right_bar, 2000)
return
message = MessageData(
**{
'chatbot_id': self._current_chatbot.chatbot_id,
'message': self._input_box.toPlainText().rstrip('\n'),
'send_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'is_user': True,
'name': self._config.user_config.name,
}
)
history_id = self._message_area.current_history_id
self._current_chatbot.append_message(message, history_id)
self._message_area.show_message(self._config.user_config, message)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
QApplication.sendEvent(self, SendMessageEvent(history_id, message))
self._input_box.clear()
def _resend_message(self, history_id):
"""
resend a message.
:param history_id: the history id to resend the message.
:return:
"""
message = self._current_chatbot.histories[history_id][-1]
QApplication.sendEvent(self, SendMessageEvent(history_id, message))
def receive_message(self, history_id, message: MessageData):
"""
receive a message from the chatbot
:param message: the message
:param history_id: the history id
:return:
"""
chatbot = self._chatbot_data_list[message.chatbot_id]
message = chatbot.histories[history_id][-1]
if history_id == self._message_area.current_history_id:
self._message_area.show_message(chatbot.character, message)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
def speak_message(self, history_id, message: MessageData):
"""
speak a message.
:param history_id: the history id
:param message: the message data
:return:
"""
if history_id == self._message_area.current_history_id:
self._message_area.set_play_status(message, True)
self._media_player.setSource(QUrl.fromLocalFile(f'./download/sounds/{message.message_id}.wav'))
self._media_player.play()
def _retrieve_button_clicked(self):
"""
the slot for the reception button
:return:
"""
message = MessageData(
**{
'chatbot_id': self._current_chatbot.chatbot_id,
'message': self._input_box.toPlainText().rstrip('\n'),
'send_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'is_user': False,
'name': self._current_chatbot.character.name,
}
)
chatbot = self._chatbot_data_list[message.chatbot_id]
chatbot.append_message(message, self._message_area.current_history_id)
self.receive_message(self._message_area.current_history_id,message)
def resizeEvent(self, e: QResizeEvent):
"""
the resize event for the main window
:param e: event
:return:
"""
# when the window is resized, emit a signal
self.Resized.emit(e.size())
def eventFilter(self, obj, event):
"""
the event filter for the main window
:param obj: which object the event is sent to
:param event: the event
:return:
"""
if event.type() == event_type.AddChatBotEventType:
self._add_chatbot_button(event.data)
self._chatbot_data_list.append(event.data)
self.set_current_chatbot(event.data)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
QApplication.sendEvent(self, AddChatBotEvent(event.data))
return True
elif event.type() == event_type.MainWindowHintEventType:
self.hint(event.hint_type, event.hint_message, self._right_bar, event.interval)
return True
elif event.type() == event_type.MainWindowCloseEventType:
self.close()
return True
elif event.type() == event_type.DeleteMessageEventType:
chatbot_id = event.data.chatbot_id
if self._chatbot_data_list[event.data.chatbot_id].delete_message(event.history_id, event.data):
self._media_player.stop()
self.stopChat.emit(chatbot_id)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
return super().eventFilter(obj, event)
def event(self, e):
if isinstance(e, MainWindowHintEvent):
self.hint(e.hint_type, e.hint_message, self._right_bar, e.interval)
return True
return super().event(e)
def _add_chatbot_button(self, data: ChatBotData):
"""
add a new chatbot button to the left bar
:param data: the data of the chatbot
:return:
"""
name = data.character.name
chatbot_id = data.chatbot_id
avatar_path = data.character.avatar_path
description = data.character.description
chatbot_button = QChatBotButton(name, id_=chatbot_id, avatar_path=avatar_path, description=description)
chatbot_button.editClicked.connect(self._edit_chatbot_start)
chatbot_button.deleteClicked.connect(self._delete_chatbot)
chatbot_button.checked.connect(self._switch_current_chatbot)
self.ChatBotUpdated.connect(chatbot_button.on_chatbot_update)
chatbot_button.setFixedSize(200, 80)
self._chatbot_button_list.append(chatbot_button)
# chatbot_button.clicked.connect(lambda : self._chatbot_button_clicked(chatbot_button))
self._left_bar_button_group.addButton(chatbot_button, self._left_bar_button_group.buttons().__len__())
self._left_bar_layout.insertWidget(self._left_bar_button_group.buttons().__len__() - 1, chatbot_button)
def on_chatbot_update(self, data: ChatBotData):
"""
the slot for the chatbot update signal
:param data: the data of the chatbot
:return:
"""
self.ChatBotUpdated.emit(data)
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
def on_chatbot_thread_status_changed(self, chatbot_id, status):
"""
the slot for the chatbot thread status changed signal.
:param chatbot_id: the id of the chatbot.
:param status: the status of the chatbot thread, true for running, false for stopped.
:return:
"""
# if not current chatbot, return
if not self.current_chatbot or self.current_chatbot.chatbot_id != chatbot_id:
return
# if the status is running, show the chatbot running button
if status:
self._chatbot_running_button.show()
# if the status is stopped, hide the chatbot running button
else:
self._chatbot_running_button.hide()
def _switch_current_chatbot(self, id_):
"""
the slot for the chatbot button, when a chatbot button is clicked, switch the current chatbot
:param id_: the id of the chatbot
:return:
"""
if self.current_chatbot and self.current_chatbot.chatbot_id == id_:
return
# get the chatbot data
self._media_player.stop()
chatbot = self._chatbot_data_list[id_]
self.set_current_chatbot(chatbot)
def _edit_chatbot_start(self, id_):
"""
start to edit a chatbot
:param id_: the id of the chatbot to be edited
:return:
"""
# get the chatbot data
data = self._chatbot_data_list[id_]
# show the chatbot setting dialog
self._chatbot_setting_dialog.show_dialogue(data, AIChatEnum.AIChat.EditChatBotMode)
def _delete_chatbot(self, id_):
"""
delete a chatbot
:param id_: the id of the chatbot to be deleted
:return:
"""
self._chatbot_data_list.remove(id_)
if self._current_chatbot.chatbot_id == id_:
self._current_chatbot = None
self._message_area.clear_messages()
QApplication.sendEvent(self, SaveDataEvent(AIChatEnum.DataType.ChatBot))
QApplication.sendEvent(self, DeleteChatBotEvent(id_))
def _load_chatbots(self, chatbots_data):
"""
load chatbots from data
:param chatbots_data: the data of chatbots
:return:
"""
if not chatbots_data.data:
return
for chatbot_data in chatbots_data:
self._add_chatbot_button(chatbot_data)
self._chatbot_button_list[0].setChecked(True)
self.set_current_chatbot(self._chatbot_data_list[0])
def set_current_chatbot(self, chatbot):
"""
set the current chatbot.
:param chatbot: the chatbot to be set as current.
:return:
"""
self._current_chatbot = chatbot
self._message_area.load_messages(self._config.user_config, self._current_chatbot,
self._current_chatbot.histories.latest().id_)
def play_audio(self, path):
"""
play an audio file.
:param path: audio file path
:return:
"""
self._media_player.setSource(QUrl.fromLocalFile(path))
self._media_player.play()
@staticmethod
def hint(hint_type, text, obj=None, interval=3000):
"""
show a hint box
:param hint_type: the type of the hint box, see HintBoxType
:param text: text to be displayed
:param obj: widget to add the hint box to
:param interval: after how many milliseconds the hint box will disappear
:return:
"""
if not obj:
obj = AppGUI._instance.default_hint_area
hint_box = HintBox(hint_type, text, obj, interval)
hint_box.show()
@property
def current_chatbot(self):
return self._current_chatbot
@property
def default_hint_area(self):
return self._right_bar
@staticmethod
def get_instance():
if not AppGUI._instance:
AppGUI._instance = AppGUI()
return AppGUI._instance
class MessageArea(QWidget):
"""
the area to display history_list
"""
resendMessage = Signal(str) # history id
copyMessage = Signal(str) # message text
stopPlayAudio = Signal() # stop playing audio
playAudio = Signal(MessageData) # message data
speakIt = Signal(str, MessageData) # message data
def __init__(self):
super().__init__()
self.setObjectName('message_area')
self.setContentsMargins(0, 0, 0, 0)
self._layout = QVBoxLayout()
self._layout.setContentsMargins(15, 15, 15, 15)
self._layout.setSpacing(15)
self._layout.setAlignment(Qt.AlignTop)
self.setLayout(self._layout)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self._message_container_list: list[QMessageContainer] = []
self._current_history_id = None
self._current_play_audio = None
self._greeting_message_container = None
def addWidget(self, widget):
"""
add a widget to the message area's layout
:param widget: the widget to be added
:return:
"""
self._layout.addWidget(widget)
def load_messages(self, user_config: UserConfigData, chatbot_data: ChatBotData, history_id):
"""
load history_list from database
:param user_config: the user config data
:param chatbot_data: chatbot data
:param history_id: the id of the history or an index of the history
:return:
"""
# clear the message area
self.clear_messages()
if chatbot_data.character.greeting:
# load greeting message
self.show_message(chatbot_data.character, MessageData(**{
'message': chatbot_data.character.greeting,
'is_user': False,
'chatbot_id': chatbot_data.chatbot_id,
'message_id': 'greeting',
'send_time': utils.get_current_time(),
'name': chatbot_data.character.name,
}), settable=False)
# load history_list
self._current_history_id = history_id
history = chatbot_data.histories[history_id]
for message in history:
if message.is_user:
self.show_message(user_config, message)
else:
self.show_message(chatbot_data.character, message)
def show_message(self, sender_data: UserConfigData | CharacterData, message_data: MessageData, resendable=True, settable=True):
"""
show a message in the message area
:param resendable: if the message is resendable
:param sender_data: the sender of the data. It can be a user or a character.
:param message_data: message data
:return:
"""
max_width = self.parent().parent().parent().parent().parent().parent().width() - 230
# create a message container
message_container = QMessageContainer(sender_data, message_data, max_width, settable)
if settable:
message_container.startPlay.connect(self.start_play)
message_container.stopPlay.connect(self._stop_play)
message_container.resendClicked.connect(self.resend_message)
message_container.copyClicked.connect(lambda: self.copyMessage.emit(message_data.message))
message_container.deleteClicked.connect(self.delete_message)
self._message_container_list.append(message_container)
else:
self._greeting_message_container = message_container
# if not resendable, disable the resend button
if not resendable:
message_container.set_resendable(False)
# if the message list is more than 2, set the resend button disabled except the latest 2 history_list
if len(self._message_container_list) > 2:
self._message_container_list[-3].set_resendable(False)
# add the message container to the layout to show it
self.addWidget(message_container)
# when the window is resized, the max width of the message container should be changed
self.parent().parent().parent().parent().parent().parent().Resized.connect(message_container.mainWindowResized)
def resend_message(self, message_data: MessageData):
"""
resend a message
:param message_data: the message to be resent
:return:
"""
# delete all the history_list after the message to be resent
for message_container in self._message_container_list:
if message_container.message_data > message_data:
self.delete_message(message_container.message_data)
if not message_data.is_user:
self.delete_message(message_data)
self.resendMessage.emit(self._current_history_id)
def delete_message(self, message_data: MessageData):
"""
delete a message
:param message_data: the message to be deleted
:return:
"""
# delete the message container
for message_container in self._message_container_list:
if message_container.message_data == message_data:
self._message_container_list.remove(message_container)
message_container.deleteLater()
QApplication.sendEvent(self, DeleteMessageEvent(self._current_history_id, message_data))
# set the latest 2 message container's resend button enabled
if len(self._message_container_list) >= 2:
self._message_container_list[-2].set_resendable(True)
self._message_container_list[-1].set_resendable(True)
def clear_messages(self):
"""
clear all history_list
:return:
"""
if self._greeting_message_container:
self._greeting_message_container.deleteLater()
self._greeting_message_container = None
for message_container in self._message_container_list:
message_container.deleteLater()
self._current_play_audio = None
self._message_container_list.clear()
def set_play_status(self, message_data, is_playing):
"""
set the message container's play status.
:param message_data: message data
:return:
"""
if self._current_play_audio and self._current_play_audio != message_data:
current_play_message_container = self.get_message_container(self._current_play_audio)
if current_play_message_container:
current_play_message_container.set_play_status(False)
self._current_play_audio = message_data
message_container = self.get_message_container(message_data)
message_container.set_play_status(is_playing)
def start_play(self, message):
"""
start playing the audio.
:param message: message data which contains the audio.
:return:
"""
has_file = utils.has_file(f'./download/sounds/{message.message_id}.wav')
if self._current_play_audio and has_file:
current_play_message_container = self.get_message_container(self._current_play_audio)
if current_play_message_container:
current_play_message_container.set_play_status(False)
self._current_play_audio = message
# if there is not the message file, send speakIt event to the main window
if not has_file:
self.speakIt.emit(self._current_history_id, message)
self.get_message_container(message).set_play_status(False)
QApplication.sendEvent(self, MainWindowHintEvent(AIChatEnum.HintType.Info, 'The audio file is not downloaded yet. Please wait.'))
return
self._current_play_audio = message
self.playAudio.emit(message)
def _stop_play(self, message_data: MessageData):
"""
stop playing the audio
:param message_data: the message data
:return:
"""
if self._current_play_audio and self._current_play_audio.message_id == message_data.message_id:
self._current_play_audio = None
self.stopPlayAudio.emit()
def on_media_status_changed(self, status):
"""
when the media status is changed, update the message area
:param status: QMediaPlayer.MediaStatus
:return:
"""
if status == QMediaPlayer.EndOfMedia:
if self._current_play_audio:
current_play_message_container = self.get_message_container(self._current_play_audio)
if current_play_message_container:
current_play_message_container.set_play_status(False)
self._current_play_audio = None
def on_config_updated(self, data: ConfigData):
"""
when the config is updated, update the message area
:param data: config data or chatbot data
:return:
"""
for message_container in self._message_container_list:
if message_container.is_user:
message_container.set_avatar(data.user_config.avatar_path)
message_container.set_name(data.user_config.name)
def on_chatbot_updated(self, data: ChatBotData):
"""
when the chatbot is updated, update the message area
:param data: chatbot data
:return:
"""
if not data:
return
# if the chatbot is not the current chatbot, do nothing
if not data.has_history(self._current_history_id):
return
if self._greeting_message_container:
self._greeting_message_container.set_avatar(data.character.avatar_path)
self._greeting_message_container.set_name(data.character.name)
for message_container in self._message_container_list:
if not message_container.is_user:
message_container.set_avatar(data.character.avatar_path)
message_container.set_name(data.character.name)
def get_message_container(self, message_data: MessageData):
"""
get the message container by message data.
:param message_data: message data.
:return: message container.
"""
for message_container in self._message_container_list:
if message_container.message_data == message_data:
return message_container
return None
@property
def current_history_id(self):
return self._current_history_id
class ChatBotSettingDialog(QInWindowDialog):
"""
This is a dialog for chatbot setting
:param parent: the parent widget
:param save_mode: if this dialog is used to add a new chatbot
"""
chatbotEdited = Signal(ChatBotData)
def __init__(self, gpt_params_config, parent=None, save_mode=AIChat.AddNewChatBotMode):
super().__init__(parent)
self._gpt_params_config = gpt_params_config
self._setting_stage = AIChat.BasicSettingStage
self._save_mode = save_mode
self._chatbot = None
self.setting_area_layout.setContentsMargins(0, 15, 0, 0)
self.setting_area_layout.setAlignment(Qt.AlignTop)
self.setting_area_layout.setSpacing(0)
# add a setting button to the title bar
self._setting_button = QTitleBarSettingButton(30, 30, 2.5, 3.4)
self._setting_button.setObjectName('setting_button')
self._setting_button.setFixedSize(30, 30)
# in the first row, there is an avatar label
self._avatar_label = QAvatarLabel('./resources/images/test_avatar_me.jpg', 220, editable=True)
self._image = './resources/images/test_avatar_me.jpg'
# if avatar clicked, open a file dialog to select a new avatar
self._avatar_label.clicked.connect(self._update_avatar)
self.setting_area_layout.addWidget(self._avatar_label, alignment=Qt.AlignCenter)
# if setting button is clicked, change the setting stage and show the corresponding setting group
self._setting_button.clicked.connect(self._change_setting_stage)
self.title_bar_layout.insertWidget(1, self._setting_button)
# add a basic setting group to the setting area
self._basic_setting_group = QWidget()
self._basic_setting_group.setObjectName('basic_setting_group')
self._basic_setting_group.setContentsMargins(15, 15, 15, 15)
self._basic_setting_group_layout = QSettableVLayout(content_margin=(15, 15, 15, 15), spacing=15)
self._basic_setting_group.setLayout(self._basic_setting_group_layout)
self.setting_area_layout.addWidget(self._basic_setting_group)
# in the second row, there is a label and a name input box in a container
self._name_input_box = QLabelInput('Name: ')
self._basic_setting_group_layout.addWidget(self._name_input_box)
# in the third row, there is a personality input box
self._personality_input_box = QLabelInput('Personality: ')
self._basic_setting_group_layout.addWidget(self._personality_input_box)
# in the fourth row, there is a description input box
self._description_input_box = QLabelInput('Description: ')
self._basic_setting_group_layout.addWidget(self._description_input_box)
# in the fifth row, there is a greeting input box
self._greeting_input_box = QLabelInput('Greeting: ')
self._basic_setting_group_layout.addWidget(self._greeting_input_box)
# in the sixth row, there is a prompts plain text edit
self._prompts_plain_text_edit = QPlainTextEdit()
self._prompts_plain_text_edit.setObjectName('prompts_plain_text_edit')
self._prompts_plain_text_edit.setPlaceholderText('Please input the prompts here, one prompt per line')
self._basic_setting_group_layout.addWidget(self._prompts_plain_text_edit)
# add an advanced setting group to the setting area, but hide it
self._advanced_setting_group = QWidget()
self._advanced_setting_group.setObjectName('advanced_setting_group')
self._advanced_setting_group.setContentsMargins(15, 15, 15, 15)
self._advanced_setting_group_layout = QSettableVLayout(content_margin=(15, 15, 15, 15), spacing=15)
self._advanced_setting_group.setLayout(self._advanced_setting_group_layout)
self.setting_area_layout.addWidget(self._advanced_setting_group)
self._advanced_setting_group.hide()
# in the first row, there is a label and a combobox in a container
self._model_combobox = QLabelComboBox('Model: ', ['gpt-3.5-turbo', 'gpt-4'])
self._advanced_setting_group_layout.addWidget(self._model_combobox)
# in the second row, there is a label, a horizontal slider and an input box in a container
self._temperature_input_box = QLabelSliderInput('Temperature: ', (0, 20))
self._advanced_setting_group_layout.addWidget(self._temperature_input_box)
# in the third row, there is a label, a horizontal slider and an input box in a container
self._top_p_input_box = QLabelSliderInput('Top P: ', (0, 10))
self._advanced_setting_group_layout.addWidget(self._top_p_input_box)
# in the fourth row, there is a label, a horizontal slider and an input box in a container
self._frequency_penalty_input_box = QLabelSliderInput('Frequency: ', (-20, 20))
self._advanced_setting_group_layout.addWidget(self._frequency_penalty_input_box)
# in the fifth row, there is a label, a horizontal slider and an input box in a container
self._presence_penalty_input_box = QLabelSliderInput('Presence: ', (-20, 20))
self._advanced_setting_group_layout.addWidget(self._presence_penalty_input_box)
# in the sixth row, there is a label, a horizontal slider and an input box in a container
self._max_tokens_input_box = QLabelSliderInput('Max Tokens: ', (0, 2048), False)
self._advanced_setting_group_layout.addWidget(self._max_tokens_input_box)
# add a button box to the setting area
self._button_box = QWidget()
self._button_box.setObjectName('button_box')
self._button_box.setFixedHeight(60)
self._button_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self._button_box_layout = QSettableHLayout(content_margin=(15, 0, 15, 15), spacing=15, alignment=Qt.AlignCenter)
self._button_box.setLayout(self._button_box_layout)
self.setting_area_layout.addWidget(self._button_box, alignment=Qt.AlignBottom)
# add two buttons into the button box
self._cancel_button = QPushButton('Cancel')
self._cancel_button.setObjectName('cancel_button')
self._cancel_button.setFixedSize(100, 30)
self._cancel_button.clicked.connect(self._cancel_setting)
self._button_box_layout.addWidget(self._cancel_button)
self._save_button = QPushButton('Save')
self._save_button.setObjectName('save_button')
self._save_button.setFixedSize(100, 30)
self._save_button.clicked.connect(self._save_setting)
self._button_box_layout.addWidget(self._save_button)
def show_dialogue(self, data=None, mode=AIChat.AddNewChatBotMode):
"""
Show the dialog.
:param data: the data of the chat
:param mode: the mode of the dialog
:return:
"""
self._save_mode = mode
if mode == AIChat.AddNewChatBotMode:
self._clear_setting()
self._load_gpt_params(self._gpt_params_config)
elif mode == AIChat.EditChatBotMode:
if isinstance(data, ChatBotData):
self._chatbot = data
self._load_chatbot_data(data)
super().show()
def _change_setting_stage(self):
"""
Change the setting stage. When the setting stage is changed, change the setting content.
:return:
"""
if self._setting_stage == AIChat.BasicSettingStage:
self._setting_stage = AIChat.AdvancedSettingStage
self._basic_setting_group.hide()
self._advanced_setting_group.show()
self.set_title('')
else:
self._setting_stage = AIChat.BasicSettingStage
self._basic_setting_group.show()
self._advanced_setting_group.hide()
self.set_title('')
def _cancel_setting(self):
"""
Close the dialog. When the cancel button is clicked, this function will be called.
:return:
"""
self.close()
def _save_setting(self):
"""
save the setting and close the dialog.
:return:
"""
if self._name_input_box.input_content == '':
QApplication.sendEvent(self, MainWindowHintEvent(AIChatEnum.HintType.Warning,
'Please input the name of the chat bot'))
return
if self._prompts_plain_text_edit.toPlainText() == '':
QApplication.sendEvent(self, MainWindowHintEvent(AIChatEnum.HintType.Warning,
'Please input the prompts of the chat bot'))
return
self.close()
if self._save_mode == AIChat.AddNewChatBotMode:
chatbot_data = ChatBotData(**self.input_data)
QApplication.sendEvent(self, AddChatBotEvent(chatbot_data))
elif self._save_mode == AIChat.EditChatBotMode:
self._chatbot.update(self.input_data)
self.chatbotEdited.emit(self._chatbot)
self._chatbot = None
self._clear_setting()
def update_config(self, config: ConfigData):
"""
This function will be called when the config is saved.
:param config:
:return:
"""
self._gpt_params_config = config.openai_config.get_gpt_params()
def _change_save_model(self, model):
"""
Change the save model.
:return:
"""
self._save_mode = model
def _load_gpt_params(self, gpt_params: GPTParamsData):
"""
This function will load the gpt params from the config.
:return:
"""
self._model_combobox.setCurrentText(gpt_params.model)
self._temperature_input_box.set_value(gpt_params.temperature)
self._top_p_input_box.set_value(gpt_params.top_p)
self._frequency_penalty_input_box.set_value(gpt_params.frequency_penalty)
self._presence_penalty_input_box.set_value(gpt_params.presence_penalty)
self._max_tokens_input_box.set_value(gpt_params.max_tokens)
def _clear_setting(self):
"""
Clear the setting.
:return:
"""
self._name_input_box.input_content = ''
self._avatar_label.set_image('./resources/images/test_avatar_me.jpg')
self._personality_input_box.input_content = ''
self._description_input_box.input_content = ''
self._greeting_input_box.input_content = ''
self._prompts_plain_text_edit.setPlainText('')
def _load_chatbot_data(self, data: ChatBotData):
"""
This function will load the chatbot data.
:param data: the chatbot data
:return:
"""
character = data.character
self._name_input_box.input_content = character.name
self._avatar_label.set_image(character.avatar_path)
self._personality_input_box.input_content = character.personality
self._description_input_box.input_content = character.description
self._greeting_input_box.input_content = character.greeting
self._prompts_plain_text_edit.setPlainText(character.prompt)
self._load_gpt_params(data.gpt_params)
@property
def input_data(self):
result = {
'gpt_params': {
'model': self._model_combobox.currentText,
'temperature': self._temperature_input_box.value,
'top_p': self._top_p_input_box.value,
'frequency_penalty': self._frequency_penalty_input_box.value,
'presence_penalty': self._presence_penalty_input_box.value,
'max_tokens': self._max_tokens_input_box.value
},
'character': {
'name': self._name_input_box.input_content,
'avatar_path': self._avatar_label.avatar_path,
'personality': self._personality_input_box.input_content,
'description': self._description_input_box.input_content,
'greeting': self._greeting_input_box.input_content,
'prompt': self._prompts_plain_text_edit.toPlainText()
}
}
if self._save_mode == AIChat.AddNewChatBotMode:
result['histories'] = [{'memory': {}, 'history_list': []}]
return result
@property
def avatar_label(self):
return self._avatar_label
@avatar_label.setter
def avatar_label(self, avatar):
self._image = avatar
self._avatar_label.set_image(avatar)
def _update_avatar(self):
image_path = \
QFileDialog.getOpenFileName(self, 'Open Image', './resources/images', 'Image Files (*.png *.jpg *.bmp)')[0]
if image_path:
self.avatar_label = image_path
class GlobalSettingDialog(QInWindowDialog):
configSaved = Signal() # signal for config saved