-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
263 lines (218 loc) · 10.5 KB
/
Copy pathapp.py
File metadata and controls
263 lines (218 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python3
"""MiniMax All-in-One GUI — wraps mmx CLI with Gradio web interface."""
import os
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["GRADIO_ANALYTICS_ENABLED"] = "false"
import subprocess
import tempfile
import os
import gradio as gr
OUT_DIR = os.path.expanduser("~/Desktop/mmx_outputs")
os.makedirs(OUT_DIR, exist_ok=True)
def run_mmx(args, timeout=120):
"""Run mmx CLI and return parsed result."""
cmd = ["mmx"] + args + ["--output", "json"]
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
stdout = r.stdout.strip()
stderr = r.stderr.strip()
if r.returncode != 0:
return None, stderr or stdout or "Unknown error"
return stdout, None
except subprocess.TimeoutExpired:
return None, "请求超时"
except Exception as e:
return None, str(e)
# ─── Tab 1: Text Chat ────────────────────────────────────────────
def text_chat(message, history):
history = history or []
history.append({"role": "user", "content": message})
# Build multi-message input
args = ["text", "chat"]
for h in history[-10:]: # last 10 turns
args += ["--message", f"{h['role']}:{h['content']}"]
output, err = run_mmx(args, timeout=60)
if err:
history.append({"role": "assistant", "content": f"❌ {err}"})
else:
try:
import json
data = json.loads(output)
reply = data.get("content", output)
except:
reply = output
history.append({"role": "assistant", "content": reply})
return "", history
# ─── Tab 2: Image Generation ─────────────────────────────────────
def image_generate(prompt, num_images):
args = ["image", prompt, "--n", str(num_images)]
out_path = os.path.join(OUT_DIR, "image")
args += ["--out", out_path]
output, err = run_mmx(args, timeout=90)
if err:
return [None] * num_images, f"❌ {err}"
# Find generated files
import glob
files = sorted(glob.glob(out_path + "*"))
if not files:
files = sorted(glob.glob(out_path + "_*"))
if not files:
# Try current dir
files = sorted(glob.glob("mmx_*.jpg") + glob.glob("mmx_*.png"))
images = []
for i in range(num_images):
if i < len(files):
images.append(files[i])
else:
images.append(None)
return images, f"✅ 已保存到 {OUT_DIR}/"
# ─── Tab 3: Image Understanding ──────────────────────────────────
def vision_describe(image):
if image is None:
return "请上传图片"
args = ["vision", image]
output, err = run_mmx(args, timeout=30)
if err:
return f"❌ {err}"
try:
import json
data = json.loads(output)
return data.get("content", output)
except:
return output
# ─── Tab 4: Speech Synthesis ─────────────────────────────────────
def speech_synthesize(text, voice, speed):
if not text.strip():
return None, "请输入文本"
out_path = os.path.join(OUT_DIR, "speech.mp3")
args = ["speech", "synthesize", "--text", text, "--voice", voice,
"--speed", str(speed), "--out", out_path]
output, err = run_mmx(args, timeout=60)
if err:
return None, f"❌ {err}"
return out_path, f"✅ 已保存 {out_path}"
# ─── Tab 5: Music Generation ─────────────────────────────────────
def music_generate(prompt, lyrics, vocals, instrumental, lyrics_optimizer):
out_path = os.path.join(OUT_DIR, "music.mp3")
args = ["music", "generate", "--prompt", prompt, "--out", out_path]
if instrumental:
args.append("--instrumental")
elif lyrics_optimizer:
args.append("--lyrics-optimizer")
elif lyrics.strip():
args += ["--lyrics", lyrics]
if vocals.strip():
args += ["--vocals", vocals]
output, err = run_mmx(args, timeout=120)
if err:
return None, f"❌ {err}"
return out_path, f"✅ 已保存 {out_path}"
# ─── Tab 6: Music Cover ──────────────────────────────────────────
def music_cover(audio_file, style_prompt):
if audio_file is None:
return None, "请上传参考音频"
out_path = os.path.join(OUT_DIR, "cover.mp3")
args = ["music", "cover", "--prompt", style_prompt,
"--audio-file", audio_file, "--out", out_path]
output, err = run_mmx(args, timeout=180)
if err:
return None, f"❌ {err}"
return out_path, f"✅ 已保存 {out_path}"
# ─── Build UI ────────────────────────────────────────────────────
VOICES = [
"male-qn-qingse", "male-qn-jingying", "male-qn-badao", "male-qn-daxuesheng",
"female-shaonv", "female-yujie", "female-chengshu", "female-tianmei",
"clever_boy", "cute_boy", "lovely_girl", "junlang_nanyou",
"tianxin_xiaoling", "qiaopi_mengmei", "wumei_yujie",
]
with gr.Blocks(title="MiniMax Studio") as app:
gr.Markdown("# 🎨 MiniMax Studio")
gr.Markdown("AI 文本 · 图片 · 语音 · 音乐 — 一站式创作")
with gr.Tabs():
# ── Text ──
with gr.Tab("💬 文本对话"):
gr.Markdown("M2.7 多轮对话(每次独立请求)")
txt_msg = gr.Textbox(placeholder="输入消息...", label="你的消息", lines=2)
txt_system = gr.Textbox(label="系统提示词(可选)",
placeholder="你是一个有帮助的助手", lines=1)
txt_btn = gr.Button("发送", variant="primary")
txt_output = gr.Textbox(label="回复", lines=20)
def text_single(message, system_prompt):
args = ["text", "chat", "--message", message]
if system_prompt.strip():
args += ["--system", system_prompt]
output, err = run_mmx(args, timeout=60)
if err:
return f"❌ {err}"
try:
import json
data = json.loads(output)
# Handle array response (thinking + text blocks)
if isinstance(data, list):
texts = []
for block in data:
if isinstance(block, dict) and block.get("type") == "text":
texts.append(block.get("text", ""))
return "\n".join(texts) if texts else output
# Handle object response
if isinstance(data, dict):
return data.get("content", output)
return output
except:
return output
txt_btn.click(text_single, [txt_msg, txt_system], [txt_output])
txt_msg.submit(text_single, [txt_msg, txt_system], [txt_output])
# ── Image Gen ──
with gr.Tab("🖼️ 图片生成"):
with gr.Row():
img_prompt = gr.Textbox(label="描述", placeholder="一只猫在太空站里喝咖啡")
img_num = gr.Slider(1, 4, value=1, step=1, label="数量")
img_btn = gr.Button("生成", variant="primary")
img_gallery = gr.Gallery(label="生成结果", columns=2, height=400)
img_msg = gr.Markdown("")
img_btn.click(image_generate, [img_prompt, img_num], [img_gallery, img_msg])
# ── Vision ──
with gr.Tab("👁️ 图片理解"):
with gr.Row():
vis_image = gr.Image(type="filepath", label="上传图片")
vis_output = gr.Textbox(label="分析结果", lines=15)
vis_btn = gr.Button("分析", variant="primary")
vis_btn.click(vision_describe, [vis_image], [vis_output])
# ── Speech ──
with gr.Tab("🔊 语音合成"):
sp_text = gr.Textbox(label="文本", placeholder="输入要朗读的文字...", lines=3)
with gr.Row():
sp_voice = gr.Dropdown(VOICES, value="female-yujie", label="音色")
sp_speed = gr.Slider(0.5, 2.0, value=1.0, label="语速")
sp_btn = gr.Button("合成", variant="primary")
sp_audio = gr.Audio(label="播放")
sp_msg = gr.Markdown("")
sp_btn.click(speech_synthesize, [sp_text, sp_voice, sp_speed], [sp_audio, sp_msg])
# ── Music ──
with gr.Tab("🎵 音乐生成"):
mu_prompt = gr.Textbox(label="风格描述", placeholder="轻快流行,温暖人声",
value="轻快的电子流行音乐")
mu_lyrics = gr.Textbox(label="歌词(留空则自动生成)", lines=5,
placeholder="[verse] 歌词...\n[chorus] 副歌...")
mu_vocals = gr.Textbox(label="人声描述(可选)",
placeholder="温暖男声 / 明亮女高音 / 男女对唱")
with gr.Row():
mu_instrumental = gr.Checkbox(label="纯音乐(无歌词)")
mu_lyrics_opt = gr.Checkbox(label="AI 自动写歌词")
mu_btn = gr.Button("生成音乐", variant="primary")
mu_audio = gr.Audio(label="播放")
mu_msg = gr.Markdown("")
mu_btn.click(music_generate, [mu_prompt, mu_lyrics, mu_vocals,
mu_instrumental, mu_lyrics_opt],
[mu_audio, mu_msg])
# ── Cover ──
with gr.Tab("🎤 翻唱"):
cv_audio = gr.Audio(type="filepath", label="上传原曲")
cv_style = gr.Textbox(label="目标风格", placeholder="摇滚 / 爵士 / 民谣 / ...",
value="硬摇滚,电吉他,强力鼓点")
cv_btn = gr.Button("翻唱", variant="primary")
cv_output = gr.Audio(label="翻唱结果")
cv_msg = gr.Markdown("")
cv_btn.click(music_cover, [cv_audio, cv_style], [cv_output, cv_msg])
if __name__ == "__main__":
app.launch(server_port=7860, share=False, inbrowser=True)