194130157a commited on
Commit
61d6621
·
verified ·
1 Parent(s): d3121f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +483 -0
app.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import subprocess
4
+ import re
5
+ import time
6
+ import zipfile
7
+ import json
8
+ import shutil
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+
11
+ # 1. 自动安装依赖
12
+ def ensure_dependencies():
13
+ try:
14
+ import gradio
15
+ import requests
16
+ except ImportError:
17
+ # 确保安装所需库
18
+ print("Installing required packages: gradio, requests...")
19
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "gradio", "requests"])
20
+
21
+ ensure_dependencies()
22
+
23
+ import gradio as gr
24
+ import requests
25
+
26
+ # ================= 默认配置 =================
27
+ # 1. 文本/思考专用 Key (架构师 + 导演)
28
+ DEFAULT_LLM_API_KEY = "sk-DZ5g7Zu0lFDlR7mBkbNsZLFTt1KBqA8ocsAH1mcvsZDWtydx"
29
+ # 2. 视频生成专用 Key (Veo 渲染) -> [新增]
30
+ DEFAULT_VIDEO_API_KEY = "sk-G6LN0uC2BVclZjx1ObDJPkMZTZvtjau1Ss7GjCvRLJyI5euU"
31
+
32
+ MERCHANT_BASE_URL = "https://xingjiabiapi.com"
33
+ VEO_MODEL = "veo_3_1-fast"
34
+ VIDEO_SIZE = "16x9"
35
+ TEXT_MODEL = "gemini-3-pro-preview-thinking"
36
+
37
+ # ===============================================
38
+ # --- 角色1:首席工艺工程师 (The Chief Process Engineer) ---
39
+ # ===============================================
40
+ DEFAULT_ARCHITECT_PROMPT = """
41
+ 你是一家顶级工厂的**首席工艺工程师 (Chief Process Engineer)**。
42
+ 你**完全不懂**电影制作,你的唯一职责是设计一条**“逻辑严密、设备真实、物理过程详尽”**的工业生产线。
43
+
44
+ **你的任务:**
45
+ 为指定产品设计一份《全生命周期工艺说明书》(Full Lifecycle Process Protocol)。
46
+
47
+ **⚠️ 工程师铁律 (Engineering Laws):**
48
+ 1. **全链路覆盖 (Full Lifecycle Scope)**:
49
+ * **起点必须是源头**:严禁只从工厂门口写起。必须包含**“原材料获取 (Acquisition)”**(例如:果园采摘、矿山开采、原木砍伐)。
50
+ * **终点必须是成品**:必须包含**“最终成品形态 (Final Product)”**(例如:装瓶、装箱、码垛完成)。
51
+ 2. **物理真实性**:必须使用真实的工业设备名称(如:Harvester, Hammer Mill, Optical Sorter)。
52
+ 3. **流程闭环**:Step N 的输出必须是 Step N+1 的输入。严禁逻辑断层。
53
+ 4. **微观物理描述**:你必须详细描述原料在每一道工序中发生了什么**物理或化学变化**。
54
+ * *Input State*: 进入机器前的状态。
55
+ * *Mechanism*: 机器施加的力。
56
+ * *Output State*: 离开机器后的状态。
57
+
58
+ **流程结构要求 (Standard Operating Procedure)**:
59
+ 请列出 **30-40 个关键工序**(为了满足200个镜头的细节支撑,工序必须足够细致),必须严格涵盖以下四个物理阶段:
60
+ 1. **Raw Material Acquisition (源头获取)**: 采摘、开采、收割。
61
+ 2. **Preprocessing (预处理)**: 运输、清洗、去皮、除杂、分拣。
62
+ 3. **Core Processing (核心加工)**: 改变物质形态的关键步骤(粉碎、混合、加热、成型、装配)。**这是物理变化的中心。**
63
+ 4. **Final Packaging (成品封装)**: 灌装/装箱、贴标、封箱、码垛入库。
64
+
65
+ **输出格式 (严禁修改)**:
66
+ 请输出一份技术列表,不要写成剧本。
67
+
68
+ Step [序号] | [工序名称]
69
+ * **Equipment**: [真实机器名称]
70
+ * **Physics Input**: [原料进入时的状态]
71
+ * **Mechanism**: [机器运作原理与物理动作描述]
72
+ * **Physics Output**: [原料离开时的物理变化结果]
73
+ """
74
+
75
+ # ===============================================
76
+ # --- 角色2:IMAX 细节狂魔导演 (Director & Editor) ---
77
+ # --- 核心修改:200+长视频节奏 + 10%前奏限制 + 史诗开篇 ---
78
+ # ===============================================
79
+ DEFAULT_DIRECTOR_PROMPT = """
80
+ 你是一位追求**“极致真实与细节”**的 IMAX 纪录片导演,同时也是一位**金牌剪辑师**。
81
+ 你拿到了一份由“首席工程师”编写的枯燥《工艺说明书》。
82
+ 你的任务是:**基于这份技术文档,通过“剪辑配比”和“视觉转译”,生成一部节奏完美的“解压沉浸式 (Decompressive Immersion)”长视频工业大片脚本。**
83
+
84
+ **⚠️ 优先级说明:以下【五大终极死令】拥有最高优先级,必须 100% 执行!⚠️**
85
+
86
+ **💀 死令一:长视频剪辑配比与节奏法则 (The Long-Form Editorial Ratio) [★核心节奏控制★]**
87
+ * **背景**:这部视频总长度将超过 **200个8秒镜头**。你必须精细规划节奏,防止观众疲劳。
88
+ * **强制执行 (10-90 Rule)**:
89
+ * **Phase A: 史诗开篇与物流 (The Epic Intro & Logistics)**:[**严格限制在总量的 10% 以内**]
90
+ * **开篇要求**:原材料采集(Acquisition)必须是**“大片级解压沉浸”**。
91
+ * *❌ 拒绝*:普通的果农摘果子。
92
+ * *✅ 必须*:宏大的机械收割阵列、慢动作果实坠落特写、极致的自然光影。让观众前3秒就起鸡皮疙瘩。
93
+ * **物流压缩**:运输和卸货要快、准、狠。不要在路上浪费时间。
94
+ * **Phase B: 极致沉浸核心区 (The Deep Immersion Core)**:[**必须占据总量的 90% 以上**]
95
+ * 核心加工环节(切、碎、炸、流)是绝对主角。**无限膨胀**这些步骤。
96
+
97
+ **💀 死令二:架构微观膨胀法则 (The Law of Architectural Expansion) [★长视频填充术★]**
98
+ * **原则**:为了填满 200+ 个镜头,工程师的一个 `Step` 必须被极度展开。
99
+ * **强制执行**:
100
+ * **核心步骤 (Core Processing)**:必须**膨胀**为 4-6 个连续的 `Shots` (Entry -> Process Slow-mo -> Highlight Detail -> Exit)。
101
+ * **非核心步骤**:用 1-2 个镜头交代。
102
+
103
+ **💀 死令三:三段式微观动作拆解 (The Tri-Phase Action Protocol) [★拒绝原子化★]**
104
+ * **原则**:对于任何核心物理处理,必须拆解为 **Entry -> Process -> Exit**。
105
+ * **强制执行**:
106
+ * **Phase 1 (Entry/Impact)**: 交代**“进入/倾泻”**。例如:原料**倾倒**进机器。
107
+ * **Phase 2 (Process/Turmoil)**: 交代**“作用/剧变”**。例如:刀片**高速旋转**,原料被**瞬间切碎**,汁液/火花飞溅。
108
+ * **Phase 3 (Exit/Transfer)**: 交代**“撤出/结果”**。例如:成品被传送带**带离**,进入下一环。
109
+
110
+ **💀 死令四:X光负载锁定与防空车 (Visual Load Enforcement) [★拒绝空车BUG★]**
111
+ * **原则**:解决“车辆/容器到站变空”的逻辑断层。
112
+ * **强制执行**:在描述“车辆到达”、“倒车入库”或“停靠”时,**严禁**只写车辆外观。
113
+ * **必须包含动作**:Prompt 必须包含 **"The rear doors SWING OPEN to reveal the massive cargo inside."** (车门打开露出货物)。
114
+
115
+ **💀 死令五:绝对状态继承与防回退 (Absolute State Inheritance) [★拒绝物体复原★]**
116
+ * **原则**:Veo 看不见上一条视频。你必须在 Prompt 开头显式描述“上一个镜头造成的改变”。
117
+ * **形容词前置锁死**:
118
+ * ❌ 严禁写 "The apple" -> 必须写 "The **SLICED and CUBED** apple pieces"。
119
+ * ❌ 严禁写 "The truck" -> 必须写 "The **HEAVILY LOADED** truck"。
120
+ * **动势接龙**:Shot N 的 **(Start_Frame_Visual)** 必须完美衔接 Shot N-1 的结束画面。
121
+
122
+ # ---------------------------------------------------------------------
123
+ # 导演执行手册:常规铁律 (The Execution Manual)
124
+ # ---------------------------------------------------------------------
125
+
126
+ **🔥 铁律一:解压沉浸流派的极致执行 (The Execution of Decompressive Immersion)**
127
+ 根据工程师描述的物理动作,必须分配并执行以下流派:
128
+ * **[SLICE] (切削沉浸)**:侧面微距,展示阻力与丝滑。
129
+ * **[CRUSH] (破坏沉浸)**:慢动作,展示崩裂与形变。
130
+ * **[PEEL] (剥离沉浸)**:拉伸运镜,展示反光。
131
+ * **[FLOW] (流体沉浸)**:高光特写,展示粘稠无气泡。
132
+ * **[CLEAN] (净化沉浸)**:对比运镜,展示污渍剥离。
133
+ * **[SYNC] (循环沉浸)**:阵列同步,展示宏大规模。
134
+
135
+ **🔥 铁律二:视觉内容铁律**
136
+ 1. **绝对饱和密度 (Absolute Saturation)**:拒绝留白。产品必须**铺满屏幕 (Edge-to-Edge)**。
137
+ 2. **暴力冗余 (Brute-Force Redundancy)**:**严禁代词**。必须在每个镜头里**全称复述主语及其状态**。
138
+
139
+ **🔥 铁律三:逻辑与连贯性铁律**
140
+ 3. **剪辑思维**:使用“Continuing the motion...”桥接。
141
+ 4. **场景一致性**:同一阶段环境描述必须**复制粘贴**。
142
+
143
+ # ==================== 输出格式 (严禁修改) ====================
144
+ 请严格按照以下格式生成脚本。**格式已包含状态继承、三段式检查与逻辑负载检查。**
145
+
146
+ Shot [序号]/[总数] | [中文标题-用于文件名]
147
+ Sora Prompt (English): (Action_Phase): [CRITICAL CHECK: Entry/Process/Exit? ENFORCE 3-SHOT RULE] (Start_Frame_Visual): [Visual Bridge from prev shot. IF TRUCK ARRIVAL -> DOORS OPEN REVEALING CARGO] (Object_State_Adjectives): [MANDATORY: Sliced/Crushed/Liquid/Packed - DO NOT USE RAW NOUNS] (Engineering_Source): [Ref Step # from Engineer] (Satisfaction_Genre): [SLICE/CRUSH/FLOW/SYNC/PEEL/FIT/CLEAN - DIRECTOR DECIDES] (Execution_Focus): [Macro Resistance/Glossy Flow/Zero Error Sync...] (Scene_Environment): [LOCKED CONSISTENT DESCRIPTION] (Visual_Action_Trajectory): [DETAILED: Start -> Arc -> Impact -> Release. RE-STATE SUBJECT FULLY.] (Screen_Density): [Edge-to-Edge Filling/Infinite Array] (Audio_Decompressive_Immersion): [Specific Mechanical Sound, NO MUSIC] (Asset_Consistency): [Repeat Product Description] (Human_Interaction): [Hands retracting/Eyes monitoring/Sterile Suit]
148
+ """
149
+
150
+ # ===============================================
151
+
152
+ def generate_process_architecture(topic, api_key, architect_prompt):
153
+ """阶段一:生成工艺说明书 (使用 LLM Key)"""
154
+ if not topic: return "❌ 请先输入产品名称"
155
+ if not api_key: return "❌ 请先输入 LLM API Key"
156
+
157
+ print(f"🧠 [{TEXT_MODEL}] 正在构建《{topic}》的全生命周期工艺流程...")
158
+
159
+ user_content = f"""
160
+ Design a rigorous, physically accurate Full Lifecycle Industrial Process Protocol for: {topic}.
161
+
162
+ ROLE: You are the Chief Process Engineer.
163
+ GOAL: Create a technical blueprint covering Raw Material Acquisition -> Final Product.
164
+
165
+ REQUIREMENTS:
166
+ 1. **Scope**: MUST Start from **Source Acquisition** (Harvesting/Mining) -> End at **Final Packaging**.
167
+ 2. **Logic**: Step-by-step physical transformation. No gaps.
168
+ 3. **Equipment**: Use real industrial machine names.
169
+ 4. **Objective Reality**: Describe the process objectively. No camera angles.
170
+ """
171
+
172
+ url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
173
+ headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key.strip()}"}
174
+ data = {
175
+ "model": TEXT_MODEL,
176
+ "messages": [
177
+ {"role": "system", "content": architect_prompt},
178
+ {"role": "user", "content": user_content}
179
+ ],
180
+ "temperature": 0.5,
181
+ "max_tokens": 4096
182
+ }
183
+
184
+ try:
185
+ response = requests.post(url, headers=headers, json=data, timeout=240)
186
+ if response.status_code == 200:
187
+ return response.json()['choices'][0]['message']['content']
188
+ else:
189
+ return f"Error: {response.text}"
190
+ except Exception as e:
191
+ return f"Request Failed: {e}"
192
+
193
+ def generate_script_batch(topic, architecture, start_shot, end_shot, total_shots, system_prompt, api_key):
194
+ """阶段二:分批循环生成脚本 (使用 LLM Key)"""
195
+
196
+ print(f"🔄 正在生成分镜 {start_shot} - {end_shot} ...")
197
+
198
+ user_content = f"""
199
+ Product: {topic}
200
+ Engineering Blueprint Reference:
201
+ {architecture}
202
+
203
+ Task: Generate ONLY shots #{start_shot} to #{end_shot} (out of {total_shots} total).
204
+
205
+ IMPORTANT CONTEXT:
206
+ * You are the IMAX DIRECTOR & EDITOR.
207
+ * This is a LONG-FORM video ({total_shots} shots total).
208
+ * **GOAL**: Create "Decompressive Immersion" visuals.
209
+
210
+ CRITICAL INSTRUCTIONS:
211
+ 1. **APPLY THE 10% RULE**:
212
+ - IF this batch is part of the first 10% ({int(total_shots*0.1)} shots): Focus on **BLOCKBUSTER ACQUISITION** (Harvesting/Mining). Make it EPIC but FAST (Total Acquisition+Logistics <= 10%).
213
+ - IF this batch is past the first 10%: Focus on **CORE PROCESSING**. Expand every step massively.
214
+ 2. **TRI-PHASE PROTOCOL**: For core steps, you MUST use Entry->Process->Exit.
215
+ 3. **VISUAL CONTINUITY**: Fix any logic gaps.
216
+ 4. **DENSITY**: Edge-to-Edge Filling.
217
+ 5. **AUDIO**: Only use "Decompressive Immersion" sounds.
218
+ """
219
+
220
+ url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
221
+ headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key.strip()}"}
222
+ data = {
223
+ "model": TEXT_MODEL,
224
+ "messages": [
225
+ {"role": "system", "content": system_prompt},
226
+ {"role": "user", "content": user_content}
227
+ ],
228
+ "temperature": 0.7,
229
+ "max_tokens": 64000 # [核心修改] 取消限制!设置极大值以确保一次生成大量内容不截断
230
+ }
231
+
232
+ try:
233
+ response = requests.post(url, headers=headers, json=data, timeout=360)
234
+ if response.status_code == 200:
235
+ return response.json()['choices'][0]['message']['content']
236
+ else:
237
+ return None
238
+ except Exception as e:
239
+ return None
240
+
241
+ def step2_generate_script(topic, architecture, count, system_prompt, api_key):
242
+ """阶段二:分批循环生成脚本 (使用 LLM Key)"""
243
+ if not architecture: return "❌ 请先生成并确认工艺架构", None
244
+ if not api_key: return "❌ 请先输入 LLM API Key", None
245
+
246
+ logs = [f"🚀 [任务启动] 目标: 生成 {count} 个 IMAX 级分镜脚本...", "------------------------------------------------"]
247
+ yield "\n".join(logs), None
248
+
249
+ full_script_text = ""
250
+ # 根据用户要求,虽然代码支持分批,但因为Token限制已取消,实际上LLM可能一次性输出很多。
251
+ # 这里保持逻辑不变,但确保 prompt 里的 token 足够大。
252
+ batch_size = 10
253
+ total_batches = (count + batch_size - 1) // batch_size
254
+ MAX_RETRIES = 3
255
+
256
+ for i in range(total_batches):
257
+ start_num = i * batch_size + 1
258
+ end_num = min((i + 1) * batch_size, count)
259
+ batch_success = False
260
+
261
+ for attempt in range(MAX_RETRIES):
262
+ if attempt == 0:
263
+ logs.append(f"🔵 [Batch {i+1}/{total_batches}] 正在初始化 Shot {start_num}-{end_num}...")
264
+ yield "\n".join(logs), full_script_text
265
+ time.sleep(0.5)
266
+ logs.append(f"🧠 [导演思维] 正在回溯上文并应用【死令】(10%开篇 / 三段式 / 负载锁定)...")
267
+ yield "\n".join(logs), full_script_text
268
+ logs.append(f"📡 [云端通讯] 正在请求 Thinking 模型撰写剧本 (使用 LLM Key)...")
269
+ yield "\n".join(logs), full_script_text
270
+ else:
271
+ logs.append(f"⚠️ [网络重试] 第 {i+1} 批次生成失败,正在进行第 {attempt+1}/{MAX_RETRIES} 次重试...")
272
+ yield "\n".join(logs), full_script_text
273
+
274
+ # 使用传入的 api_key (即 LLM Key)
275
+ batch_script = generate_script_batch(topic, architecture, start_num, end_num, count, system_prompt, api_key)
276
+
277
+ if batch_script and len(batch_script) > 100:
278
+ full_script_text += f"\n{batch_script}\n"
279
+ logs.append(f"✅ [成功] 第 {i+1} 批次脚本已写入内存。")
280
+ logs.append("------------------------------------------------")
281
+ batch_success = True
282
+ yield "\n".join(logs), full_script_text
283
+ break
284
+ else:
285
+ logs.append(f"❌ [失败] 返回数据为空或格式错误。等待冷却...")
286
+ yield "\n".join(logs), full_script_text
287
+ time.sleep(2)
288
+
289
+ if not batch_success:
290
+ return "\n".join(logs) + "\n❌❌❌ [严重错误] 任务熔断停止。", full_script_text
291
+
292
+ prompts_data = extract_prompts_with_titles(full_script_text)
293
+ logs.append(f"\n🎉 [全部完成] 脚本生成完毕!共解析出 {len(prompts_data)} 个有效镜头。")
294
+ logs.append(f"👉 准备进入第三步渲染 (将使用 Video API Key)。")
295
+ return "\n".join(logs), full_script_text
296
+
297
+ def extract_prompts_with_titles(script_text):
298
+ """提取 Prompt 和 标题 (支持 Markdown)"""
299
+ if not script_text: return []
300
+ pattern = r"(?:[\*\#]*\s*)Shot\s+(\d+).*?\|\s*([^\n]+).*?Sora Prompt \(English\):\s*(.*?)(?=\n\s*(?:[\*\#]*\s*)Shot|::END::|$)"
301
+ matches = re.findall(pattern, script_text, re.DOTALL | re.IGNORECASE)
302
+ results = []
303
+ for shot_num, title, content in matches:
304
+ clean_title = title.replace("**", "").replace("##", "").strip()
305
+ safe_title = re.sub(r'[\\/*?:"<>|]', "", clean_title).strip().replace(" ", "_")
306
+ if len(safe_title) > 40: safe_title = safe_title[:40]
307
+ filename_base = f"Shot_{int(shot_num):03d}_{safe_title}"
308
+ clean_p = content.replace("\n", " ").replace("**", "").replace("##", "").strip()
309
+ clean_p = re.sub(r'\s+', ' ', clean_p)
310
+ if len(clean_p) > 10:
311
+ results.append({"filename": filename_base, "prompt": clean_p})
312
+ return results
313
+
314
+ def generate_single_video_task(prompt, filename_base, save_dir, video_api_key, topic):
315
+ """生成单视频:使用 VIDEO API KEY"""
316
+ if not prompt: return None
317
+ clean_prompt = prompt.replace("--ar 16:9", "").replace("16:9", "")
318
+ final_prompt = (
319
+ f"Wide screen 16x9 video. {topic} manufacturing documentary blockbuster. "
320
+ f"**BBC/Discovery Style, Hyper-Realistic, 8K, No Sci-Fi.** "
321
+ f"**Ultimate Decompressive Immersion, Massive Screen Density, Edge-to-Edge Filling.** "
322
+ f"**Editorial Continuity, Smooth Transitions, Perfect Loop.** "
323
+ f"**Completed Action Trajectory, Object Lands Successfully.** "
324
+ f"**Pure Diegetic Audio, No Music, Decompressive Immersion Sounds.** "
325
+ f"**Extremely Detailed Texture, Physics-based Motion, Human-Machine Collaboration.** "
326
+ f"{clean_prompt} --ar 16x9"
327
+ )
328
+ url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
329
+ # === 核心修改:使用 video_api_key ===
330
+ headers = {"Content-Type": "application/json", "Authorization": f"Bearer {video_api_key.strip()}"}
331
+ data = {
332
+ "model": VEO_MODEL,
333
+ "messages": [{"role": "user", "content": final_prompt}],
334
+ "stream": False, "size": VIDEO_SIZE, "seconds": 8, "aspect_ratio": "16:9"
335
+ }
336
+ fname = f"{filename_base}.mp4"
337
+ save_path = os.path.join(save_dir, fname)
338
+ try:
339
+ resp = requests.post(url, headers=headers, json=data, timeout=300)
340
+ if resp.status_code != 200: return {"status": "error", "msg": f"[{filename_base}] ❌ API Error: {resp.status_code}"}
341
+ try:
342
+ content = resp.json()['choices'][0]['message']['content']
343
+ url_match = re.search(r'(https?://[^\s)"]+)', content)
344
+ if not url_match: return {"status": "error", "msg": f"[{filename_base}] ❌ No URL found"}
345
+ vid_data = requests.get(url_match.group(1).split(')')[0]).content
346
+ with open(save_path, "wb") as f: f.write(vid_data)
347
+ return {"status": "success", "file": save_path, "msg": f"✅ [渲染成功] {fname}"}
348
+ except Exception as e: return {"status": "error", "msg": f"[{filename_base}] ❌ Parse Error: {e}"}
349
+ except Exception as e: return {"status": "error", "msg": f"[{filename_base}] ❌ Network Error: {e}"}
350
+
351
+ def step3_generate_videos(topic, script_text, video_api_key, progress=gr.Progress()):
352
+ """阶段三:批量生成视频 (传入 Video API Key)"""
353
+ if not script_text: yield "❌ 脚本内容为空,请先执行第二步", None, None; return
354
+ if not video_api_key: yield "❌ 请先输入 Video API Key", None, None; return
355
+
356
+ timestamp = int(time.time())
357
+ safe_topic = re.sub(r'[\\/*?:"<>|]', "", topic).replace(" ", "_") if topic else "Untitled"
358
+ base_dir = "AutoSaved_Videos"
359
+ session_dir = os.path.join(base_dir, f"{safe_topic}_{timestamp}")
360
+ os.makedirs(session_dir, exist_ok=True)
361
+
362
+ logs = [f"🚀 [渲染启动] 开始批量生成视频 (使用 Veo 专用 Key)...", f"📂 归档目录: {os.path.abspath(session_dir)}"]
363
+ yield "\n".join(logs), None, None
364
+
365
+ with open(os.path.join(session_dir, "script.txt"), "w", encoding="utf-8") as f:
366
+ f.write(script_text)
367
+
368
+ prompts_data = extract_prompts_with_titles(script_text)
369
+ if not prompts_data:
370
+ logs.append("❌ 脚本格式解析失败,未找到有效 Prompt"); yield "\n".join(logs), None, None; return
371
+
372
+ logs.append(f"🎥 任务队列建立完成:共 {len(prompts_data)} 个镜头。正在向 Veo 发送并发请求...")
373
+ yield "\n".join(logs), None, None
374
+
375
+ work_list = prompts_data
376
+ generated_files = []
377
+
378
+ # [核心修改] 确保一次性提交所有视频 (max_workers=len(work_list))
379
+ # 只要系统资源允许,这将同时发起 200 个请求
380
+ with ThreadPoolExecutor(max_workers=len(work_list)) as executor:
381
+ futures = {
382
+ # === 核心修改:传入 video_api_key ===
383
+ executor.submit(generate_single_video_task, item['prompt'], item['filename'], session_dir, video_api_key, topic): item['filename']
384
+ for item in work_list
385
+ }
386
+
387
+ completed = 0
388
+ for future in as_completed(futures):
389
+ res = future.result()
390
+ completed += 1
391
+ progress(completed/len(work_list), desc=f"渲染中 {completed}/{len(work_list)}")
392
+ if res:
393
+ if res['status'] == 'success':
394
+ logs.append(f"✅ [{completed}/{len(work_list)}] 视频就绪: {res['msg'].split(' ')[-1]}")
395
+ generated_files.append(res['file'])
396
+ else:
397
+ logs.append(f"❌ [{completed}/{len(work_list)}] 失败: {res['msg']}")
398
+
399
+ yield "\n".join(logs[-15:]), generated_files, None
400
+
401
+ if generated_files:
402
+ generated_files.sort()
403
+ zip_name = f"{session_dir}.zip"
404
+ shutil.make_archive(session_dir, 'zip', session_dir)
405
+ logs.append(f"\n🎉 [全部完成] 已打包 ZIP,请点击右侧下载。");
406
+ yield "\n".join(logs), generated_files, zip_name
407
+ else:
408
+ logs.append("\n❌ 全部失败,无视频生成"); yield "\n".join(logs), None, None
409
+
410
+ # === 界面 ===
411
+ with gr.Blocks(title="Veo Ultimate + Viral Decompressive Immersion (超级全量版)") as app:
412
+ gr.Markdown("# 🏭 终极工业大片 + 极致解压 (Super Hybrid V14 - 双引擎版)")
413
+ gr.Markdown("核心升级:**[独立 Video API]** + **[超长视频(200+镜头)]** + **[无限制生成]**")
414
+
415
+ with gr.Row(variant="panel"):
416
+ # 1. LLM 专用 Key
417
+ api_key_input = gr.Textbox(
418
+ label="🔑 LLM API Key (架构师+导演)",
419
+ value=DEFAULT_LLM_API_KEY,
420
+ type="password",
421
+ placeholder="用于生成架构和剧本 (Gemini)"
422
+ )
423
+ # 2. 视频生成专用 Key
424
+ video_api_key_input = gr.Textbox(
425
+ label="🎬 Video API Key (Veo 渲染专用)",
426
+ value=DEFAULT_VIDEO_API_KEY,
427
+ type="password",
428
+ placeholder="用于生成视频 (Veo)"
429
+ )
430
+
431
+ with gr.Row(variant="panel"):
432
+ with gr.Column(scale=1):
433
+ topic_input = gr.Textbox(label="1. 输入产品名称", placeholder="例如:Apple Juice, Ceramic Plate, Steel Gear")
434
+ with gr.Accordion("🛠️ 角色1:首席工艺工程师 (全生命周期技术)", open=False):
435
+ architect_prompt_input = gr.Textbox(label="Engineer System Prompt", value=DEFAULT_ARCHITECT_PROMPT, lines=8)
436
+ plan_btn = gr.Button("🛠️ 第一步:生成工艺说明书 (LLM)", variant="secondary")
437
+
438
+ with gr.Column(scale=2):
439
+ architecture_output = gr.Textbox(
440
+ label="2. 确认说明书 (检查:源头 -> 物理流程 -> 成品)",
441
+ lines=10,
442
+ placeholder="点击左侧按钮生成工艺...",
443
+ interactive=True
444
+ )
445
+
446
+ with gr.Row():
447
+ with gr.Column(scale=1):
448
+ # [核心修改] UI 适配 200 个镜头
449
+ count_slider = gr.Slider(minimum=1, maximum=300, value=200, step=1, label="3. 镜头数量 (建议 200+)")
450
+
451
+ script_btn = gr.Button("📝 第二步:导演介入-解压沉浸分镜 (LLM)", variant="primary")
452
+ video_btn = gr.Button("🎬 第三步:开始批量渲染视频 (Video API)", variant="stop")
453
+
454
+ with gr.Column(scale=2):
455
+ with gr.Accordion("🎭 角色2:IMAX 导演 (负责解压沉浸美学)", open=False):
456
+ system_prompt_input = gr.Textbox(label="Director System Prompt", value=DEFAULT_DIRECTOR_PROMPT, lines=8)
457
+
458
+ with gr.Row():
459
+ log_out = gr.Textbox(label="运行日志 (实时反馈)", lines=12)
460
+ script_out = gr.Textbox(label="最终脚本", lines=12, interactive=True)
461
+ zip_out = gr.File(label="下载生成结果 (文件列表 & ZIP)")
462
+
463
+ # 绑定事件
464
+ plan_btn.click(
465
+ generate_process_architecture,
466
+ inputs=[topic_input, api_key_input, architect_prompt_input],
467
+ outputs=[architecture_output]
468
+ )
469
+
470
+ script_btn.click(
471
+ step2_generate_script,
472
+ inputs=[topic_input, architecture_output, count_slider, system_prompt_input, api_key_input],
473
+ outputs=[log_out, script_out]
474
+ )
475
+
476
+ video_btn.click(
477
+ step3_generate_videos,
478
+ # === 核心修改:传入 Video API Key ===
479
+ inputs=[topic_input, script_out, video_api_key_input],
480
+ outputs=[log_out, zip_out, zip_out]
481
+ )
482
+
483
+ app.launch()