-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimax_web.py
More file actions
1384 lines (1208 loc) · 55 KB
/
minimax_web.py
File metadata and controls
1384 lines (1208 loc) · 55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MiniMax AI Web UI
基于 Gradio 的图形化界面
"""
import gradio as gr
import os
import sys
import time
import json
import base64
import requests
from pathlib import Path
from datetime import datetime
# 添加当前目录到路径
sys.path.insert(0, str(Path(__file__).parent))
from minimax_cli import MiniMaxClient, FileManager
# 初始化客户端
client = None
file_mgr = None
def init_client():
"""初始化 MiniMax 客户端"""
global client, file_mgr
try:
client = MiniMaxClient()
file_mgr = FileManager()
return True, "✅ 连接成功"
except Exception as e:
return False, f"❌ 连接失败: {str(e)}"
# ==================== 对话模块 ====================
def create_chat_tab():
"""创建对话标签页"""
with gr.TabItem("💬 对话"):
gr.Markdown("## AI 对话聊天")
with gr.Row():
with gr.Column(scale=1):
# 模型分类选择
model_category = gr.Dropdown(
choices=[
("编程/Agent (Anthropic API)", "anthropic"),
("对话/角色扮演 (M2-her)", "m2her"),
],
value="anthropic",
label="模型类别",
)
# Anthropic API 模型
anthropic_model = gr.Dropdown(
choices=[
"MiniMax-M2.7",
"MiniMax-M2.7-highspeed",
"MiniMax-M2.5",
"MiniMax-M2.5-highspeed",
"MiniMax-M2.1",
"MiniMax-M2.1-highspeed",
"MiniMax-M2",
],
value="MiniMax-M2.7",
label="模型",
visible=True,
)
# M2-her 模型(专用)
m2her_model = gr.Dropdown(
choices=["M2-her"], value="M2-her", label="模型", visible=False
)
# 系统提示词(通用)
system_prompt = gr.Textbox(
label="系统提示词 (system)",
placeholder="设定AI的角色和行为...",
lines=2,
)
# M2-her 专用参数
with gr.Accordion(
"🎭 M2-her 角色设定", open=False, visible=False
) as m2her_settings:
user_system = gr.Textbox(
label="用户角色设定 (user_system)",
placeholder="设定用户的角色和人设...",
lines=2,
)
group_name = gr.Textbox(
label="对话分组名称 (group)",
placeholder="标识对话场景...",
lines=1,
)
with gr.Row():
ai_name = gr.Textbox(
label="AI名称", placeholder="如:MiniMax AI", lines=1
)
user_name = gr.Textbox(
label="用户名称", placeholder="如:用户", lines=1
)
with gr.Accordion("示例对话学习", open=False):
sample_user = gr.Textbox(
label="示例用户输入",
placeholder="示例用户说的话...",
lines=2,
)
sample_ai = gr.Textbox(
label="示例AI回复", placeholder="示例AI的回复...", lines=2
)
# 高级参数
with gr.Accordion("高级参数", open=False):
temperature = gr.Slider(
0.01, 1, value=1.0, step=0.05, label="Temperature (0-1]"
)
top_p = gr.Slider(0.01, 1, value=0.95, step=0.05, label="Top-p")
max_tokens = gr.Slider(
100, 8192, value=4096, step=100, label="Max Tokens"
)
use_anthropic = gr.Checkbox(
label="使用 Anthropic API 格式", value=True, visible=False
)
with gr.Column(scale=2):
# 对话区域
chatbot = gr.Chatbot(label="对话历史", height=480)
msg_input = gr.Textbox(
label="输入消息", placeholder="输入你想说的话..."
)
with gr.Row():
send_btn = gr.Button("🚀 发送", variant="primary")
clear_btn = gr.Button("🗑️ 清空")
# 根据模型类别切换显示
def on_category_change(category):
if category == "anthropic":
return {
anthropic_model: gr.Dropdown(visible=True),
m2her_model: gr.Dropdown(visible=False),
m2her_settings: gr.Accordion(visible=False),
use_anthropic: gr.Checkbox(value=True, visible=False),
}
else:
return {
anthropic_model: gr.Dropdown(visible=False),
m2her_model: gr.Dropdown(visible=True),
m2her_settings: gr.Accordion(visible=True),
use_anthropic: gr.Checkbox(value=False, visible=False),
}
model_category.change(
on_category_change,
inputs=[model_category],
outputs=[anthropic_model, m2her_model, m2her_settings, use_anthropic],
)
# 事件处理 - 流式响应
def respond(
message,
chat_history,
category,
anthropic_m,
m2her_m,
system_prompt,
user_system,
group_name,
ai_name,
user_name,
sample_user,
sample_ai,
temp,
top_p,
max_tok,
use_anthropic,
):
user_system = user_system or ""
group_name = group_name or ""
ai_name = ai_name or ""
user_name = user_name or ""
sample_user = sample_user or ""
sample_ai = sample_ai or ""
system_prompt = system_prompt or ""
if not message.strip():
return chat_history, ""
model = anthropic_m if category == "anthropic" else m2her_m
temp = max(0.01, min(temp, 1.0))
top_p = max(0.01, min(top_p, 1.0))
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": ""})
try:
if category == "m2her":
messages = []
if system_prompt.strip():
msg = {"role": "system", "content": system_prompt}
if ai_name.strip():
msg["name"] = ai_name
messages.append(msg)
if user_system.strip():
messages.append({"role": "user_system", "content": user_system})
if group_name.strip():
messages.append({"role": "group", "content": group_name})
if sample_user.strip() and sample_ai.strip():
messages.append(
{"role": "sample_message_user", "content": sample_user}
)
messages.append(
{"role": "sample_message_ai", "content": sample_ai}
)
for msg in chat_history[:-1]:
if isinstance(msg, dict):
role = msg.get("role", "user")
content = msg.get("content", "")
if role in ("user", "assistant"):
messages.append({"role": role, "content": content})
user_msg = {"role": "user", "content": message}
if user_name.strip():
user_msg["name"] = user_name
messages.append(user_msg)
max_completion_tokens = min(max_tok, 2048)
yield chat_history, ""
for chunk in client.chat_stream(
messages=messages,
model=model,
system_prompt=system_prompt,
temperature=temp,
max_tokens=max_completion_tokens,
use_anthropic_api=False,
show_thinking=False,
):
if chunk["type"] == "error":
chat_history[-1]["content"] = f"❌ 错误: {chunk['content']}"
yield chat_history, ""
return
if chunk["type"] == "text":
chat_history[-1]["content"] += chunk["content"]
yield chat_history, ""
else:
messages = []
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
for msg in chat_history[:-1]:
if isinstance(msg, dict):
role = msg.get("role", "user")
content = msg.get("content", "")
if role in ("user", "assistant"):
messages.append({"role": role, "content": content})
messages.append({"role": "user", "content": message})
yield chat_history, ""
for chunk in client.chat_stream(
messages=messages,
model=model,
system_prompt=system_prompt,
temperature=temp,
max_tokens=max_tok,
use_anthropic_api=True,
show_thinking=False,
):
if chunk["type"] == "error":
chat_history[-1]["content"] = f"❌ 错误: {chunk['content']}"
yield chat_history, ""
return
if chunk["type"] == "text":
chat_history[-1]["content"] += chunk["content"]
yield chat_history, ""
except Exception as e:
chat_history[-1]["content"] = f"❌ 错误: {str(e)}"
yield chat_history, ""
def clear_chat():
return [], ""
send_btn.click(
respond,
inputs=[
msg_input,
chatbot,
model_category,
anthropic_model,
m2her_model,
system_prompt,
user_system,
group_name,
ai_name,
user_name,
sample_user,
sample_ai,
temperature,
top_p,
max_tokens,
use_anthropic,
],
outputs=[chatbot, msg_input],
)
msg_input.submit(
respond,
inputs=[
msg_input,
chatbot,
model_category,
anthropic_model,
m2her_model,
system_prompt,
user_system,
group_name,
ai_name,
user_name,
sample_user,
sample_ai,
temperature,
top_p,
max_tokens,
use_anthropic,
],
outputs=[chatbot, msg_input],
)
clear_btn.click(clear_chat, outputs=[chatbot, msg_input])
# ==================== 图像生成模块 ====================
def create_image_tab():
"""创建图像生成标签页"""
with gr.TabItem("🎨 图像"):
gr.Markdown("## AI 图像生成")
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(
label="提示词", placeholder="描述你想要生成的图像...", lines=3
)
model = gr.Dropdown(
choices=["image-01", "image-01-live"],
value="image-01",
label="模型",
)
aspect_ratio = gr.Dropdown(
choices=["1:1", "16:9", "4:3", "3:2", "2:3", "3:4", "9:16", "21:9"],
value="1:1",
label="宽高比",
)
num_images = gr.Slider(1, 9, value=1, step=1, label="生成数量")
ref_image = gr.Image(
label="参考图片(可选,用于图生图)", type="filepath"
)
generate_btn = gr.Button("🎨 生成图像", variant="primary")
with gr.Column(scale=2):
output_gallery = gr.Gallery(label="生成结果", columns=3, height=600)
status_text = gr.Textbox(label="状态", interactive=False)
def generate_image(prompt, model, aspect, num, ref_img):
if not prompt.strip():
return [], "请输入提示词"
try:
# 构建参数
kwargs = {
"prompt": prompt,
"model": model,
"aspect_ratio": aspect,
"n": int(num),
}
if ref_img:
kwargs["reference_image"] = ref_img
result = client.image(**kwargs)
# 处理结果
image_paths = []
if isinstance(result, list):
# URL 列表
for i, url in enumerate(result):
if url.startswith("http"):
# 下载图片
img_path = file_mgr.get_path(
"images",
f"image_{file_mgr.generate_timestamp()}_{i}.png",
)
import urllib.request
urllib.request.urlretrieve(url, img_path)
image_paths.append(str(img_path))
else:
image_paths.append(url)
return image_paths, f"✅ 成功生成 {len(image_paths)} 张图片"
except Exception as e:
return [], f"❌ 错误: {str(e)}"
generate_btn.click(
generate_image,
inputs=[prompt, model, aspect_ratio, num_images, ref_image],
outputs=[output_gallery, status_text],
)
# ==================== 视频生成模块 ====================
def create_video_tab():
"""创建视频生成标签页"""
with gr.TabItem("🎬 视频"):
gr.Markdown("## AI 视频生成")
with gr.Tabs():
# 文生视频
with gr.TabItem("📝 文生视频"):
with gr.Row():
with gr.Column(scale=1):
prompt = gr.Textbox(
label="视频描述",
placeholder="描述你想要生成的视频...",
lines=4,
)
model = gr.Dropdown(
choices=[
"MiniMax-Hailuo-2.3",
"T2V-01-Director",
"T2V-01",
"T2V-01-live",
],
value="MiniMax-Hailuo-2.3",
label="模型",
)
duration = gr.Dropdown(
choices=[6, 10], value=6, label="时长(秒)"
)
resolution = gr.Dropdown(
choices=["512P", "720P", "768P", "1080P"],
value="768P",
label="分辨率",
)
generate_btn = gr.Button("🎬 生成视频", variant="primary")
with gr.Column(scale=2):
status = gr.Textbox(label="任务状态", value="等待生成...")
video_output = gr.Video(label="生成结果")
def generate_text_video(prompt, model, duration, resolution):
if not prompt.strip():
return "请输入视频描述", None
try:
# 提交任务
task_id = client.video(
prompt=prompt,
model=model,
duration=int(duration),
resolution=resolution,
)
# 轮询状态
max_attempts = 60 # 最多等待10分钟
for i in range(max_attempts):
status_result = client.video_status(task_id)
task_status = status_result.get("status", "")
if task_status == "Success":
file_id = status_result.get("file_id")
if file_id:
# 下载视频
video_path = client.download_video(file_id)
return f"✅ 视频生成成功!", video_path
else:
return "✅ 视频生成成功,但无法获取文件", None
elif task_status == "Fail":
return "❌ 视频生成失败", None
elif task_status in ["Preparing", "Queueing", "Processing"]:
yield (
f"⏳ 状态: {task_status} (等待 {i + 1} 秒)...",
None,
)
time.sleep(10)
else:
yield (
f"⏳ 状态: {task_status} (等待 {i + 1} 秒)...",
None,
)
time.sleep(10)
return "⏱️ 等待超时,请稍后手动查询", None
except Exception as e:
return f"❌ 错误: {str(e)}", None
generate_btn.click(
generate_text_video,
inputs=[prompt, model, duration, resolution],
outputs=[status, video_output],
)
# 图生视频
with gr.TabItem("🖼️ 图生视频"):
with gr.Row():
with gr.Column(scale=1):
first_frame = gr.Image(label="首帧图片", type="filepath")
prompt_img = gr.Textbox(
label="视频描述(可选)",
placeholder="描述视频内容...",
lines=3,
)
model_img = gr.Dropdown(
choices=[
"I2V-01-Director",
"I2V-01-live",
"I2V-01",
"MiniMax-Hailuo-2.3",
],
value="I2V-01-Director",
label="模型",
)
duration_img = gr.Dropdown(
choices=[6, 10], value=6, label="时长(秒)"
)
generate_btn_img = gr.Button("🎬 生成视频", variant="primary")
with gr.Column(scale=2):
status_img = gr.Textbox(label="任务状态", value="等待生成...")
video_output_img = gr.Video(label="生成结果")
def generate_image_video(first_frame, prompt, model, duration):
if not first_frame:
return "请上传首帧图片", None
try:
# 提交任务
task_id = client.image_to_video(
first_frame_image=first_frame,
prompt=prompt or "",
model=model,
duration=int(duration),
)
# 轮询状态
max_attempts = 60
for i in range(max_attempts):
status_result = client.video_status(task_id)
task_status = status_result.get("status", "")
if task_status == "Success":
file_id = status_result.get("file_id")
if file_id:
video_path = client.download_video(file_id)
return f"✅ 视频生成成功!", video_path
else:
return "✅ 视频生成成功,但无法获取文件", None
elif task_status == "Fail":
return "❌ 视频生成失败", None
else:
yield (
f"⏳ 状态: {task_status} (等待 {i + 1} 秒)...",
None,
)
time.sleep(10)
return "⏱️ 等待超时,请稍后手动查询", None
except Exception as e:
return f"❌ 错误: {str(e)}", None
generate_btn_img.click(
generate_image_video,
inputs=[first_frame, prompt_img, model_img, duration_img],
outputs=[status_img, video_output_img],
)
# ==================== 音乐与音频模块 ====================
def create_audio_tab():
"""创建音乐与音频标签页"""
with gr.TabItem("🎵 音乐"):
gr.Markdown("## AI 音乐生成")
with gr.Tabs():
# 音乐生成
with gr.TabItem("🎼 音乐创作"):
with gr.Row():
with gr.Column(scale=1):
model = gr.Dropdown(
choices=["music-2.5+", "music-2.5"],
value="music-2.5+",
label="模型",
)
instrumental = gr.Checkbox(
label="纯音乐模式(无人声)", value=False
)
prompt = gr.Textbox(
label="音乐描述",
placeholder="描述风格、情绪、场景,如:流行音乐,欢快,适合派对...",
lines=2,
)
lyrics = gr.Textbox(
label="歌词",
placeholder="[Verse]\n歌词内容...\n[Chorus]\n副歌内容...",
lines=6,
)
lyrics_optimizer = gr.Checkbox(
label="自动生成歌词", value=False
)
with gr.Accordion("音频参数", open=False):
sample_rate = gr.Dropdown(
[16000, 24000, 32000, 44100],
value=44100,
label="采样率",
)
bitrate = gr.Dropdown(
[32000, 64000, 128000, 256000],
value=256000,
label="比特率",
)
format_type = gr.Dropdown(
["mp3", "wav", "pcm"], value="mp3", label="格式"
)
generate_btn = gr.Button("🎵 生成音乐", variant="primary")
with gr.Column(scale=2):
status = gr.Textbox(label="状态", value="等待生成...")
audio_output = gr.Audio(label="生成结果", type="filepath")
def generate_music(
model,
instrumental,
prompt,
lyrics,
lyrics_opt,
sample_rate,
bitrate,
format_type,
):
try:
# 调用音乐生成
audio_data = client.music(
prompt=prompt if prompt else None,
lyrics=lyrics if lyrics else None,
model=model,
is_instrumental=instrumental,
lyrics_optimizer=lyrics_opt,
sample_rate=int(sample_rate),
bitrate=int(bitrate),
format=format_type,
)
# 保存音频文件
timestamp = file_mgr.generate_timestamp()
filename = f"music_{timestamp}.{format_type}"
filepath = file_mgr.save_file(audio_data, filename, "music")
return f"✅ 音乐生成成功!", filepath
except Exception as e:
return f"❌ 错误: {str(e)}", None
generate_btn.click(
generate_music,
inputs=[
model,
instrumental,
prompt,
lyrics,
lyrics_optimizer,
sample_rate,
bitrate,
format_type,
],
outputs=[status, audio_output],
)
# TTS
with gr.TabItem("🗣️ 语音合成"):
with gr.Row():
with gr.Column(scale=1):
text = gr.Textbox(
label="文本内容",
placeholder="输入要转换为语音的文本...",
lines=4,
)
# 加载音色列表
def load_voices():
try:
result = client.list_voices("system")
voices = result.get("voices", [])
if voices:
choices = [v["voice_id"] for v in voices]
return gr.Dropdown(
choices=choices, value=choices[0]
)
else:
# 默认音色列表
default_voices = [
"female-chengshu",
"male-chengshu",
"female-yujie",
"male-yujie",
"female-tianmei",
]
return gr.Dropdown(
choices=default_voices, value="female-chengshu"
)
except:
default_voices = [
"female-chengshu",
"male-chengshu",
"female-yujie",
"male-yujie",
"female-tianmei",
]
return gr.Dropdown(
choices=default_voices, value="female-chengshu"
)
voice = gr.Dropdown(label="音色", choices=[])
tts_model = gr.Dropdown(
choices=[
"speech-2.8-hd",
"speech-2.8-turbo",
"speech-2.6-hd",
"speech-2.6-turbo",
"speech-02-hd",
"speech-02-turbo",
],
value="speech-2.8-hd",
label="TTS模型",
)
emotion = gr.Dropdown(
choices=[
"happy",
"sad",
"angry",
"fearful",
"disgusted",
"surprised",
"calm",
"fluent",
"whisper",
],
value="happy",
label="情感",
)
with gr.Row():
speed = gr.Slider(
0.5, 2.0, value=1.0, step=0.1, label="语速"
)
vol = gr.Slider(0, 10, value=1.0, step=0.1, label="音量")
pitch = gr.Slider(-12, 12, value=0, step=1, label="音高")
tts_btn = gr.Button("🗣️ 生成语音", variant="primary")
with gr.Column(scale=2):
tts_status = gr.Textbox(label="状态")
tts_audio = gr.Audio(label="生成结果", type="filepath")
# 页面加载时加载音色列表
def load_voices():
try:
result = client.list_voices("system")
voices = result.get("voices", [])
if voices:
choices = [v["voice_id"] for v in voices]
return gr.Dropdown(choices=choices, value=choices[0])
else:
# 默认音色列表
default_voices = [
"female-chengshu",
"male-chengshu",
"female-yujie",
"male-yujie",
"female-tianmei",
]
return gr.Dropdown(
choices=default_voices, value="female-chengshu"
)
except:
default_voices = [
"female-chengshu",
"male-chengshu",
"female-yujie",
"male-yujie",
"female-tianmei",
]
return gr.Dropdown(
choices=default_voices, value="female-chengshu"
)
# 初始化音色列表
voice.choices = load_voices().choices
voice.value = load_voices().value
def generate_tts(text, voice, model, emotion, speed, vol, pitch):
if not text.strip():
return "请输入文本", None
try:
audio_data = client.tts(
text=text,
voice_id=voice,
model=model,
emotion=emotion,
speed=speed,
vol=vol,
pitch=pitch,
)
# 保存音频
timestamp = file_mgr.generate_timestamp()
filename = f"tts_{timestamp}.mp3"
filepath = file_mgr.save_file(audio_data, filename, "audio")
return f"✅ 语音合成成功!", filepath
except Exception as e:
return f"❌ 错误: {str(e)}", None
# 加载音色列表
voice.choices = load_voices().choices
voice.value = "female-chengshu"
tts_btn.click(
generate_tts,
inputs=[text, voice, tts_model, emotion, speed, vol, pitch],
outputs=[tts_status, tts_audio],
)
# ==================== 播客模块 ====================
def create_podcast_tab():
"""创建播客生成标签页"""
with gr.TabItem("🎙️ 播客"):
gr.Markdown("## AI 播客生成")
with gr.Row():
with gr.Column(scale=1):
topic = gr.Textbox(
label="播客主题",
placeholder="输入播客主题,如:AI创作短剧会成为新风口吗?",
lines=2,
)
welcome_text = gr.Textbox(
label="欢迎语", value="欢迎收听本期节目!", lines=1
)
with gr.Accordion("对话编辑(高级)", open=False):
dialogue_json = gr.Code(
label="对话 JSON(可选,用于自定义)", language="json", lines=10
)
generate_btn = gr.Button("🎙️ 生成播客", variant="primary")
with gr.Column(scale=2):
progress = gr.Textbox(label="生成进度", value="等待开始...")
podcast_audio = gr.Audio(label="生成结果", type="filepath")
def generate_podcast(topic, welcome_text, dialogue_json):
if not topic.strip():
return "请输入播客主题", None
try:
# 这里需要调用播客生成功能
# 由于播客生成涉及多个步骤,简化处理
yield "📝 正在生成对话脚本...", None
# 使用 chat 方法生成对话
system_prompt = """你是一个专业的播客制作助手。请生成一个自然流畅的双人对话播客,围绕用户提供的主题展开。
对话要求:
1. 包含两位主播:主持人(活泼开朗,引导话题)和嘉宾(专业人士,分享观点)
2. 对话形式自然,有互动和讨论,不是单方面讲解
3. 总长度控制在10-15轮对话
4. 输出严格为JSON数组,每个元素包含:
- speaker: "主持人"或"嘉宾"
- text: 对话内容(口语化,自然)
- voice_id: 主持人用"female-tianmei"(甜美女声),嘉宾用"male-chengshu"(成熟男声)
- emotion: 根据内容选择合适的情感,如happy、calm、excited等"""
messages = [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": f'请生成关于"{topic}"的播客对话,开头必须包含欢迎语:{welcome_text}',
},
]
response = client._request(
"POST",
"text/chatcompletion_v2",
json={
"model": "MiniMax-M2.5",
"messages": messages,
"temperature": 0.8,
"max_completion_tokens": 2048,
},
)
dialogue_text = response["choices"][0]["message"]["content"]
# 尝试解析JSON
try:
# 提取JSON部分
import re
json_match = re.search(r"\[.*\]", dialogue_text, re.DOTALL)
if json_match:
dialogue_data = json.loads(json_match.group())
else:
dialogue_data = json.loads(dialogue_text)
except:
return "❌ 对话生成失败,无法解析JSON", None
yield f"🎤 正在合成语音(共{len(dialogue_data)}段对话)...", None
# 合成每段语音并合并
audio_segments = []
for i, item in enumerate(dialogue_data):
text = item.get("text", "")
voice_id = item.get("voice_id", "female-chengshu")
emotion = item.get("emotion", "happy")
if text:
try:
audio_data = client.tts(
text=text,
voice_id=voice_id,
emotion=emotion,
speed=1.0,
vol=1.0,
)
audio_segments.append(audio_data)
yield f"🎤 合成进度: {i + 1}/{len(dialogue_data)}", None
except:
continue
# 合并音频(简化处理,实际应该使用音频处理库)
# 这里只保存第一段作为示例
if audio_segments:
timestamp = file_mgr.generate_timestamp()
filename = f"podcast_{timestamp}.mp3"
filepath = file_mgr.save_file(
audio_segments[0], filename, "podcasts"
)
return f"✅ 播客生成成功(示例,仅第一段)!", filepath
else:
return "❌ 语音合成失败", None
except Exception as e:
return f"❌ 错误: {str(e)}", None
generate_btn.click(
generate_podcast,
inputs=[topic, welcome_text, dialogue_json],
outputs=[progress, podcast_audio],
)
# ==================== 文件管理模块 ====================
def create_file_tab():
"""创建文件管理标签页"""
with gr.TabItem("📁 文件"):
gr.Markdown("## 文件管理")
with gr.Row():
file_purpose = gr.Dropdown(
choices=["voice_clone", "prompt_audio", "t2a_async_input"],
value="voice_clone",
label="文件用途",
scale=3,
)
refresh_btn = gr.Button("🔄 刷新列表", scale=1)
files_state = gr.State([])
file_table = gr.Dataframe(
headers=["ID", "文件名", "用途", "大小", "创建时间"],
label="文件列表",
interactive=False,
)