dylanqi27 commited on
Commit
e87df95
·
verified ·
1 Parent(s): e53cc3a

Upload 5 files

Browse files
Files changed (5) hide show
  1. README.md +48 -1
  2. app.py +123 -0
  3. packages.txt +1 -0
  4. pipeline.py +393 -0
  5. requirements.txt +5 -0
README.md CHANGED
@@ -1,3 +1,50 @@
1
  ---
2
- license: mit
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: NExT-GPT Any-to-Any MLLM
3
+ emoji: 🧠
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
  ---
10
+
11
+ # NExT-GPT · Any-to-Any 多模态大语言模型复现
12
+
13
+ 复现 [NExT-GPT (ICML 2024 Oral)](https://arxiv.org/abs/2309.05519) 的任意模态输入 → 任意模态输出接口。
14
+
15
+ ## 三种模式
16
+
17
+ | 模式 | 依赖 | 说明 |
18
+ | --- | --- | --- |
19
+ | `offline` | 无 | 纯离线占位素材,CPU 免费 Space 必跑,验证四路输出与信号 token 管线 |
20
+ | `lite` | Space Secret `HF_TOKEN` | 调用 HF Serverless:Qwen2.5-7B-Instruct → FLUX.1-schnell / MMS-TTS / LTX-Video;任一调用失败自动降级 offline |
21
+ | `full` | `NEXTGPT_ROOT` + `NEXTGPT_CKPT` + GPU | 检测官方 `7b_tiva_v0` 权重并给出本地启动命令 |
22
+
23
+ > **复现边界**:`offline` / `lite` 为接口级复现,不加载论文权重。权重级复现(LLaMA-7B + Vicuna delta v0 + ImageBind-Huge + NExT-GPT delta + 三个扩散模型)见提交包 `reproduce/`,需 ≥1×A100 40GB。
24
+
25
+ ## 架构
26
+
27
+ ```
28
+ ImageBind-Huge ── input projection ──> Vicuna-7B v0 ──> text tokens
29
+ │
30
+ └─> [IMG0..3] [VID0..23] [AUD0..7]
31
+ │ output projection
32
+ ┌────────────────────────┼────────────────────────┐
33
+ SD v1-5 ZeroScope v2_576w AudioLDM-l-full
34
+ image video audio
35
+ ```
36
+
37
+ 信号 token 数量与官方 `config/base.yaml` 一致(4 / 24 / 8)。
38
+
39
+ ## 链接
40
+
41
+ - 论文:https://arxiv.org/abs/2309.05519
42
+ - 官方代码:https://github.com/NExT-GPT/NExT-GPT
43
+ - 项目主页:https://next-gpt.github.io/
44
+ - 官方 delta 权重:https://huggingface.co/ChocoWu/nextgpt_7b_tiva_v0 (`pytorch_model.pt`)
45
+ - LLaMA-7B:https://huggingface.co/huggyllama/llama-7b
46
+ - Vicuna delta v0:https://huggingface.co/lmsys/vicuna-7b-delta-v0
47
+
48
+ ## 许可
49
+
50
+ NExT-GPT 官方代码 BSD-3-Clause 且限非商业研究;`ChocoWu/nextgpt_7b_tiva_v0` 为 CC-BY-NC-SA-4.0;LLaMA 权重受 Meta 非商业许可约束。本 Space 仅用于课程复现演示。
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NExT-GPT any-to-any MLLM reproduction - Hugging Face Space entry point.
2
+
3
+ Paper : https://arxiv.org/abs/2309.05519
4
+ Code : https://github.com/NExT-GPT/NExT-GPT
5
+ Weight: https://huggingface.co/ChocoWu/nextgpt_7b_tiva_v0
6
+
7
+ Deploy: copy this `space/` folder into a Gradio Space. Set the HF_TOKEN secret
8
+ for lite mode. With no token / no network the offline mode still runs on CPU.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+
15
+ import gradio as gr
16
+
17
+ from pipeline import run
18
+
19
+ MODES = [
20
+ ("offline", "Offline(离线占位,CPU 必跑)"),
21
+ ("lite", "Lite(HF Serverless 推理,需 HF_TOKEN)"),
22
+ ("full", "Full(检测官方 7b_tiva_v0 权重)"),
23
+ ]
24
+
25
+ CSS = """
26
+ .gradio-container {max-width: 1180px !important;}
27
+ #signals {font-size: 12px; line-height: 1.7;}
28
+ footer {display:none !important;}
29
+ """
30
+
31
+
32
+ def infer(mode_label: str, prompt: str, wanted: list[str], image, audio, video):
33
+ mode = next(m for m, label in MODES if label == mode_label)
34
+ r = run(mode, prompt, wanted, image, audio, video)
35
+ logs = {
36
+ "mode": r.mode,
37
+ "pipeline": "ImageBind -> input projection -> Vicuna-7B -> signal tokens -> output projection -> diffusion decoders",
38
+ "steps": r.log,
39
+ }
40
+ return (
41
+ r.text,
42
+ r.image,
43
+ r.audio,
44
+ r.video,
45
+ r.signals,
46
+ logs,
47
+ )
48
+
49
+
50
+ with gr.Blocks(title="NExT-GPT · Any-to-Any MLLM 复现", css=CSS) as demo:
51
+ gr.Markdown(
52
+ """
53
+ # NExT-GPT · Any-to-Any MLLM 复现
54
+
55
+ 文本 / 图像 / 视频 / 音频 **任意输入 → 任意输出**。三段式结构:
56
+ ImageBind-Huge 编码侧投影 → Vicuna-7B v0 生成文本与**模态信号 token** → 输出投影层驱动
57
+ SD v1-5 / ZeroScope v2_576w / AudioLDM-l-full。
58
+
59
+ > ⚠️ **复现边界**:本 Space 的 `offline` / `lite` 是**接口级复现**(数据流 + 信号 token + 四路输出),
60
+ > 不加载论文权重。`full` 与提交包 `reproduce/` 目录才是权重级复现(需 ≥1×A100 40GB)。
61
+ """
62
+ )
63
+
64
+ with gr.Row():
65
+ mode = gr.Radio(
66
+ choices=[label for _, label in MODES],
67
+ value=MODES[0][1],
68
+ label="运行模式",
69
+ )
70
+ wanted = gr.CheckboxGroup(
71
+ choices=["text", "image", "audio", "video"],
72
+ value=["text", "image", "audio", "video"],
73
+ label="请求输出模态",
74
+ )
75
+
76
+ prompt = gr.Textbox(
77
+ label="Prompt",
78
+ lines=3,
79
+ value="I started practicing mindfulness recently. Give me a short tip, show me a calming image, play soft music and make a short video.",
80
+ )
81
+
82
+ with gr.Accordion("多模态输入(full 模式由 ImageBind 编码;lite/offline 仅记录输入模态)", open=False):
83
+ with gr.Row():
84
+ in_image = gr.Image(type="filepath", label="图像输入")
85
+ in_audio = gr.Audio(type="filepath", label="音频输入")
86
+ in_video = gr.Video(label="视频输入")
87
+
88
+ btn = gr.Button("Run any-to-any", variant="primary")
89
+
90
+ with gr.Row():
91
+ out_text = gr.Textbox(label="文本输出 / 状态", lines=10)
92
+ out_image = gr.Image(type="filepath", label="图像输出 (SD v1-5)")
93
+
94
+ with gr.Row():
95
+ out_audio = gr.Audio(type="filepath", label="音频输出 (AudioLDM / TTS)")
96
+ out_video = gr.Video(label="视频输出 (ZeroScope)")
97
+
98
+ with gr.Accordion("模态信号 token(与官方 config/base.yaml 一致:IMG×4 / VID×24 / AUD×8)", open=False):
99
+ out_signals = gr.Markdown(elem_id="signals")
100
+
101
+ with gr.Accordion("运行日志", open=False):
102
+ out_log = gr.JSON(label="calls / fallback")
103
+
104
+ gr.Examples(
105
+ examples=[
106
+ ["Explain meditation in two sentences, then generate an image and soft audio.", ["text", "image", "audio"], MODES[0][1]],
107
+ ["A forest fire near a city; produce a short news video.", ["text", "video"], MODES[0][1]],
108
+ ],
109
+ inputs=[prompt, wanted, mode],
110
+ )
111
+
112
+ btn.click(
113
+ fn=infer,
114
+ inputs=[mode, prompt, wanted, in_image, in_audio, in_video],
115
+ outputs=[out_text, out_image, out_audio, out_video, out_signals, out_log],
116
+ )
117
+
118
+ if __name__ == "__main__":
119
+ demo.launch(
120
+ server_name="0.0.0.0",
121
+ server_port=int(os.getenv("PORT", "7860")),
122
+ show_api=False,
123
+ )
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
pipeline.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NExT-GPT any-to-any pipeline for the Hugging Face Space.
2
+
3
+ Three modes:
4
+ offline - pure local placeholders, always works (no token / no network / CPU)
5
+ lite - Hugging Face serverless Inference API, one model per output modality
6
+ full - detects the official 7b_tiva_v0 weights and reports how to run them
7
+
8
+ IMPORTANT: offline / lite are *interface-level* reproductions of the NExT-GPT
9
+ data flow (modality signal tokens -> output projection -> diffusion decoders).
10
+ They do NOT load the paper's checkpoint. The weight-level reproduction lives in
11
+ ../reproduce/. See README.md in the submission root.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import os
18
+ import re
19
+ import struct
20
+ import sys
21
+ import tempfile
22
+ import time
23
+ import traceback
24
+ import wave
25
+ from dataclasses import asdict, dataclass, field
26
+ from typing import Any
27
+
28
+ # Matches upstream/NExT-GPT-Lagacy/code/config/base.yaml
29
+ NUM_SIGNAL_TOKENS = {"image": 4, "video": 24, "audio": 8}
30
+ SIGNAL_PREFIX = {"image": "IMG", "video": "VID", "audio": "AUD"}
31
+
32
+ TEXT_MODEL = os.getenv("NEXTGPT_TEXT_MODEL", "Qwen/Qwen2.5-7B-Instruct")
33
+ IMAGE_MODEL = os.getenv("NEXTGPT_IMAGE_MODEL", "black-forest-labs/FLUX.1-schnell")
34
+ AUDIO_MODEL = os.getenv("NEXTGPT_AUDIO_MODEL", "facebook/mms-tts-eng")
35
+ VIDEO_MODEL = os.getenv("NEXTGPT_VIDEO_MODEL", "Lightricks/LTX-Video")
36
+
37
+ SYSTEM_PROMPT = (
38
+ "You are NExT-GPT, an any-to-any multimodal LLM. Reply to the user in 1-2 "
39
+ "sentences, then output exactly two extra lines:\n"
40
+ "CAPTION: <a short English visual description for image/video diffusion>\n"
41
+ "AUDIO: <a short English sound description for audio diffusion>\n"
42
+ "No other text."
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class Result:
48
+ mode: str
49
+ text: str = ""
50
+ image: str | None = None
51
+ audio: str | None = None
52
+ video: str | None = None
53
+ signals: str = ""
54
+ log: list[dict[str, Any]] = field(default_factory=list)
55
+
56
+ def add(self, modality: str, status: str, detail: str, t0: float) -> None:
57
+ self.log.append(
58
+ {
59
+ "modality": modality,
60
+ "status": status,
61
+ "detail": detail[:400],
62
+ "seconds": round(time.time() - t0, 2),
63
+ }
64
+ )
65
+
66
+ def as_dict(self) -> dict[str, Any]:
67
+ return asdict(self)
68
+
69
+
70
+ def make_workdir() -> str:
71
+ return tempfile.mkdtemp(prefix="nextgpt_")
72
+
73
+
74
+ def signal_tokens(modalities: list[str]) -> str:
75
+ """Reproduce the modality signal tokens emitted by the Vicuna backbone."""
76
+ blocks = []
77
+ for m in modalities:
78
+ if m not in NUM_SIGNAL_TOKENS:
79
+ continue
80
+ p = SIGNAL_PREFIX[m]
81
+ n = NUM_SIGNAL_TOKENS[m]
82
+ blocks.append(f"**{m}**: " + " ".join(f"[{p}{i}]" for i in range(n)))
83
+ return "\n\n".join(blocks) if blocks else "(no output modality signal)"
84
+
85
+
86
+ def describe_inputs(prompt: str, image: Any, audio: Any, video: Any) -> str:
87
+ ins = ["text"]
88
+ for name, value in (("image", image), ("audio", audio), ("video", video)):
89
+ if value:
90
+ ins.append(name)
91
+ return ", ".join(ins)
92
+
93
+
94
+ # --------------------------------------------------------------------------- #
95
+ # offline generators (stdlib + Pillow + imageio-ffmpeg only)
96
+ # --------------------------------------------------------------------------- #
97
+ def offline_text(prompt: str, inputs: str, wanted: list[str]) -> str:
98
+ return (
99
+ "**[OFFLINE MODE] 离线管线占位输出,非模型推理结果**\n\n"
100
+ f"输入模态: {inputs}\n"
101
+ f"请求输出: {', '.join(wanted)}\n\n"
102
+ "NExT-GPT 三段式数据流已在本地完整走通:\n"
103
+ "1. 编码侧 ImageBind-Huge -> 输入投影层 -> language-like embeddings\n"
104
+ "2. Vicuna-7B v0 产生文本 token 与模态信号 token(见下方信号面板)\n"
105
+ "3. 输出投影层把信号表示映射到 SD v1-5 / ZeroScope v2_576w / AudioLDM-l-full\n\n"
106
+ "说明:本模式不加载任何权重,用占位素材验证 any-to-any 接口、信号 token 数量 "
107
+ "与四路输出绑定。权重复现见提交包 reproduce/ 目录。"
108
+ )
109
+
110
+
111
+ def offline_image(prompt: str, path: str) -> str:
112
+ from PIL import Image, ImageDraw
113
+
114
+ w, h = 512, 384
115
+ img = Image.new("RGB", (w, h))
116
+ px = img.load()
117
+ seed = sum(ord(c) for c in prompt) or 1
118
+ for y in range(h):
119
+ for x in range(w):
120
+ r = (60 + x * 120 // w + seed % 40) % 256
121
+ g = (80 + y * 130 // h + seed % 30) % 256
122
+ b = (130 + (x + y) * 90 // (w + h)) % 256
123
+ px[x, y] = (r, g, b)
124
+ d = ImageDraw.Draw(img)
125
+ d.rectangle((16, 16, w - 16, h - 16), outline=(255, 255, 255), width=2)
126
+ d.text((28, 28), "NExT-GPT OFFLINE PLACEHOLDER", fill=(255, 255, 255))
127
+ d.text((28, 48), "image diffusion = SD v1-5", fill=(255, 255, 255))
128
+ d.text((28, 66), "prompt hash = " + str(seed), fill=(255, 255, 255))
129
+ img.save(path)
130
+ return path
131
+
132
+
133
+ def offline_audio(prompt: str, path: str) -> str:
134
+ sr, dur = 22050, 2.5
135
+ seed = sum(ord(c) for c in prompt) or 1
136
+ base = 180 + seed % 120
137
+ with wave.open(path, "wb") as f:
138
+ f.setnchannels(1)
139
+ f.setsampwidth(2)
140
+ f.setframerate(sr)
141
+ frames = bytearray()
142
+ for i in range(int(sr * dur)):
143
+ t = i / sr
144
+ env = min(1.0, t * 4, (dur - t) * 4)
145
+ s = (
146
+ 0.45 * math.sin(2 * math.pi * base * t)
147
+ + 0.25 * math.sin(2 * math.pi * base * 1.5 * t)
148
+ + 0.15 * math.sin(2 * math.pi * base * 2 * t)
149
+ )
150
+ frames += struct.pack("<h", int(max(-1.0, min(1.0, s * env)) * 24000))
151
+ f.writeframes(frames)
152
+ return path
153
+
154
+
155
+ def offline_video(prompt: str, path: str) -> str:
156
+ """Write a real mp4 without a system ffmpeg binary."""
157
+ import numpy as np
158
+ import imageio_ffmpeg as iio
159
+
160
+ w, h, fps, frames_n = 320, 240, 8, 24
161
+ seed = sum(ord(c) for c in prompt) or 1
162
+ writer = iio.write_frames(
163
+ path,
164
+ (w, h),
165
+ fps=fps,
166
+ codec="libx264",
167
+ quality=6,
168
+ macro_block_size=1,
169
+ )
170
+ writer.send(None)
171
+ yy, xx = np.mgrid[0:h, 0:w]
172
+ for k in range(frames_n):
173
+ phase = 2 * math.pi * k / frames_n
174
+ r = np.clip(60 + 90 * (xx / w) + 60 * np.sin(phase + yy / 40 + seed % 7), 0, 255)
175
+ g = np.clip(70 + 90 * (yy / h) + 60 * np.cos(phase + xx / 50), 0, 255)
176
+ b = np.clip(120 + 70 * np.sin(phase * 2 + (xx + yy) / 90), 0, 255)
177
+ frame = np.stack([r, g, b], axis=-1).astype(np.uint8)
178
+ writer.send(frame.tobytes())
179
+ writer.close()
180
+ return path
181
+
182
+
183
+ def run_offline(prompt: str, wanted: list[str], inputs: str, workdir: str) -> Result:
184
+ r = Result(mode="offline", signals=signal_tokens(wanted))
185
+ r.text = offline_text(prompt, inputs, wanted)
186
+ for m in wanted:
187
+ t0 = time.time()
188
+ try:
189
+ if m == "image":
190
+ r.image = offline_image(prompt, os.path.join(workdir, "image.png"))
191
+ elif m == "audio":
192
+ r.audio = offline_audio(prompt, os.path.join(workdir, "audio.wav"))
193
+ elif m == "video":
194
+ r.video = offline_video(prompt, os.path.join(workdir, "video.mp4"))
195
+ else:
196
+ continue
197
+ r.add(m, "ok", "offline placeholder generated", t0)
198
+ except Exception as exc: # keep the other modalities alive
199
+ r.add(m, "error", f"{type(exc).__name__}: {exc}", t0)
200
+ return r
201
+
202
+
203
+ # --------------------------------------------------------------------------- #
204
+ # lite mode: HF serverless inference, one call per modality
205
+ # --------------------------------------------------------------------------- #
206
+ def _build_client() -> Any:
207
+ from huggingface_hub import InferenceClient
208
+
209
+ token = os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
210
+ return InferenceClient(token=token, timeout=90)
211
+
212
+
213
+ def _plan_from_text(text: str, prompt: str) -> tuple[str, str]:
214
+ cap = re.search(r"CAPTION:\s*(.+)", text)
215
+ aud = re.search(r"AUDIO:\s*(.+)", text)
216
+ clean = lambda s: (s.group(1).strip()[:180] if s else "")
217
+ caption = clean(cap) or prompt.strip()[:180] or "a calm landscape at sunrise"
218
+ audio = clean(aud) or caption
219
+ tts = re.sub(r"[^A-Za-z0-9 ,.'!?-]", " ", audio)[:180]
220
+ return caption, tts
221
+
222
+
223
+ def _save_image(obj: Any, path: str) -> str:
224
+ from PIL import Image
225
+
226
+ if isinstance(obj, Image.Image):
227
+ obj.convert("RGB").save(path)
228
+ elif isinstance(obj, (bytes, bytearray)):
229
+ with open(path, "wb") as f:
230
+ f.write(bytes(obj))
231
+ else:
232
+ raise TypeError(f"unexpected text_to_image return type: {type(obj)}")
233
+ return path
234
+
235
+
236
+ def run_lite(prompt: str, wanted: list[str], inputs: str, workdir: str) -> Result:
237
+ r = Result(mode="lite", signals=signal_tokens(wanted))
238
+ try:
239
+ client = _build_client()
240
+ except Exception as exc:
241
+ r.add("client", "error", f"{type(exc).__name__}: {exc}", time.time())
242
+ r.add("all", "fallback", "InferenceClient unavailable; offline placeholders used", time.time())
243
+ return _fill_missing(r, prompt, wanted, workdir)
244
+
245
+ caption, tts = prompt.strip()[:180], prompt.strip()[:180]
246
+ if "text" in wanted:
247
+ t0 = time.time()
248
+ try:
249
+ resp = client.chat_completion(
250
+ messages=[
251
+ {"role": "system", "content": SYSTEM_PROMPT},
252
+ {"role": "user", "content": prompt},
253
+ ],
254
+ model=TEXT_MODEL,
255
+ max_tokens=220,
256
+ )
257
+ text = resp.choices[0].message.content or ""
258
+ r.text = text
259
+ caption, tts = _plan_from_text(text, prompt)
260
+ r.add("text", "ok", f"chat_completion via {TEXT_MODEL}", t0)
261
+ except Exception as exc:
262
+ r.text = (
263
+ "[lite] 文本生成失败,已降级为离线占位。\n"
264
+ f"原因: {type(exc).__name__}: {exc}\n\n" + offline_text(prompt, inputs, wanted)
265
+ )
266
+ r.add("text", "fallback", f"{type(exc).__name__}: {exc}", t0)
267
+ else:
268
+ r.text = "(text output disabled)"
269
+
270
+ tasks = [
271
+ ("image", IMAGE_MODEL),
272
+ ("audio", AUDIO_MODEL),
273
+ ("video", VIDEO_MODEL),
274
+ ]
275
+ for m, model in tasks:
276
+ if m not in wanted:
277
+ continue
278
+ t0 = time.time()
279
+ try:
280
+ if m == "image":
281
+ obj = client.text_to_image(caption, model=model)
282
+ r.image = _save_image(obj, os.path.join(workdir, "image.png"))
283
+ elif m == "audio":
284
+ # TTS stands in for AudioLDM diffusion audio on serverless API.
285
+ data = client.text_to_speech(tts or caption, model=model)
286
+ path = os.path.join(workdir, "audio.wav")
287
+ with open(path, "wb") as f:
288
+ f.write(data if isinstance(data, (bytes, bytearray)) else bytes(data))
289
+ r.audio = path
290
+ else:
291
+ fn = getattr(client, "text_to_video", None)
292
+ if fn is None:
293
+ raise RuntimeError("InferenceClient has no text_to_video method")
294
+ data = fn(caption, model=model)
295
+ path = os.path.join(workdir, "video.mp4")
296
+ with open(path, "wb") as f:
297
+ f.write(data if isinstance(data, (bytes, bytearray)) else bytes(data))
298
+ r.video = path
299
+ r.add(m, "ok", f"via {model}", t0)
300
+ except Exception as exc:
301
+ r.add(m, "fallback", f"{type(exc).__name__}: {exc}; offline placeholder used", t0)
302
+ try:
303
+ if m == "image":
304
+ r.image = offline_image(prompt, os.path.join(workdir, "image.png"))
305
+ elif m == "audio":
306
+ r.audio = offline_audio(prompt, os.path.join(workdir, "audio.wav"))
307
+ elif m == "video":
308
+ r.video = offline_video(prompt, os.path.join(workdir, "video.mp4"))
309
+ except Exception as exc2:
310
+ r.add(m, "error", f"offline fallback failed: {exc2}", t0)
311
+ return r
312
+
313
+
314
+ def _fill_missing(r: Result, prompt: str, wanted: list[str], workdir: str) -> Result:
315
+ r.text = r.text or offline_text(prompt, "", wanted)
316
+ for m, gen, name in (
317
+ ("image", offline_image, "image.png"),
318
+ ("audio", offline_audio, "audio.wav"),
319
+ ("video", offline_video, "video.mp4"),
320
+ ):
321
+ if m in wanted:
322
+ try:
323
+ path = gen(prompt, os.path.join(workdir, name))
324
+ setattr(r, m, path)
325
+ except Exception as exc:
326
+ r.add(m, "error", str(exc), time.time())
327
+ return r
328
+
329
+
330
+ # --------------------------------------------------------------------------- #
331
+ # full mode: official weights (GPU machine, not the free CPU Space)
332
+ # --------------------------------------------------------------------------- #
333
+ def run_full(prompt: str, wanted: list[str], inputs: str, workdir: str) -> Result:
334
+ root = os.getenv("NEXTGPT_ROOT", "").strip()
335
+ ckpt = os.getenv("NEXTGPT_CKPT", "").strip()
336
+ ckpt_file = os.path.join(ckpt, "pytorch_model.pt") if ckpt else ""
337
+ r = Result(mode="full", signals=signal_tokens(wanted))
338
+ ready = bool(root and ckpt_file and os.path.isfile(ckpt_file))
339
+ if not ready:
340
+ r.text = (
341
+ "**[FULL MODE] 未检测到官方权重**\n\n"
342
+ f"NEXTGPT_ROOT = {root or '(unset)'}\n"
343
+ f"NEXTGPT_CKPT = {ckpt or '(unset)'}\n\n"
344
+ "官方 7b_tiva_v0 约需 30-40 GB 显存,无法在免费 CPU Space 内加载。"
345
+ "请在 GPU 机器按提交包 reproduce/ 的步骤准备权重,然后运行:\n\n"
346
+ "```bash\ncd upstream/NExT-GPT-Lagacy/code && bash scripts/app.sh\n```\n\n"
347
+ "本 Space 的 offline / lite 模式用于展示同一 any-to-any 接口与信号 token 机制。"
348
+ )
349
+ r.add("weights", "unavailable", "NEXTGPT_ROOT / NEXTGPT_CKPT not configured", time.time())
350
+ return _fill_missing(r, prompt, wanted, workdir)
351
+
352
+ # Weight-level inference is delegated to the upstream demo_app.py. That
353
+ # script owns the NextGPTModel graph, diffusion decoders and generation loop.
354
+ try:
355
+ code_dir = os.path.join(root, "code")
356
+ sys.path.insert(0, code_dir)
357
+ from model.anyToImageVideoAudio import NextGPTModel # noqa: F401
358
+ import torch # noqa: F401
359
+
360
+ r.text = (
361
+ "**[FULL MODE] 权重已检测到**\n\n"
362
+ f"checkpoint: {ckpt_file}\n\n"
363
+ "NextGPTModel 可在 GPU 环境加载。为避免在 Web 进程内重复实现官方 20+ 参数的 "
364
+ "generate 循环,请直接使用官方 Gradio demo:\n\n"
365
+ "```bash\ncd upstream/NExT-GPT-Lagacy/code && bash scripts/app.sh\n```"
366
+ )
367
+ r.add("weights", "ok", f"found {ckpt_file}; NextGPTModel import succeeded", time.time())
368
+ except Exception as exc:
369
+ r.text = (
370
+ f"**[FULL MODE] 权重存在但依赖未就绪**: {type(exc).__name__}: {exc}\n\n"
371
+ "需 PyTorch 1.13.1 + CUDA 11.6 + 官方 legacy requirements.txt。"
372
+ )
373
+ r.add("weights", "error", traceback.format_exc(limit=2), time.time())
374
+ return _fill_missing(r, prompt, wanted, workdir)
375
+
376
+
377
+ def run(
378
+ mode: str,
379
+ prompt: str,
380
+ wanted: list[str],
381
+ image: Any = None,
382
+ audio: Any = None,
383
+ video: Any = None,
384
+ ) -> Result:
385
+ prompt = (prompt or "").strip() or "Describe a calm sunrise over the sea and compose music for it."
386
+ wanted = [m for m in (wanted or []) if m in ("text", "image", "audio", "video")]
387
+ inputs = describe_inputs(prompt, image, audio, video)
388
+ workdir = make_workdir()
389
+ if mode == "lite":
390
+ return run_lite(prompt, wanted, inputs, workdir)
391
+ if mode == "full":
392
+ return run_full(prompt, wanted, inputs, workdir)
393
+ return run_offline(prompt, wanted, inputs, workdir)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.44.0,<6.0.0
2
+ huggingface_hub>=0.24.0
3
+ Pillow>=9.5.0
4
+ numpy>=1.24.0
5
+ imageio-ffmpeg>=0.4.9