-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtts4.2.7.7.Console.py
8591 lines (7031 loc) · 411 KB
/
tts4.2.7.7.Console.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 json
import qianfan
import os
import re
import sys
import shutil
import time
import glob
import threading
import pyperclip
# import base64
# import hashlib
# import hmac
# import ssl
# import websocket
import tkinter as tk
# import _thread as thread
from tkinter import filedialog, ttk, messagebox, scrolledtext
from tkinter.ttk import Progressbar, Notebook
from tkinter.scrolledtext import ScrolledText
from gradio_client import Client, handle_file
from datetime import datetime
from PIL import Image, ImageTk
from pydub import AudioSegment
from openai import OpenAI, RateLimitError
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QPushButton, QLabel, QListWidget, QComboBox, QDialog)
from PyQt5.QtCore import QThread, pyqtSignal, Qt, QEvent
# from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
# from sparkai.core.messages import ChatMessage
# from urllib.parse import urlparse, urlencode
# from wsgiref.handlers import format_date_time
client = None
# 创建全局锁
api_lock = threading.Lock()
api_lock_baidu = threading.Lock()
api_lock_kimi = threading.Lock()
api_lock_ali = threading.Lock()
def acquire_lock(lock):
def decorator(func):
def wrapper(*args, **kwargs):
if not lock.acquire(blocking=False): # 尝试非阻塞式获取锁
raise Exception("当前API被占用")
try:
result = func(*args, **kwargs) # 执行函数
finally:
lock.release() # 确保在函数结束时释放锁
return result
return wrapper
return decorator
def check_using_api(func):
def wrapper(*args, **kwargs):
# 尝试获取锁,非阻塞式获取
if not api_lock.acquire(blocking=False):
messagebox.showwarning("API被其他操作占用",
"有其他操作占用API期间部分功能不可用")
return
try:
result = func(*args, **kwargs) # 执行函数
finally:
api_lock.release() # 确保在函数结束时释放锁
return result
return wrapper
class StartMenu:
def __init__(self, root, text_preprocessor):
self.root = root
# 初始化 API 密钥属性
self.config = {} # 用于存储所有配置项
self.projects = {} # 用于存储项目数据
self.text_preprocessor = text_preprocessor
self.chat_window = None # 用来存储 ChatGUI 窗口实例
# 创建 path_frame 容纳左、右两列
path_frame = tk.Frame(self.root)
path_frame.pack(fill=tk.X, padx=10, pady=10)
# 左侧列
left_frame = tk.Frame(path_frame)
left_frame.grid(row=0, column=0, padx=(10, 5), sticky='nsw')
tk.Label(left_frame, text="选择项目:").grid(row=0, column=0, sticky='w', pady=5)
# 选择项目行
self.select_project_frame = tk.Frame(left_frame)
self.select_project_frame.grid(row=1, column=0, sticky='ew')
# 使用 Combobox 替换项目名文本框
self.project_name_combobox = ttk.Combobox(self.select_project_frame, width=28)
self.project_name_combobox.grid(row=0, column=0, sticky='ew', pady=5)
self.project_name_combobox.bind("<<ComboboxSelected>>", self.load_selected_project) # 绑定选择事件
# 删除项目按钮
self.delete_project_button = tk.Button(self.select_project_frame, text="删除", command=self.delete_project)
self.delete_project_button.grid(row=0, column=1, padx=(5, 0))
# 设置按钮
tk.Label(left_frame, text="配置AI:").grid(row=2, column=0, sticky='w', pady=(4, 5))
self.settings_button = tk.Button(left_frame, text="设置", command=self.open_settings_window)
self.settings_button.grid(row=3, column=0, sticky='we')
# 右侧列
right_frame = tk.Frame(path_frame)
right_frame.grid(row=0, column=1, padx=(15, 5), sticky='nsew')
# 确保右侧列的 Entry 随窗口变化
path_frame.grid_columnconfigure(1, weight=1)
tk.Label(right_frame, text="工作文件夹路径:").grid(row=0, column=0, sticky='w', pady=5)
self.folder_path_var = tk.StringVar()
self.folder_path_entry = tk.Entry(right_frame, textvariable=self.folder_path_var)
self.folder_path_entry.grid(row=1, column=0, sticky='ew', pady=5)
self.select_folder_button = tk.Button(right_frame, text="浏览...", command=self.select_folder)
self.select_folder_button.grid(row=1, column=1, sticky='w', padx=5)
tk.Label(right_frame, text="小说原文路径:").grid(row=2, column=0, sticky='w', pady=5)
self.text_file_path_var = tk.StringVar()
self.text_file_path_entry = tk.Entry(right_frame, textvariable=self.text_file_path_var)
self.text_file_path_entry.grid(row=3, column=0, sticky='ew', pady=5)
self.select_text_file_button = tk.Button(right_frame, text="浏览...", command=self.select_text_file)
self.select_text_file_button.grid(row=3, column=1, sticky='w', padx=5)
# 确保右侧列的按钮也随窗口变化
right_frame.grid_columnconfigure(0, weight=1)
# 测试按钮行
self.test_button_frame = tk.Frame(path_frame)
self.test_button_frame.grid(row=1, column=0, sticky='ew')
# 新建 ChatGUI 按钮
self.open_chat_button = tk.Button(self.test_button_frame, text="测试大模型", command=self.open_chat_window,
width=16)
self.open_chat_button.grid(row=0, column=0, padx=(10, 9), pady=(20, 5), sticky='we')
# 占位
self.blank_frame = tk.Frame(self.test_button_frame, width=6)
self.blank_frame.grid(row=0, column=1)
# 新建 GPT-SoVITS 按钮
self.open_GPT_SoVITS_Button = tk.Button(self.test_button_frame, text="测试GPT-SoVITS",
command=self.toggle_example_window, width=16)
self.open_GPT_SoVITS_Button.grid(row=0, column=2, padx=5, pady=(20, 5), sticky='we')
# 创建项目按钮
self.create_project_button = tk.Button(path_frame, text="创建项目/进入项目", command=self.create_project)
self.create_project_button.grid(row=1, column=1, padx=(15, 10), pady=(20, 5), sticky='ew')
# 添加一个按钮来刷新选项卡2的内容
# self.refresh_button = tk.Button(path_frame, text="刷新选项卡2内容", command=self.refresh_tab2)
# self.refresh_button.grid(row=2, columnspan=2, padx=5, pady=10, sticky='ew')
# 创建可滚动画布
self.create_scrollable_canvas()
# 初始化配置
self.load_config() # Load existing keys if available
self.populate_project_names() # Populate project names in Combobox
# print(self.config)
# 实例化 ExampleWindow 并保存其引用
self.example_window = GPTSoVITSWindow(self.root)
# self.run_connect_to_gradio_start()
def save_config(self):
"""将配置保存回 config.json"""
with open("config.json", "w", encoding="utf-8") as f:
json.dump({"config": self.config, "projects": self.projects}, f, ensure_ascii=False, indent=4)
def delete_project(self):
"""删除选择的项目"""
selected_project = self.project_name_combobox.get() # 获取下拉框选择的项目名称
if selected_project:
# 检查项目是否存在于 projects 字典中
if selected_project in self.projects:
# 删除项目
del self.projects[selected_project]
# 保存更新后的配置
self.save_config()
# 更新下拉框中的项目列表
self.populate_project_names()
print(f"项目 '{selected_project}' 已删除.")
else:
print(f"未找到项目 '{selected_project}'.")
def toggle_example_window(self):
# 控制 ExampleWindow 窗口的显示与隐藏
if self.example_window.window.winfo_ismapped(): # 如果窗口已显示,则隐藏
self.example_window.hide_window()
else: # 如果窗口未显示,则显示
self.example_window.show_window()
def open_chat_window(self):
"""点击按钮时打开 ChatGUI 窗口"""
if not self.chat_window:
self.chat_window = ChatGUI() # 如果窗口还没创建,创建一个新的实例
self.chat_window.show() # 显示窗口
def load_config(self):
"""从 config.json 加载配置"""
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
self.config = config_data.get("config", {}) # Load keys from config
self.projects = config_data.get("projects", {}) # Load projects
else:
# 如果 config.json 不存在,则初始化配置
self.config = {}
self.projects = {}
def populate_project_names(self):
project_names = []
# 检查 config.json 是否存在
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
# 从 config_data 中提取项目名
if "projects" in config_data:
project_names = list(config_data["projects"].keys())
# 添加“新建项目”选项
project_names.append("新建项目")
# 更新 Combobox 的选项
self.project_name_combobox['values'] = project_names
# 检查 config.json 是否存在
if not os.path.exists("config.json"):
# 如果 config.json 不存在,默认选择“新建项目”
self.project_name_combobox.current(project_names.index("新建项目"))
else:
# 只有在项目名称不为空时,选择最新创建的项目
if project_names and len(project_names) > 1: # 确保有项目可供选择
# 筛选出有效项目(不包括“新建项目”)
valid_projects = [name for name in project_names if name != "新建项目"]
if valid_projects: # 确保有效项目列表不为空
latest_project = max(valid_projects, key=lambda name: self.projects[name]['created_time'])
self.project_name_combobox.current(self.project_name_combobox['values'].index(latest_project))
# 填充最新项目的配置到控件
self.fill_project_config(latest_project)
project_name = self.project_name_combobox.get()
folder_path = self.folder_path_var.get()
text_file_path = self.text_file_path_var.get()
created_time = self.projects[latest_project]['created_time']
# 将项目数据保存到 projects 字典中
self.projects[project_name] = {
"folder_path": folder_path,
"text_file_path": text_file_path,
"created_time": created_time
}
# 更新画布中的项目详细信息
self.update_project_details_in_canvas(project_name)
def get_text_file_stats(self, file_path):
"""获取文本文档的字符数和行数"""
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
char_count = len(content)
line_count = content.count('\n') + 1 # 计算行数
return char_count, line_count
return 0, 0
def fill_project_config(self, project_name):
"""填充选定项目的配置到控件"""
if project_name in self.projects:
project_data = self.projects[project_name]
self.folder_path_var.set(project_data['folder_path'])
self.text_file_path_var.set(project_data['text_file_path'])
else:
# 清空文件夹路径和文本文档路径
self.folder_path_var.set("")
self.text_file_path_var.set("")
def load_selected_project(self, event):
"""加载选定的项目到输入框"""
selected_project = self.project_name_combobox.get()
if selected_project != "新建项目":
project_data = self.projects[selected_project]
self.folder_path_var.set(project_data['folder_path'])
self.text_file_path_var.set(project_data['text_file_path'])
# 显示项目的创建时间、字符数和行数
created_time = project_data['created_time']
char_count, line_count = self.get_text_file_stats(project_data['text_file_path'])
details = (
f"项目名: {selected_project}\n"
f"创建时间/修改时间: {created_time}\n"
f"字符数: {char_count}\n"
f"行数: {line_count}"
)
self.project_details_label.config(text=details)
self.update_project_details_in_canvas(selected_project)
self.refresh_tab2()
else:
# 清空文件夹路径和文本文档路径
self.folder_path_var.set("")
self.text_file_path_var.set("")
self.project_details_label.config(text="")
def refresh_tab2_content(self):
"""刷新选项卡2的内容"""
self.text_preprocessor.update_content()
def select_folder(self):
folder_path = filedialog.askdirectory()
if folder_path:
self.folder_path_var.set(folder_path)
def select_text_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
if file_path:
self.text_file_path_var.set(file_path)
def open_settings_window(self):
# 创建设置窗口
self.settings_window = tk.Toplevel(self.root)
self.settings_window.title("设置")
self.settings_window.geometry("820x480") # 调整窗口大小,确保能容纳所有控件
self.settings_window.minsize(820, 485)
# 上方框架
top_frame = tk.Frame(self.settings_window)
top_frame.pack(side="top", fill=tk.BOTH, expand=True)
# 左侧框架
left_frame = tk.Frame(top_frame)
left_frame.pack(side="left", fill="both", expand=True)
# 右侧框架
right_frame = tk.Frame(top_frame)
right_frame.pack(side="right", fill="both", expand=True)
# 右上方框架
button_frame = tk.Frame(right_frame)
button_frame.pack(side="top", fill="x")
# 创建按钮来添加新的文本框
self.canvas_frame = tk.Frame(right_frame)
self.canvas_frame.pack(side="bottom", fill="both", expand=True)
# 创建一个框架来放置URL输入框和连接按钮
url_frame = tk.Frame(left_frame)
url_frame.pack(side="top", fill="both")
# 创建另一个框架放置服务的选项卡
services_frame = tk.Frame(left_frame)
services_frame.pack(side="bottom", fill="both", expand=True)
# 在url_frame上方新建一个Notebook控件
notebook_url = ttk.Notebook(url_frame)
notebook_url.pack(padx=10, pady=10, fill="both")
# 创建“GPT-SoVITS”标签页
gpt_sovits_tab = tk.Frame(notebook_url)
notebook_url.add(gpt_sovits_tab, text="GPT-SoVITS")
# 在“GPT-SoVITS”标签页中放置现有的URL输入框和连接按钮
tk.Label(gpt_sovits_tab, text="Gradio URL:").pack(anchor='w', padx=10, pady=5)
self.gradio_url_var = tk.StringVar(value="http://localhost:9872/")
self.gradio_url_entry = tk.Entry(gpt_sovits_tab, textvariable=self.gradio_url_var, width=30)
self.gradio_url_entry.pack(side='left', padx=10, fill="x", expand=True)
# 连接按钮
connect_button = tk.Button(gpt_sovits_tab, text="连接", command=self.connect_gradio)
connect_button.pack(side='left', padx=(0, 10), pady=(0, 5))
# 创建“更多”标签页
more_tab = tk.Frame(notebook_url)
notebook_url.add(more_tab, text="更多")
# 在“更多”标签页中显示“暂不支持”
label_more = tk.Label(more_tab, text="暂不支持", font=("font", 16))
label_more.pack(padx=10, pady=10)
self.charactor_label = tk.Label(button_frame, text="角色管理器设置:")
self.charactor_label.pack(side='left', padx=10)
# 新建一个按钮来添加文本框
self.add_textbox_button = tk.Button(button_frame, text="添加预设路径", command=self.add_textbox)
self.add_textbox_button.pack(side='left', padx=(5, 0))
# 创建Canvas和滚动条
self.canvas_window = tk.Canvas(self.canvas_frame, height=100, highlightthickness=0)
self.scrollbar = tk.Scrollbar(self.canvas_frame, orient="vertical", command=self.canvas_window.yview)
self.canvas_window.config(yscrollcommand=self.scrollbar.set)
# 将Canvas放入滚动窗口
self.scrollable_frame_window = tk.Frame(self.canvas_window)
self.canvas_window.create_window((0, 0), window=self.scrollable_frame_window, anchor="nw")
self.scrollable_frame_window.columnconfigure(0, weight=1) # 使第0列可扩展
self.scrollable_frame_window.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
self.scrollable_frame_window.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
self.scrollable_frame_window.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
self.scrollbar.pack(side="right", fill="y")
self.canvas_window.pack(side="left", fill="both", expand=True)
# 让Canvas能够自动调整大小
self.scrollable_frame_window.bind(
"<Configure>",
lambda e: self.canvas_window.config(scrollregion=self.canvas_window.bbox("all"))
)
self.textbox_counter = 0 # 用于计数创建的文本框数量
# 创建服务的选项卡
services = ["百度", "KIMI", "阿里", "讯飞", "腾讯", "自定义", "更多"]
self.tab_frames = {}
self.entries = {} # 存储每个选项卡的entry,以便保存时读取
self.model_vars = {} # 存储每个服务的模型选择
# 新建一个Notebook控件来放置服务选项卡
notebook_services = ttk.Notebook(services_frame)
notebook_services.pack(padx=10, pady=10, expand=True, fill="both")
for service in services:
tab_frame = tk.Frame(notebook_services)
notebook_services.add(tab_frame, text=service)
self.tab_frames[service] = tab_frame
if service == "KIMI":
tk.Label(tab_frame, text=f"{service} API_KEY:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(tab_frame, width=30)
secret_key_entry.pack(anchor='w', padx=10, fill="both")
elif service == "阿里":
tk.Label(tab_frame, text=f"{service} API_KEY:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(tab_frame, width=30)
secret_key_entry.pack(anchor='w', padx=10, fill="both")
elif service == "讯飞":
tk.Label(tab_frame, text=f"{service} APPID:").pack(anchor='w', padx=10, pady=5)
access_key_entry = tk.Entry(tab_frame, width=30)
access_key_entry.pack(anchor='w', padx=10, fill="both")
tk.Label(tab_frame, text=f"{service} APISecret:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(tab_frame, width=30)
secret_key_entry.pack(anchor='w', padx=10, fill="both")
tk.Label(tab_frame, text=f"{service} APIKey:").pack(anchor='w', padx=10, pady=5)
api_key_entry = tk.Entry(tab_frame, width=30)
api_key_entry.pack(anchor='w', padx=10, fill="both")
# 特别处理:将 api_key_entry 也加入到 self.entries[service] 中
self.entries[service] = {
"access_key": access_key_entry,
"secret_key": secret_key_entry,
"api_key": api_key_entry, # 存储 API_KEY
}
# 清空 tab_frame 中已有的控件
for widget in tab_frame.winfo_children():
widget.pack_forget() # 或者 widget.destroy()
tk.Label(tab_frame, text="暂不支持", font=("font", 16)).pack(padx=10, pady=10)
elif service == "腾讯":
# 清空 tab_frame 中已有的控件
for widget in tab_frame.winfo_children():
widget.pack_forget() # 或者 widget.destroy()
tk.Label(tab_frame, text="暂不支持", font=("font", 16)).pack(padx=10, pady=10)
elif service == "自定义":
choose_custom_config_frame = tk.Frame(tab_frame)
choose_custom_config_frame.pack(anchor='w', fill="x")
tk.Label(choose_custom_config_frame, text="自定义预设").pack(anchor='w', padx=10, pady=5)
self.custom_config_var = tk.StringVar()
custom_config = ttk.Combobox(choose_custom_config_frame, textvariable=self.custom_config_var)
custom_config.pack(side='left', padx=10, fill="x", expand=True)
custom_config.bind("<<ComboboxSelected>>", lambda event: self.load_selected_preset(custom_config))
create_custom_config = tk.Button(choose_custom_config_frame, text="创建",
command=self.create_custom_preset)
create_custom_config.pack(side='left', padx=(0, 5))
self.custom_config_combobox = custom_config
delete_custom_config = tk.Button(choose_custom_config_frame, text="删除",
command=lambda: self.delete_custom_preset(custom_config))
delete_custom_config.pack(side='left', padx=(5, 10))
tk.Label(tab_frame, text=f"{service} base_url:").pack(anchor='w', padx=10, pady=(0, 5))
access_key_entry = tk.Entry(tab_frame, width=30)
access_key_entry.pack(anchor='w', padx=10, fill="both")
tk.Label(tab_frame, text=f"{service} API_KEY:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(tab_frame, width=30)
secret_key_entry.pack(anchor='w', padx=10, fill="both")
# 导入配置时,填充“自定义”选项卡的下拉栏
self.load_custom_presets(custom_config)
elif service == "更多":
label_more2 = tk.Label(tab_frame, text="请按“文本预处理”\n选项卡内具体要求使用", font=("font", 16))
label_more2.pack(padx=10, pady=10)
else:
tk.Label(tab_frame, text=f"{service} ACCESS_KEY:").pack(anchor='w', padx=10, pady=5)
access_key_entry = tk.Entry(tab_frame, width=30)
access_key_entry.pack(anchor='w', padx=10, fill="both")
tk.Label(tab_frame, text=f"{service} SECRET_KEY:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(tab_frame, width=30)
secret_key_entry.pack(anchor='w', padx=10, fill="both")
if service != "讯飞":
self.entries[service] = {"access_key": access_key_entry, "secret_key": secret_key_entry}
if service != "更多":
# 添加模型选择下拉框
model_var = tk.StringVar(value="待定")
self.model_vars[service] = model_var
model_options = ["待定"]
if service == "百度":
model_options = [
"ERNIE-4.0-Turbo-128K",
"ERNIE-4.0-Turbo-8K-Latest",
"ERNIE-4.0-Turbo-8K-Preview",
"ERNIE-4.0-Turbo-8K",
"ERNIE-4.0-8K-Latest",
"ERNIE-4.0-8K-Preview",
"ERNIE-4.0-8K",
"ERNIE-3.5-128K",
"ERNIE-3.5-8K-Preview",
"ERNIE-3.5-8K",
"ERNIE-Speed-Pro-128K",
"ERNIE-Speed-128K",
"ERNIE-Speed-8K",
"ERNIE-Lite-Pro-128K",
"ERNIE-Lite-8K-0308",
"ERNIE-Tiny-8K",
"ERNIE-Character-8K",
"ERNIE-Character-Fiction-8K",
"ERNIE-Novel-8K",
"Qianfan-Chinese-Llama-2-70B",
"Llama-2-70b-chat"
]
model_var.set("ERNIE-4.0-Turbo-128K") # 默认选中百度的第一个模型选项
if service == "KIMI":
model_options = [
"moonshot-v1-8k",
"moonshot-v1-32k",
"moonshot-v1-128k",
"moonshot-v1-auto"
]
model_var.set("moonshot-v1-128k")
if service == "阿里":
model_options = [
"qwen-long",
"qwen-turbo",
"qwen-plus",
"qwen-max"
]
model_var.set("qwen-long")
if service == "讯飞":
model_options = [
"lite",
"generalv3",
"generalv3.5",
"pro-128k",
"max-32k",
"4.0Ultra",
]
model_var.set("pro-128k")
choose_model_label = tk.Label(tab_frame, text="选择模型")
choose_model_label.pack(anchor='w', padx=10, pady=5)
model_combobox = ttk.Combobox(tab_frame, textvariable=model_var, values=model_options, width=27)
model_combobox.pack(anchor='w', padx=10, fill="both")
# 在“更多”选项卡中,隐藏模型选择下拉框
if service == "更多":
model_combobox.pack_forget() # 隐藏模型选择下拉框
choose_model_label.pack_forget()
# 从 config.json 读取配置并填充控件
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
# 设置每个服务的 ACCESS_KEY、SECRET_KEY 和模型选择
for service in services:
if service != "更多":
try:
access_key = config_data.get("config", {}).get(service, {}).get("ACCESS_KEY", "")
secret_key = config_data.get("config", {}).get(service, {}).get("SECRET_KEY", "")
model_choice = config_data.get("config", {}).get(service, {}).get("MODEL", "待定")
# 特别处理“讯飞”选项卡,获取 API_KEY
if service == "讯飞":
api_key = config_data.get("config", {}).get(service, {}).get("API_KEY", "")
# 填充讯飞的 API_KEY
self.entries[service]["api_key"].delete(0, tk.END)
self.entries[service]["api_key"].insert(0, api_key)
# 填充每个服务的控件
self.entries[service]["access_key"].delete(0, tk.END)
self.entries[service]["access_key"].insert(0, access_key)
self.entries[service]["secret_key"].delete(0, tk.END)
self.entries[service]["secret_key"].insert(0, secret_key)
self.model_vars[service].set(model_choice)
except Exception as e:
continue
# 读取 character_folder 并在滚动画布中创建文本框
character_folder_content = config_data.get("config", {}).get("character_folder", [])
for content in character_folder_content:
# 增加文本框计数器
self.textbox_counter += 1
# 创建一个 Frame 用于容纳该行的控件
row_frame = tk.Frame(self.scrollable_frame_window)
row_frame.grid_columnconfigure(1, weight=1)
row_frame.grid_columnconfigure(2, weight=0) # 使第1列不扩展
row_frame.grid_columnconfigure(3, weight=0) # 使第2列不扩展
row_frame.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
row_frame.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
row_frame.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
# 创建文本框并填充初始内容
new_textbox = tk.Entry(row_frame, width=30)
new_textbox.insert(0, content)
new_textbox.grid(row=0, column=0, pady=5, padx=10, sticky="ew")
# 为该文本框创建“浏览...”按钮
def browse_folder(textbox=new_textbox): # 使用默认参数来绑定当前文本框
folder_path = filedialog.askdirectory() # 打开选择文件夹对话框
if folder_path: # 如果选择了路径,则填充到文本框
textbox.delete(0, tk.END)
textbox.insert(0, folder_path)
# 创建“浏览...”按钮并放置在文本框的右侧
browse_button = tk.Button(row_frame, text="浏览...", command=browse_folder)
browse_button.grid(row=0, column=1, pady=5, padx=(0, 10), sticky="w")
# 为每个文本框和浏览按钮创建删除按钮
def delete_row(frame=row_frame):
# 删除当前行的所有控件
frame.destroy()
# 创建“删除”按钮并放置在浏览按钮的右侧
delete_button = tk.Button(row_frame, text="删除", command=delete_row)
delete_button.grid(row=0, column=2, pady=5, padx=(0, 10), sticky="w")
# 将这一行的所有控件(文本框、浏览按钮、删除按钮)添加到框架中
row_frame.grid(row=self.textbox_counter, column=0, pady=5, padx=10, sticky="ew")
for widget in row_frame.winfo_children():
widget.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
widget.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
widget.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
else:
print("配置文件 config.json 不存在,使用默认配置")
# 保存按钮
save_button = tk.Button(self.settings_window, text="保存", command=self.save_keys_and_close_window)
save_button.pack(anchor='w', padx=10, pady=10, fill="both")
self.canvas_window.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
self.canvas_window.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
self.canvas_window.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
self.load_selected_preset(custom_config)
def delete_custom_preset(self, custom_config):
"""删除自定义预设"""
selected_preset = self.custom_config_var.get()
# 确保选中一个预设
if selected_preset:
# 读取现有的 config.json 文件
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
existing_data = json.load(f)
# 检查是否存在自定义预设配置
if "自定义" in existing_data["config"]:
custom_presets = existing_data["config"]["自定义"]
# 如果选中的预设存在于自定义预设中,则删除
if selected_preset in custom_presets:
del custom_presets[selected_preset]
# 更新自定义预设
existing_data["config"]["自定义"] = custom_presets
# 如果删除的是当前选中的预设,清空选择
if self.custom_config_var.get() == selected_preset:
self.custom_config_var.set("") # 清空选择
# 写入更新后的配置文件
with open("config.json", "w", encoding="utf-8") as f:
json.dump(existing_data, f, ensure_ascii=False, indent=4)
# 从下拉栏中移除已删除的预设
self.load_custom_presets(custom_config)
print(f"预设 '{selected_preset}' 已被删除")
else:
print(f"未找到预设 '{selected_preset}'")
else:
print("没有自定义预设可删除")
else:
print("配置文件不存在")
else:
print("没有选中任何预设")
def load_custom_presets(self, custom_config):
"""读取并填充所有自定义预设名称到下拉栏"""
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
data = json.load(f)
if "自定义" in data["config"]:
custom_presets = data["config"]["自定义"]
# 排除“已选择”项并获取所有预设名称
preset_names = [name for name in custom_presets.keys()]
# 将自定义预设的名称填充到下拉栏
custom_config['values'] = preset_names + ["新建配置"]
# 默认选中“自定义已选择”项对应的预设
selected_preset = data["config"].get("自定义已选择") # 获取“自定义已选择”项
if selected_preset and selected_preset in preset_names:
# 如果“自定义已选择”项存在且在预设名称中,设置为默认选中项
self.custom_config_var.set(selected_preset)
elif preset_names:
# 如果没有“自定义已选择”项,默认选中第一个预设
self.custom_config_var.set(preset_names[0])
def load_selected_preset(self, custom_config):
"""根据选择的自定义预设填充相关配置"""
selected_preset = custom_config.get() # 获取选中的自定义预设名称
if not selected_preset:
return # 如果没有选择预设,则不进行填充
# 如果选中了“新建配置”,直接清空控件内容
if selected_preset == "新建配置":
# 假设控件的名称是 "access_key", "secret_key", "model" 等
self.entries["自定义"]["access_key"].delete(0, tk.END)
self.entries["自定义"]["secret_key"].delete(0, tk.END)
self.model_vars["自定义"].set("") # 清空模型选择
return
# 获取配置文件中的自定义预设项
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
data = json.load(f)
if "自定义" in data["config"]:
custom_presets = data["config"]["自定义"]
if selected_preset in custom_presets:
preset_config = custom_presets[selected_preset]
# 填充到相应的控件
if "ACCESS_KEY" in preset_config:
self.entries["自定义"]["access_key"].delete(0, tk.END)
self.entries["自定义"]["access_key"].insert(0, preset_config["ACCESS_KEY"])
if "SECRET_KEY" in preset_config:
self.entries["自定义"]["secret_key"].delete(0, tk.END)
self.entries["自定义"]["secret_key"].insert(0, preset_config["SECRET_KEY"])
if "MODEL" in preset_config:
self.model_vars["自定义"].set(preset_config["MODEL"]) # 选择模型
# 如果有其他控件需要填充,可以继续添加
def create_custom_preset(self):
# 获取“自定义预设”下拉框的内容(即用户输入的名称)
custom_preset_name = self.tab_frames["自定义"].winfo_children()[0].winfo_children()[1].get()
custom_config_combobox = self.custom_config_combobox
# 如果名称为空,则不执行操作
if not custom_preset_name:
messagebox.showwarning("警告","请输入预设名称!")
return
if custom_preset_name == "新建配置":
messagebox.showwarning("警告","请修改预设名称!")
return
# 获取用户填写的其他信息
# 获取"base_url"、"API_KEY"和"MODEL"输入框的内容
base_url = self.entries["自定义"]["access_key"].get() # 假设 "access_key" 对应的是 base_url
api_key = self.entries["自定义"]["secret_key"].get() # 假设 "secret_key" 对应的是 API_KEY
model = self.model_vars["自定义"].get() # 获取模型的选择项
# 打印获取到的值(可选,调试用)
print(f"正在保存自定义预设:{custom_preset_name}")
print(f"Base URL: {base_url}")
print(f"API_KEY: {api_key}")
print(f"MODEL: {model}")
# 读取 config.json 文件并更新配置
if os.path.exists("config.json"):
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
else:
print("配置文件 config.json 不存在,创建配置文件")
self.save_keys() # 调用 self.save_keys 函数创建配置文件
# 重新加载配置文件
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
# 获取或初始化 "自定义" 配置项
custom_config = config_data.get("config", {}).get("自定义", {})
# 将用户填写的内容保存到配置中,覆盖已存在的内容
custom_config[custom_preset_name] = {
"ACCESS_KEY": base_url, # 用 base_url 填充 ACCESS_KEY
"SECRET_KEY": api_key, # 用 api_key 填充 SECRET_KEY
"MODEL": model # 用 model 填充 MODEL
}
# 将更新后的配置写回 config.json 文件
config_data["config"]["自定义"] = custom_config
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config_data, f, ensure_ascii=False, indent=4)
print(f"自定义预设 {custom_preset_name} 已保存!")
self.load_custom_presets(custom_config_combobox)
def add_textbox(self):
# 创建一个新的文本框计数器
self.textbox_counter += 1
# 创建一个 Frame 用于容纳该行的控件
row_frame = tk.Frame(self.scrollable_frame_window)
row_frame.grid_columnconfigure(0, weight=1)
row_frame.grid_columnconfigure(1, weight=0) # 使第1列不扩展
row_frame.grid_columnconfigure(2, weight=0) # 使第2列不扩展
row_frame.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
row_frame.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
row_frame.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
# 创建新的文本框
new_textbox = tk.Entry(row_frame, width=30)
new_textbox.grid(row=0, column=0, pady=5, padx=10, sticky="ew")
# 为每个新文本框创建一个“浏览...”按钮
def browse_folder(textbox=new_textbox): # 使用默认参数来绑定当前文本框
folder_path = filedialog.askdirectory() # 打开选择文件夹对话框
if folder_path: # 如果选择了路径,则填充到文本框
textbox.delete(0, tk.END)
textbox.insert(0, folder_path)
# 创建“浏览...”按钮并放置在文本框的右侧
browse_button = tk.Button(row_frame, text="浏览...", command=browse_folder)
browse_button.grid(row=0, column=1, pady=5, padx=(0, 10), sticky="w")
# 创建“删除”按钮,并绑定删除功能
def delete_row(frame=row_frame):
# 删除当前行的所有控件
frame.destroy()
# 创建“删除”按钮并放置在浏览按钮的右侧
delete_button = tk.Button(row_frame, text="删除", command=delete_row)
delete_button.grid(row=0, column=2, pady=5, padx=(0, 10), sticky="w")
# 将这一行的所有控件(文本框、浏览按钮、删除按钮)添加到框架中
row_frame.grid(row=self.textbox_counter, column=0, pady=5, padx=10, sticky="ew")
for widget in row_frame.winfo_children():
widget.bind("<MouseWheel>", self._on_mouse_wheel) # Windows
widget.bind("<Button-4>", self._on_mouse_wheel) # macOS 向上滚动
widget.bind("<Button-5>", self._on_mouse_wheel) # macOS 向下滚动
def _on_mouse_wheel(self, event):
"""处理鼠标滚轮事件以滚动画布"""
if event.num == 4 or event.delta > 0:
self.canvas_window.yview_scroll(-1, "units") # 向上滚动
elif event.num == 5 or event.delta < 0:
self.canvas_window.yview_scroll(1, "units") # 向下滚动
def connect_gradio(self):
# 获取输入框中的 URL
url = self.gradio_url_var.get() or "http://localhost:9872/" # 如果为空则使用默认值
thread_url = threading.Thread(target=self.connect_to_gradio, args=(url,)) # 使用 args 传递参数
thread_url.start()
def connect_to_gradio(self, url):
global client # 确保在函数中修改全局变量
try:
client = Client(url) # 初始化 Gradio 客户端
folder_audio_viewer.set_client(client) # 将 client 赋值给 FolderAudioViewer 实例
voice_generator_app.set_client(client) # 将 client 赋值给 VoiceGeneratorApp 实例
self.example_window.set_client(client) # 将 client 赋值给 GPTSoVITSWindow 实例
print(f"Connected to {url}")
tk.messagebox.showinfo("Connection", f"Connected to {url}")
except Exception as e:
print(f"Failed to connect to {url}: {e}")
tk.messagebox.showerror("Connection Error",
f"Failed to connect to {url}: 请启动WebUI并开启TTS推理,在推理UI启动后连接到WebUI地址{e}")
def run_connect_to_gradio_start(self):
threading.Thread(target=self.connect_to_gradio_start).start()
def connect_to_gradio_start(self):
global client # 确保在函数中修改全局变量
# 从 config.json 中读取 Gradio URL
try:
with open("config.json", "r", encoding="utf-8") as f:
config_data = json.load(f)
url = config_data.get("config", {}).get("Gradio_URL", "http://localhost:9872/")
except FileNotFoundError:
url = "http://localhost:9872/"
print("config.json 文件未找到,使用默认 URL")
try:
client = Client(url) # 初始化 Gradio 客户端
folder_audio_viewer.set_client(client) # 将 client 赋值给 FolderAudioViewer 实例
voice_generator_app.set_client(client) # 将 client 赋值给 VoiceGeneratorApp 实例
self.example_window.set_client(client)
print(f"Connected to {url}")
tk.messagebox.showinfo("Connection", f"Connected to {url}")
except Exception as e:
print(f"Failed to connect to {url}: {e}")
tk.messagebox.showerror("Connection Error",
f"Failed to connect to {url}: 请启动WebUI并开启TTS推理,在推理UI启动后连接到WebUI地址{e}")
# 使用 after() 方法确保 start_display_folders 在主线程中执行
self.example_window.root.after(0, folder_audio_viewer.start_display_folders)
def create_settings_tab(self, notebook, tab_name):
"""创建设置窗口中的每个选项卡"""
frame = tk.Frame(notebook)
notebook.add(frame, text=tab_name)
tk.Label(frame, text=f"{tab_name} ACCESS_KEY:").pack(anchor='w', padx=10, pady=5)
access_key_entry = tk.Entry(frame, width=30)
access_key_entry.pack(anchor='w', padx=10)
tk.Label(frame, text=f"{tab_name} SECRET_KEY:").pack(anchor='w', padx=10, pady=5)
secret_key_entry = tk.Entry(frame, width=30)
secret_key_entry.pack(anchor='w', padx=10)
# 将entry添加到字典中
self.entries[tab_name] = {"access_key": access_key_entry, "secret_key": secret_key_entry}
def save_keys_and_close_window(self):
self.save_keys()
# 关闭设置窗口
self.settings_window.destroy()
def save_keys(self):
"""保存每个选项卡的 ACCESS_KEY、SECRET_KEY 和模型选择"""
config_data = {"config": {}, "projects": self.projects}
# 记录当前的自定义预设配置
custom_presets = {}
# 保存Gradio URL
config_data["config"]["Gradio_URL"] = self.gradio_url_var.get()
# 遍历每个选项卡,保存 ACCESS_KEY、SECRET_KEY 和模型选择
for tab_name, entry_dict in self.entries.items():
if tab_name == "自定义" or tab_name == "更多":
continue # 跳过自定义和更多选项卡的配置
# 特殊处理“讯飞”选项卡
if tab_name == "讯飞":
access_key = entry_dict["access_key"].get()
secret_key = entry_dict["secret_key"].get()
api_key = entry_dict["api_key"].get() # 获取APIKey
model_choice = self.model_vars[tab_name].get() # 获取模型选择