-
Notifications
You must be signed in to change notification settings - Fork 61
/
main.py
1271 lines (1102 loc) · 48 KB
/
main.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
# coding=utf-8
import json
import hashlib
from datetime import datetime
import os
import time
import openai
import flet as ft
import re
import shutil
from flet import (
ElevatedButton,
FilePicker,
FilePickerResultEvent,
Page,
Row,
Text,
icons,
)
from prompt_engineering import *
import codecs
# 赋值固定的api_key
# 测试用
openai.api_key = None
openai.api_key = read_APIKEY()
'''
每一行对话的类
在调用的同时,会将数据存入聊天记录文件
'''
class chat_row(ft.UserControl):
def __init__(self, role, content):
super(chat_row, self).__init__()
self.role = role
self.content = content
self.hash = save_now_chat(
chat_json_path=chat_json_path,
role=self.role,
content=self.content)
def build(self):
self.role_dropdown = ft.Dropdown(
value=self.role,
width=150,
options=[
ft.dropdown.Option("system"),
ft.dropdown.Option("user"),
ft.dropdown.Option("assistant"),
],
on_change=self.role_change
)
self.content_textfield = ft.TextField(
label="消息内容",
value=self.content,
filled=True,
expand=True,
multiline=True,
on_change=self.content_change
)
self.generalize_btn = ft.ElevatedButton(
'概括本消息',
on_click=self.sum_change
)
self.sum_field = ft.TextField (
visible=False,
label="概括内容",
value='概括中',
filled=True,
expand=True,
multiline=True,
# on_change=self.content_change
)
self.one_chat_row = ft.Row (
[
self.role_dropdown,
self.content_textfield,
self.generalize_btn,
self.sum_field,
]
)
return self.one_chat_row
def sum_change(self,e):
self.generalize_btn.disabled = True
self.update()
self.one_chat_row.controls.append(self.sum_field)
self.update()
self.summary = chatGPT_sum(self.content)
renew_now_chat (
chat_json_path=chat_json_path,
hash_val=self.hash,
summary=self.summary )
self.sum_field.visible = True
self.sum_field.value = self.summary
self.generalize_btn.disabled = False
self.update ()
return self.one_chat_row
def role_change(self, e):
self.role = self.role_dropdown.value
renew_now_chat(
chat_json_path=chat_json_path,
hash_val=self.hash,
role=self.role)
def content_change(self, e):
self.content = self.content_textfield.value
renew_now_chat(
chat_json_path=chat_json_path,
hash_val=self.hash,
content=self.content)
'''
调用chatGPT获取关键词和概括的函数
'''
# 文本切块成
def split_text(text, divide_length):
return [text[i:i+divide_length] for i in range(0, len(text), divide_length)]
# 获取概括文本
def chatGPT_sum_old(content):
divided_content = split_text(content,divide_length=1000)
chain_summary = []
for single_content in divided_content:
composition_analysis_message = [{"role" : "user",
"content" : f'''为以下文本创建概括:
{content}
概括内容:'''}]
chatGPT_raw_response = openai.ChatCompletion.create (
model="gpt-3.5-turbo",
messages=composition_analysis_message
)
summary = decode_chr ( chatGPT_raw_response.choices[0].message['content'].strip () )
chain_summary.append(summary)
print(summary)
chain_summary_long = '\n'.join ( chain_summary )
return chain_summary_long
def chatGPT_sum(content,chain_type='map_reduce'):
try:
# 试图用langchain但无法打包
import langchain
from langchain.llms import OpenAI
from langchain.chains.summarize import load_summarize_chain
from langchain.chains import AnalyzeDocumentChain
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import UnstructuredFileLoader
from langchain.docstore.document import Document
from langchain.prompts import PromptTemplate
'''
准备步骤
'''
# 创建文本分块器,每块长度为1000
text_splitter = RecursiveCharacterTextSplitter ( chunk_size=1000, chunk_overlap=0 )
# 创建大语言模型,将温度拉到最低以提高精确性
llm = OpenAI ( temperature=0, openai_api_key=openai.api_key )
'''
加载需要概括的内容
'''
# 加载外部文件
# loader = UnstructuredFileLoader ( 'game_log_conversation.txt' )
# docs = loader.load ()
# split_docs = text_splitter.split_documents(docs)
# 加载函数输入的字符串
split_content = text_splitter.split_text ( content )
split_docs = [Document ( page_content=t ) for t in split_content]
'''
总结文本
'''
# 创建prompt模板
prompt_template = """为以下文本创建概括:
{text}
概括内容:"""
PROMPT = PromptTemplate ( template=prompt_template, input_variables=["text"] )
# 创建总结链,模式为map_reduce
# 第一种
# 有模板的总结链
summary_chain = load_summarize_chain ( llm, chain_type="map_reduce", return_intermediate_steps=True,
map_prompt=PROMPT, combine_prompt=PROMPT ,verbose=True)
# 带参数带模板总结
chain_summary = summary_chain (
{"input_documents" : split_docs},
# return_only_outputs=True,
)
# 第二种
# 无模板的总结链
# summary_chain = load_summarize_chain ( llm, chain_type=chain_type, verbose=True )
# 直接总结
# chain_summary = summary_chain.run ( split_docs )
chain_summary_long = '\n'.join(chain_summary['intermediate_steps'])
return chain_summary_long
except Exception as error:
print(error)
return chatGPT_sum_old(content)
# 获取关键词(还是用jieba吧)
def chatGPT_getkeyword(content):
chatGPT_raw_response = openai.Completion.create (
model="text-ada-001",
prompt=f"你要总结这一文本的关键词,并以python列表的形式返回数个关键词字符串:{content}。",
temperature=0
)
keyword = decode_chr ( chatGPT_raw_response.choices[0]['text'].strip () )
print(keyword)
return keyword
# 获取关键词(还是用jieba吧)
def chatGPT_getsummary(content):
chatGPT_raw_response = openai.Completion.create (
model="text-ada-001",
prompt=f"你要在10字以内概括这段文本:{content}。",
temperature=0
)
keyword = decode_chr ( chatGPT_raw_response.choices[0]['text'].strip () )
print(keyword)
return keyword
'''
读写chatlog的相关函数
'''
# 创建chat数据记录的方法,将聊天数据结构基于 JSON 文件进行存储
def create_chat_json(save_path='./chatlog'):
# 如果保存目录不存在,则创建目录
if not os.path.exists(save_path):
os.makedirs(save_path)
# 获取当前时间并格式化为文件名格式
now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
chat_json_name = f"chat_{now}.json"
# 如果文件不存在,则创建文件
chat_json_path = os.path.join(save_path, chat_json_name)
if not os.path.exists(chat_json_path):
with open(chat_json_path, 'w') as f:
json.dump([], f, default=str)
return chat_json_path
# 储存现有的每一句聊天信息
def save_now_chat(chat_json_path: str, role: str, content: str) -> str:
'''
将每一段聊天信息储存到一个 JSON 文件中。以哈希值作为唯一标识符
:param chat_json_path: 聊天文件的路径
:param role: 发言者
:param content: 发言内容
:return hash_val: 哈希值
'''
now = datetime.now().timestamp()
str_to_hash = str(now) + role + content
hash_obj = hashlib.blake2b(str_to_hash.encode('utf-8'), digest_size=8)
hash_val = hash_obj.hexdigest()
# 读取之前的内容
try:
with open(chat_json_path, 'r') as f:
chats = json.load(f)
except FileNotFoundError:
chats = []
# 添加新的聊天信息
message = {
'role': role,
'content': content,
'keyword': [],
'summary': ''
}
chats.append({
'chat_seq': len(chats) + 1,
'hash': hash_val,
'created_time': now,
'altered_time': None,
'message': message
})
# 将新的聊天信息写入文件
with open(chat_json_path, 'w') as f:
json.dump(chats, f, default=str,indent=4)
return hash_val
# 根据聊天信息的哈希值,更新现有历史聊天列表
def renew_now_chat(chat_json_path: str, hash_val: str,
role: str = None, content: str = None , summary=None) -> None:
'''
根据聊天信息的哈希值,更新现有历史聊天列表
:param chat_json_path: 聊天文件的路径
:param hash_val: 聊天信息的哈希值
:param role: 更新后的发言者(可选)
:param content: 更新后的发言内容(可选)
:return: None
'''
# 读取chat_renew_data.json文件
with open(chat_json_path, 'r') as f:
data = json.load(f)
# 找出哈希值相同的键值对,并更新它们的role和content
for chat_item in data:
if hash_val == chat_item['hash']:
if role:
chat_item['message']['role'] = role
if content:
chat_item['message']['content'] = content
if summary :
chat_item['message']['summary'] = summary
chat_item["altered_time"] = datetime.now().timestamp()
break
# 将更新后的数据写回文件
with open(chat_json_path, 'w') as f:
json.dump(data, f, default=str,indent=4)
# 根据聊天信息的哈希值,获取单个键值对内的role和content
def get_one_role_and_content(
chat_json_path: str, hash_value: str) -> (str, str):
'''
根据聊天信息的哈希值,获取单个键值对内的role和content
:param chat_json_path: 聊天文件的路径
:param hash_value: 聊天信息的哈希值
:return: (发言者, 发言内容)
'''
with open(chat_json_path) as f:
data = json.load(f)
for chat_item in data:
for message in chat_item['message']:
if hash_value == hashlib.blake2b(
str(message["created_time"] +
message["role"] +
message["content"]).encode('utf-8'),
digest_size=8).hexdigest():
return message["role"], message["content"]
return None
# 读取特定文件内的所有role和content
def get_combined_data(chat_json_path: str) -> list[dict[str, str]]:
'''
获取特定文件内的所有role和content
:param chat_json_path: JSON 聊天文件的路径
:return: 包含所有发言者和发言内容(若有概括则返回概括)的列表
'''
with open(chat_json_path) as f:
data = json.load(f)
result = []
for chat_item in data:
if chat_item['message']['summary'] != '':
result.append({
"role": chat_item['message']["role"],
"content": chat_item['message']["summary"]
})
else:
result.append({
"role": chat_item['message']["role"],
"content": chat_item['message']["content"]
})
return result
# 概括chatlog
def summarize_chatlog(chatlog_json_path) :
with open ( chatlog_json_path, 'r' ) as f :
chatlog = json.load ( f )
for message in chatlog :
if 'summary' not in message or not message['summary'] :
content = message['message']['content'] # assuming content is always the second item in the message list
if len ( content ) > 100 :
summary = chatGPT_sum ( content )
message['summary'] = summary
with open ( chatlog_json_path, 'w' ) as f :
json.dump ( chatlog, f ,indent=4)
# 概括chatlog
def summarize_chatlog(chatlog_json_path) :
with open ( chatlog_json_path, 'r' ) as f :
chatlog = json.load ( f )
for message in chatlog :
if 'summary' not in message or not message['summary'] :
content = message['message']['content'] # assuming content is always the second item in the message list
if len ( content ) > 100 :
summary = chatGPT_sum ( content )
message['summary'] = summary
with open ( chatlog_json_path, 'w' ) as f :
json.dump ( chatlog, f ,indent=4)
# 获取chatlog关键词
def get_chatlog_keyword(chatlog_json_path) :
with open ( chatlog_json_path, 'r' ) as f :
chatlog = json.load ( f )
for message in chatlog :
if 'keyword' not in message or not message['keyword'] :
content = message['message']['content'] # assuming content is always the second item in the message list
keywords = chatGPT_getkeyword ( content )
message['keyword'] = keywords
with open ( chatlog_json_path, 'w' ) as f :
json.dump ( chatlog, f,indent=4 )
# 创建chat数据记录
chat_json_path = create_chat_json()
'''
加工message方法,先对向chatGPT发送的请求进行处理
'''
def process_message() :
pass
def cut_message(message) :
'''
剪切接收到的message,如果超过4000token长度就从最早的消息开始剪切,剪切到小于4000token为止
:param message:
:return:
'''
total_length = 0
# Iterate over contents in the list
for message_dict in message :
# message_dict['content'] = message_dict['content']
# 计算content长度
if message_dict['content'].isalpha () :
length = len ( message_dict['content'].split () )
else :
length = len ( message_dict['content'] )
total_length += length
while total_length > 4000:
if not message:raise Exception('最后一条消息长度大于4000字符了,请编辑消息或重置对话')
removed_content = message.pop(0)
removed_length = len ( removed_content['content'] )
if removed_content['content'].isalpha () :
removed_length = len ( removed_content['content'].split () )
total_length -= removed_length
return message
'''
读写API-KEY的函数
'''
# 定义 write_APIKEY 函数
def write_APIKEY(APIKEY=None):
# 以追加模式打开或创建 APIKEY.txt 文件
with open("APIKEY.txt", "a") as f:
# 写入字符串并换行
if APIKEY:
f.write(APIKEY.strip() + "\n")
# 定义 read_APIKEY 函数
def read_APIKEY():
# 以读取模式打开 APIKEY.txt 文件
with open("APIKEY.txt", "r") as f:
# 读取所有行并存入列表
lines = f.readlines()
# 如果列表不为空,返回最后一行的值,去掉换行符
if lines:
return lines[-1].strip()
'''
读写settings.txt的函数
'''
# 读取settings.txt文件的设置项值,并返回一个字典
def read_settings():
"""
读取settings.txt文件,如果该文件不存在,则创建一个空白的文件
然后读取所有行,每行格式为:设置项名称 = 设置项的具体值
将每行拆分为键值对,添加到字典中,并返回该字典
:return: 包含settings.txt内的所有行的键值对形式的字典
"""
settings_dict = {}
try:
with open('settings.txt', 'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
if line:
key, value = line.split('=', maxsplit=1)
settings_dict[key.strip()] = value.strip()
except FileNotFoundError:
with open('settings.txt', 'w', encoding='utf-8') as file:
pass # 如果文件不存在,则创建一个空白的txt文件,不需要做任何操作
return settings_dict
# 将字典中的多个键值对写入/修改settings.txt文件的设置项值
def write_settings(settings):
"""
将多个键值对写入/更新settings.txt文件
如果文件不存在则创建一个空的文件
:param settings: 包含键值对的字典
"""
with open('settings.txt', 'r+') as f:
lines = f.readlines()
f.seek(0)
for key, value in settings.items():
for i, line in enumerate(lines):
if key in line:
lines[i] = key + ' = ' + value + '\n'
break
else:
f.write(key + ' = ' + value + '\n')
f.writelines(lines)
'''
读写字体文件的函数(适用于windows)
'''
def replace_font_file(path):
old_path = os.path.join(".", "asset", "font.ttf")
try:
os.remove(old_path)
except OSError:
pass
try:
shutil.copy(path, 'assets/font.ttf')
except FileNotFoundError:
with open('assets/font.ttf','a'):
pass
shutil.copy(path, 'assets/font.ttf')
print("替换成功!")
'''
其他函数
'''
# 字符转码
def decode_chr(s):
s = s.replace('\\\\','\\')
pattern = re.compile(r'(\\u[0-9a-fA-F]{4}|\n)')
result = ''
pos = 0
while True:
match = pattern.search(s, pos)
if match is None:
break
result += s[pos:match.start()]
if match.group() == '\n':
result += '\n'
else:
result += chr(int(match.group()[2:], 16))
pos = match.end()
result += s[pos:]
return result
def convert_content_to_unicode(txt_path):
# 读取txt文件,转换为Python列表
with open(txt_path, 'r', encoding='utf-8') as f:
txt_data = f.read()
data = json.loads(txt_data)
# 转换content内容为Unicode编码
for item in data:
content = item["message"]["content"]
item["message"]["content"] = content.encode('unicode_escape').decode()
# item["message"]["content"] = item["message"]["content"].replace('\\u',r'\u')
# 将Python列表转换为json格式字符串
json_data = json.dumps(data, ensure_ascii=False)
# 保存json文件到cache文件夹
if not os.path.exists("./cache"):
os.makedirs("./cache") # 创建cache文件夹
json_path = f"./cache/{os.path.basename(txt_path)[:-4]}.json"
with open(json_path, 'w', encoding='utf-8') as f:
f.write(json_data)
return json_path
# markdown检测
def markdown_check(gpt_msg):
pass
'''
程序主窗体
'''
def ft_interface(page: ft.Page):
# 设置字体与主题
page.title = 'BillyGPT'
page.fonts = {'A75方正像素12': './assets/font.ttf'}
page.theme = ft.Theme(font_family='A75方正像素12')
page.dark_theme = page.theme
# 设置主页面聊天区域的滚动列表
chat_area = ft.ListView(
expand=True,
spacing=10,
auto_scroll=True,
padding=20)
'''
添加选择上传文件、保存文件、打开文件夹按钮
'''
# 导入聊天记录
def import_chatlog(e: FilePickerResultEvent):
try:
clear_page()
selected_file = (
", ".join(map(lambda f: f.path, e.files)
) if e.files else "Cancelled!"
)
if selected_file[-4:] == 'json':
full_chatlog = get_combined_data(selected_file)
print(full_chatlog)
for chat_row_content in full_chatlog:
role = chat_row_content['role']
content = chat_row_content['content']
chat_area.controls.append(chat_row(role, content))
page.update()
elif selected_file[-4:] == '.txt':
json_path = convert_content_to_unicode(selected_file)
full_chatlog = get_combined_data(json_path)
for chat_row_content in full_chatlog:
role = decode_chr(chat_row_content['role'])
content = decode_chr(chat_row_content['content'])
chat_area.controls.append(chat_row(role, content))
page.update()
except Exception as e:
chat_area.controls.append(
Text(f'出现如下报错\n{e}\n请检查导入的聊天记录是否正确,或联系开发者微信B1lli_official'))
page.update()
import_chatlog_dialog = FilePicker(on_result=import_chatlog)
# 导出聊天记录
def save_file_result(e: FilePickerResultEvent):
save_file_path.value = e.path if e.path else "Cancelled!"
if save_file_path.value != "Cancelled!":
shutil.copy(chat_json_path, save_file_path.value)
path = save_file_path.value
with open ( path, 'r', encoding='utf-8' ) as f :
content = f.read ()
processed_content = decode_chr ( content )
with open ( path, 'w', encoding='utf-8' ) as f :
f.write ( processed_content )
save_file_dialog = FilePicker(on_result=save_file_result)
save_file_path = Text()
# 打开文件夹(还没做)
def get_directory_result(e: FilePickerResultEvent):
directory_path.value = e.path if e.path else "Cancelled!"
directory_path.update()
get_directory_dialog = FilePicker(on_result=get_directory_result)
directory_path = Text()
# 隐藏所有
page.overlay.extend(
[import_chatlog_dialog, save_file_dialog, get_directory_dialog])
'''
添加改变字体按钮
并调用改变字体方法
'''
def change_font_clicked(e: FilePickerResultEvent):
selected_file = (
", ".join ( map ( lambda f : f.path, e.files )
) if e.files else "Cancelled!"
)
replace_font_file(selected_file)
'''
添加设置对话和按钮
'''
def save_settings(e):
settings_dlg.open = False
write_APIKEY(apikey_field.value)
openai.api_key = read_APIKEY()
page.update()
def cancel_settings(e):
settings_dlg.open = False
page.update()
change_font_dialog = FilePicker(on_result=change_font_clicked)
page.overlay.extend([change_font_dialog])
apikey_field = ft.TextField(hint_text='在此输入apikey',)
my_wechat = ft.Text('如有任何bug请联系我:B1lli_official',size=15)
github_page_btn = ft.ElevatedButton(
'打开本项目的GitHub页面',
tooltip='如果你给这个项目点了star,你就是忠实用户了,请打开本页面后进入项目群!',
on_click=lambda _:page.launch_url('https://github.com/createrX12/BillyGPT')
)
change_font_btn = ft.ElevatedButton(
'选择新的字体文件',
on_click=lambda _:change_font_dialog.pick_files(
allowed_extensions=['ttf'],
allow_multiple=False,
dialog_title='选择字体文件导入',
)
)
settings_dlg = ft.AlertDialog(
title=ft.Text("Settings"),
content=ft.Column(
[apikey_field,my_wechat,github_page_btn,change_font_btn],
height=200,
),
actions=[
ft.TextButton("保存", on_click=save_settings),
ft.TextButton("取消", on_click=cancel_settings)
],
actions_alignment=ft.MainAxisAlignment.END,
shape=ft.RoundedRectangleBorder(radius=10)
)
def open_dlg_modal(e):
page.dialog = settings_dlg
settings_dlg.open = True
page.update()
settings_btn = ft.IconButton(
icon=ft.icons.SETTINGS_OUTLINED,
icon_color="#9ecaff",
bgcolor='#202429',
icon_size=20,
tooltip="Settings",
on_click=open_dlg_modal,
)
'''
添加启动应用程序获取apikey窗口
'''
def save_settings_open(e):
write_APIKEY(apikey_field_open.value)
openai.api_key = read_APIKEY()
open_setting_apikey_dlg.open = False
page.update()
get_apikey_btn = ft.ElevatedButton(
'从openAI获取apikey',
on_click=lambda _:page.launch_url('https://platform.openai.com/account/api-keys')
)
write_APIKEY()
openai.api_key = read_APIKEY()
if not openai.api_key:
apikey_field_open = ft.TextField(label="输入你的apikey")
open_setting_apikey_dlg = ft.AlertDialog(
open=True,
modal=True,
title=ft.Text("欢迎使用BillyGPT"),
content=ft.Column(
[apikey_field_open,get_apikey_btn],
tight=True),
actions=[
ft.ElevatedButton(
text="开始使用",
on_click=save_settings_open)],
actions_alignment="end",
)
page.dialog = open_setting_apikey_dlg
openai.api_key = read_APIKEY()
'''
添加聊天行
'''
def add_msg(e):
chatPO_btn.disabled = True
chat_area.controls.append(chat_row('user', chat_text.value))
chat_text.value = ""
page.update()
chat_area.controls.append(
chat_row(
'assistant', chatGPT()))
page.update()
def add_msg_composition(e):
chatPO_btn.disabled = True
chat_area.controls.append(chat_row('user', chat_text.value))
chat_area.controls.append(
chat_row(
'assistant',
chatGPT_PO(
chat_text.value)))
page.update()
'''
添加ctrl+enter发送消息方法
'''
def on_keyboard(e: ft.KeyboardEvent) :
if e.ctrl:
if e.key == 'Enter':
add_msg(e)
page.on_keyboard_event = on_keyboard
'''
添加模板选择功能
可以读取模板文件,实时搜索,选择时可以切换身份
'''
class DropdownSearchBar(ft.UserControl):
def __init__(self):
super(DropdownSearchBar, self).__init__()
self.item_number = ft.Text(size=9,italic=True)
def dropdown_search(self):
_object_ = ft.Container(
width=450,
height=50,
bgcolor="white10",
border_radius=6,
padding=ft.padding.only(top=15),
clip_behavior=ft.ClipBehavior.HARD_EDGE,
animate=ft.animation.Animation(400,"decelerate"),
content=ft.Column(
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
alignment=ft.MainAxisAlignment.START,
controls=[
Row(
spacing=10,
vertical_alignment=ft.CrossAxisAlignment.CENTER,
controls=[
ft.Icon(
ft.icons.SEARCH_ROUNDED,
size=15,
opacity=0.90,
),
ft.TextField(
border_color='transparent',
height=20,
text_size=12,
content_padding=2,
cursor_color='black',
cursor_width=1,
hint_text='搜索模板',
on_change=None
),
self.item_number,
],
),
ft.Column(
scroll='auto',
expand=True
)
]
)
)
return _object_
def build(self):
return ft.Container()
page.add(DropdownSearchBar())
# def template_change(self, e):
# template_name = template_dropbox.value
# renew_now_chat(
# chat_json_path=chat_json_path,
# hash_val=self.hash,
# role=self.role)
#
#
# template_dropbox = ft.Dropdown(
# value=role,
# width=150,
# options=[
# ft.dropdown.Option("system"),
# ft.dropdown.Option("user"),
# ft.dropdown.Option("assistant"),
# ],
# on_change=template_change
# )
'''
设置布局 添加控件
'''
# 模板选择下拉框
page.add(
Row(
[
ElevatedButton (
"清空聊天日志",
icon=icons.CLEANING_SERVICES,
on_click=lambda _ : clear_page(),
),
ElevatedButton(
"导入聊天日志",
icon=icons.FILE_DOWNLOAD_OUTLINED,
on_click=lambda _: import_chatlog_dialog.pick_files(
allowed_extensions=['json','txt'],
allow_multiple=False,
dialog_title='选择聊天记录文件导入',
initial_directory='./chatlog'
),
),
ElevatedButton(
"导出聊天日志",
icon=icons.FILE_UPLOAD_OUTLINED,
on_click=lambda _: save_file_dialog.save_file(
file_name=f"chat_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.txt",
# file_type=ft.FilePickerFileType.CUSTOM
),
disabled=page.web,
),
settings_btn
],
alignment=ft.MainAxisAlignment.END,
),
)
page.add(chat_area)
chat_text = ft.TextField(
hint_text="想和chatGPT说些什么?",
filled=True,
expand=True,
multiline=True)
chat_btn = ft.ElevatedButton("对话", on_click=add_msg, tooltip='随便聊聊')
chatPO_btn = ft.ElevatedButton(
"思维链优化对话",
on_click=add_msg_composition,
tooltip='认真提问\n仅在对话开始时可用'
)
view = ft.Column(
controls=[
ft.Row(
controls=[
chat_text,
chat_btn,
chatPO_btn
]
),
],
)
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
page.add(view)
'''
添加清空页面方法
'''
def clear_page():
global chat_json_path