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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 30 |
+
# 2. 视频渲染专用 Key (新增专用通道)
|
| 31 |
+
DEFAULT_VIDEO_API_KEY = "sk-G6LN0uC2BVclZjx1ObDJPkMZTZvtjau1Ss7GjCvRLJyI5euU"
|
| 32 |
+
|
| 33 |
+
MERCHANT_BASE_URL = "https://xingjiabiapi.com"
|
| 34 |
+
VEO_MODEL = "veo_3_1-fast"
|
| 35 |
+
VIDEO_SIZE = "16x9"
|
| 36 |
+
TEXT_MODEL = "gemini-3-pro-preview-thinking"
|
| 37 |
+
|
| 38 |
+
# ===============================================
|
| 39 |
+
# --- 角色1:首席工艺工程师 (The Chief Process Engineer) ---
|
| 40 |
+
# --- 核心升级:输出 [MINIMAL_ASSET_LOCK] (红线资产锁) ---
|
| 41 |
+
# ===============================================
|
| 42 |
+
DEFAULT_ARCHITECT_PROMPT = """
|
| 43 |
+
你是一家顶级工厂的**首席工艺工程师 (Chief Process Engineer)**。
|
| 44 |
+
你**完全不懂**电影制作,你的唯一职责是设计一条**“逻辑严密、设备真实、物理过程详尽”**的工业生产线。
|
| 45 |
+
|
| 46 |
+
**你的任务:**
|
| 47 |
+
为指定产品设计一份《全生命周期工艺说明书》(Full Lifecycle Process Protocol)。
|
| 48 |
+
|
| 49 |
+
**⚠️ 工程师铁律 (Engineering Laws):**
|
| 50 |
+
1. **全链路覆盖 (Full Lifecycle Scope)**:
|
| 51 |
+
* **起点必须是源头**:严禁只从工厂门口写起。必须包含**“原材料获取 (Acquisition)”**(例如:果园采摘、矿山开采、原木砍伐)。
|
| 52 |
+
* **终点必须是成品**:必须包含**“最终成品形态 (Final Product)”**(例如:装瓶、装箱、码垛完成)。
|
| 53 |
+
2. **物理真实性**:必须使用真实的工业设备名称(如:Harvester, Hammer Mill, Optical Sorter)。
|
| 54 |
+
3. **流程闭环**:Step N 的输出必须是 Step N+1 的输入。严禁逻辑断层。
|
| 55 |
+
|
| 56 |
+
**★ 新增核心任务:定义红线资产锁 (Hero Asset Lock) ★**
|
| 57 |
+
为了防止核心资产(原料、中间态、容器)在长视频中变异,你必须定义**红线资产**。环境资产(如地板、墙壁)不需要你定义,交给导演根据工序自动匹配。
|
| 58 |
+
|
| 59 |
+
**输出格式 (严禁修改):**
|
| 60 |
+
|
| 61 |
+
[MINIMAL_ASSET_LOCK]
|
| 62 |
+
* **Hero Raw Material**: [描述原料外观,例如:Deep Red Dragonfruit with Green Scales]
|
| 63 |
+
* **Hero Liquid/Pulp**: [描述加工态颜色/质感,例如:Vibrant Magenta Pulp, Ruby Red Juice]
|
| 64 |
+
* **Hero Container**: [描述最终容器,例如:Transparent PET Bottle with White Cap] (一旦定义,全片不可变!)
|
| 65 |
+
[END_ASSET_LOCK]
|
| 66 |
+
|
| 67 |
+
Step [序号] | [工序名称]
|
| 68 |
+
* **Equipment**: [真实机器名称]
|
| 69 |
+
* **Physics Input**: [原料进入时的状态]
|
| 70 |
+
* **Mechanism**: [机器运作原理与物理动作描述]
|
| 71 |
+
* **Physics Output**: [原料离开时的物理变化结果]
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
# ===============================================
|
| 75 |
+
# --- 角色2:IMAX 细节狂魔导演 (Director & Editor) ---
|
| 76 |
+
# --- 核心升级:全量历史回溯 + 最小资产锁 + 30镜头大批次 ---
|
| 77 |
+
# ===============================================
|
| 78 |
+
DEFAULT_DIRECTOR_PROMPT = """
|
| 79 |
+
你是一位追求**“极致真实与细节”**的 IMAX 纪录片导演,同时也是一位**金牌剪辑师**。
|
| 80 |
+
你拿到了一份《工艺说明书》和一份《红线资产锁》。
|
| 81 |
+
你的任务是:**基于这份技术文档,通过“剪辑配比”和“视觉转译”,生成一部节奏完美的“解压沉浸式 (Decompressive Immersion)”长视频工业大片脚本。**
|
| 82 |
+
|
| 83 |
+
**⚠️ 优先级说明:以下【六大终极死令】拥有最高优先级,必须 100% 执行!⚠️**
|
| 84 |
+
|
| 85 |
+
**💀 死令零:红线资产锁死 (Hero Asset Locking) [★解决穿帮★]**
|
| 86 |
+
* **原则**:Veo 生成视频是独立的。你必须在**每一个镜头**的 Prompt 中,把资产描述写进去。
|
| 87 |
+
* **强制执行**:
|
| 88 |
+
* **读取红线**:严格遵守传入的 `[MINIMAL_ASSET_LOCK]`。
|
| 89 |
+
* **拒绝变异**:如果账本说瓶子是塑料的(PET),绝不能写成玻璃(Glass)。如果液体是红色的,绝不能写成橙色。
|
| 90 |
+
* **环境自适应**:对于未定义的“环境资产”(地板、墙壁),根据工序自动匹配(如清洗间配湿润瓷砖,包装间配无尘车间)。
|
| 91 |
+
|
| 92 |
+
**💀 死令一:全量历史回溯与伏笔回收 (Full History Injection) [★统筹全局★]**
|
| 93 |
+
* **原则**:你拥有“上帝视角”。你必须阅读传入的 `[FULL_SCRIPT_HISTORY]` (之前生成的所有镜头)。
|
| 94 |
+
* **执行**:
|
| 95 |
+
* **伏笔回收**:如果第 5 镜是特写,第 35 镜再次出现时必须保持视觉一致。
|
| 96 |
+
* **节奏对比**:如果前 30 镜太快,现在要慢下来���
|
| 97 |
+
* **严丝合缝**:当前生成的第一个镜头,必须完美接续历史记录的最后一镜。
|
| 98 |
+
|
| 99 |
+
**💀 死令二:长视频剪辑配比 (10-90 Rule)**
|
| 100 |
+
* **Phase A: 史诗开篇 (前10%)**:原材料采集(Acquisition)必须是**“大片级解压沉浸”**。宏大、慢动作、自然光。物流要压缩。
|
| 101 |
+
* **Phase B: 极致沉浸核心 (后90%)**:核心加工环节(切、碎、炸、流)是绝对主角。**无限膨胀**这些步骤。
|
| 102 |
+
|
| 103 |
+
**💀 死令三:架构微观膨胀法则**
|
| 104 |
+
* 核心步骤必须膨胀为 4-6 个连续镜头。非核心步骤 1-2 镜带过。
|
| 105 |
+
|
| 106 |
+
**💀 死令四:三段式微观动作拆解**
|
| 107 |
+
* Entry -> Process -> Exit。
|
| 108 |
+
|
| 109 |
+
**💀 死令五:X光负载锁定**
|
| 110 |
+
* 车停必开门,开门必见货。
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------------
|
| 113 |
+
# 导演执行手册:常规铁律
|
| 114 |
+
# ---------------------------------------------------------------------
|
| 115 |
+
**🔥 铁律一:解压沉浸流派**
|
| 116 |
+
[SLICE], [CRUSH], [PEEL], [FLOW], [CLEAN], [SYNC].
|
| 117 |
+
|
| 118 |
+
**🔥 铁律二:视觉内容**
|
| 119 |
+
绝对饱和密度,暴力冗余。
|
| 120 |
+
|
| 121 |
+
# ==================== 输出格式 (严禁修改) ====================
|
| 122 |
+
Shot [序号]/[总数] | [中文标题]
|
| 123 |
+
Sora Prompt (English): (Action_Phase): [Entry/Process/Exit] (Start_Frame_Visual): [MUST CONNECT TO HISTORY] (Object_State_Adjectives): [MANDATORY] (Engineering_Source): [Ref Step] (Satisfaction_Genre): [Genre] (Execution_Focus): [Focus] (Scene_Environment): [Ref ASSET_LOCK or Adaptive] (Visual_Action_Trajectory): [Start->Arc->End] (Screen_Density): [Edge-to-Edge] (Audio_Decompressive_Immersion): [Sound] (Asset_Consistency): [CRITICAL: REPEAT DATA FROM ASSET_LOCK] (Human_Interaction): [Contextual]
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
# ===============================================
|
| 127 |
+
|
| 128 |
+
def generate_process_architecture(topic, api_key, architect_prompt):
|
| 129 |
+
"""阶段一:生成工艺说明书 + 资产账本"""
|
| 130 |
+
if not topic: return "❌ 请先输入产品名称", None
|
| 131 |
+
if not api_key: return "❌ 请先输入 LLM API Key", None
|
| 132 |
+
|
| 133 |
+
print(f"🧠 [{TEXT_MODEL}] 正在构建《{topic}》的全生命周期工艺流程...")
|
| 134 |
+
|
| 135 |
+
user_content = f"""
|
| 136 |
+
Design a rigorous, physically accurate Full Lifecycle Industrial Process Protocol for: {topic}.
|
| 137 |
+
Include a strict [MINIMAL_ASSET_LOCK] at the beginning.
|
| 138 |
+
|
| 139 |
+
ROLE: You are the Chief Process Engineer.
|
| 140 |
+
GOAL: Create a technical blueprint covering Raw Material Acquisition -> Final Product.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
|
| 144 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key.strip()}"}
|
| 145 |
+
data = {
|
| 146 |
+
"model": TEXT_MODEL,
|
| 147 |
+
"messages": [
|
| 148 |
+
{"role": "system", "content": architect_prompt},
|
| 149 |
+
{"role": "user", "content": user_content}
|
| 150 |
+
],
|
| 151 |
+
"temperature": 0.5,
|
| 152 |
+
"max_tokens": 4096
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
response = requests.post(url, headers=headers, json=data, timeout=240)
|
| 157 |
+
if response.status_code == 200:
|
| 158 |
+
content = response.json()['choices'][0]['message']['content']
|
| 159 |
+
return content, content
|
| 160 |
+
else:
|
| 161 |
+
return f"Error: {response.text}", None
|
| 162 |
+
except Exception as e:
|
| 163 |
+
return f"Request Failed: {e}", None
|
| 164 |
+
|
| 165 |
+
def extract_asset_manifest(architecture_text):
|
| 166 |
+
"""从架构师输出中提取资产账本"""
|
| 167 |
+
if not architecture_text: return "No Asset Lock Found."
|
| 168 |
+
# 兼容新旧格式,这里匹配 MINIMAL_ASSET_LOCK
|
| 169 |
+
match = re.search(r"\[MINIMAL_ASSET_LOCK\](.*?)\[END_ASSET_LOCK\]", architecture_text, re.DOTALL)
|
| 170 |
+
if match:
|
| 171 |
+
return match.group(1).strip()
|
| 172 |
+
return "Default Assets: Stainless Steel, Generic Product."
|
| 173 |
+
|
| 174 |
+
def generate_script_batch(topic, architecture, asset_manifest, full_script_history, start_shot, end_shot, total_shots, system_prompt, api_key):
|
| 175 |
+
"""阶段二:分批循环生成脚本 (传入资产账本 + 全量历史)"""
|
| 176 |
+
|
| 177 |
+
# 构建包含“全量历史”的用户 Prompt
|
| 178 |
+
# 注意:如果 history 太长,Gemini Pro 也能处理 (通常支持 1M Token),这里直接放入
|
| 179 |
+
user_content = f"""
|
| 180 |
+
Product: {topic}
|
| 181 |
+
|
| 182 |
+
=== HERO ASSET LOCK (ABSOLUTE RULES) ===
|
| 183 |
+
{asset_manifest}
|
| 184 |
+
========================================
|
| 185 |
+
|
| 186 |
+
=== FULL SCRIPT HISTORY (CONTEXT SO FAR) ===
|
| 187 |
+
{full_script_history if full_script_history else "Start of the video. No previous shots."}
|
| 188 |
+
============================================
|
| 189 |
+
|
| 190 |
+
Engineering Blueprint Reference:
|
| 191 |
+
{architecture}
|
| 192 |
+
|
| 193 |
+
Task: Generate ONLY shots #{start_shot} to #{end_shot} (out of {total_shots} total).
|
| 194 |
+
|
| 195 |
+
CRITICAL INSTRUCTIONS:
|
| 196 |
+
1. **CONSISTENCY**: Check [HERO ASSET LOCK]. If "PET Bottle" is defined, do NOT write "Glass".
|
| 197 |
+
2. **CONTINUITY**: Read [FULL SCRIPT HISTORY]. Connect seamlessly to the last shot. Maintain the pacing established previously.
|
| 198 |
+
3. **10% RULE**: If shot < {int(total_shots*0.1)}, focus on EPIC ACQUISITION.
|
| 199 |
+
4. **AUDIO**: Only Decompressive Immersion sounds.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
|
| 203 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key.strip()}"}
|
| 204 |
+
data = {
|
| 205 |
+
"model": TEXT_MODEL,
|
| 206 |
+
"messages": [
|
| 207 |
+
{"role": "system", "content": system_prompt},
|
| 208 |
+
{"role": "user", "content": user_content}
|
| 209 |
+
],
|
| 210 |
+
"temperature": 0.7,
|
| 211 |
+
"max_tokens": 16000
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
response = requests.post(url, headers=headers, json=data, timeout=360)
|
| 216 |
+
if response.status_code == 200:
|
| 217 |
+
return response.json()['choices'][0]['message']['content']
|
| 218 |
+
else:
|
| 219 |
+
return None
|
| 220 |
+
except Exception as e:
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
def step2_generate_script(topic, architecture, count, system_prompt, api_key):
|
| 224 |
+
"""阶段二:分批循环生成脚本 (Batch=30 + 全量注入 + 5次重试)"""
|
| 225 |
+
if not architecture: return "❌ 请先生成并确认工艺架构", None
|
| 226 |
+
if not api_key: return "❌ 请先输入 LLM API Key", None
|
| 227 |
+
|
| 228 |
+
logs = [f"🚀 [任务启动] 目标: {count} 个镜头. 解析资产账本...", "------------------------------------------------"]
|
| 229 |
+
yield "\n".join(logs), None
|
| 230 |
+
|
| 231 |
+
# 1. 提取红线资产
|
| 232 |
+
asset_manifest = extract_asset_manifest(architecture)
|
| 233 |
+
logs.append(f"🔐 [资产锁定] 红线资产已提取:\n{asset_manifest}")
|
| 234 |
+
yield "\n".join(logs), None
|
| 235 |
+
|
| 236 |
+
full_script_text = ""
|
| 237 |
+
|
| 238 |
+
# === 核心修改:Batch Size = 30 ===
|
| 239 |
+
batch_size = 30
|
| 240 |
+
total_batches = (count + batch_size - 1) // batch_size
|
| 241 |
+
|
| 242 |
+
# === 核心修改:重试次数 = 5 ===
|
| 243 |
+
MAX_RETRIES = 5
|
| 244 |
+
|
| 245 |
+
for i in range(total_batches):
|
| 246 |
+
start_num = i * batch_size + 1
|
| 247 |
+
end_num = min((i + 1) * batch_size, count)
|
| 248 |
+
batch_success = False
|
| 249 |
+
|
| 250 |
+
for attempt in range(MAX_RETRIES):
|
| 251 |
+
if attempt == 0:
|
| 252 |
+
logs.append(f"🔵 [Batch {i+1}/{total_batches}] 初始化 Shot {start_num}-{end_num}...")
|
| 253 |
+
yield "\n".join(logs), full_script_text
|
| 254 |
+
# 显式显示正在进行全量注入
|
| 255 |
+
history_len = len(full_script_text)
|
| 256 |
+
logs.append(f"🧠 [全量注入] 将 {history_len} 字符的历史剧本注入上下文...")
|
| 257 |
+
yield "\n".join(logs), full_script_text
|
| 258 |
+
else:
|
| 259 |
+
logs.append(f"⚠️ [网络重试] 第 {i+1} 批次生成失败,正在进行第 {attempt+1}/{MAX_RETRIES} 次重试...")
|
| 260 |
+
yield "\n".join(logs), full_script_text
|
| 261 |
+
|
| 262 |
+
# === 调用生成函数 (传入 full_script_text 作为历史) ===
|
| 263 |
+
batch_script = generate_script_batch(
|
| 264 |
+
topic, architecture, asset_manifest, full_script_text,
|
| 265 |
+
start_num, end_num, count, system_prompt, api_key
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
if batch_script and len(batch_script) > 200: # 稍微提高一点有效性阈值
|
| 269 |
+
full_script_text += f"\n{batch_script}\n"
|
| 270 |
+
|
| 271 |
+
logs.append(f"✅ [成功] Batch {i+1} 完成 ({start_num}-{end_num})。资产一致性检查通过。")
|
| 272 |
+
logs.append("------------------------------------------------")
|
| 273 |
+
batch_success = True
|
| 274 |
+
yield "\n".join(logs), full_script_text
|
| 275 |
+
break
|
| 276 |
+
else:
|
| 277 |
+
logs.append(f"❌ [失败] 返回无效或截断。冷却 3 秒...")
|
| 278 |
+
time.sleep(3)
|
| 279 |
+
yield "\n".join(logs), full_script_text
|
| 280 |
+
|
| 281 |
+
if not batch_success:
|
| 282 |
+
return "\n".join(logs) + "\n❌❌❌ [熔断] 5次重试失败,任务停止。", full_script_text
|
| 283 |
+
|
| 284 |
+
prompts_data = extract_prompts_with_titles(full_script_text)
|
| 285 |
+
logs.append(f"\n🎉 [完成] 脚本生成完毕!共 {len(prompts_data)} 个镜头。")
|
| 286 |
+
return "\n".join(logs), full_script_text
|
| 287 |
+
|
| 288 |
+
def extract_prompts_with_titles(script_text):
|
| 289 |
+
"""提取 Prompt 和 标题"""
|
| 290 |
+
if not script_text: return []
|
| 291 |
+
pattern = r"(?:[\*\#]*\s*)Shot\s+(\d+).*?\|\s*([^\n]+).*?Sora Prompt \(English\):\s*(.*?)(?=\n\s*(?:[\*\#]*\s*)Shot|::END::|$)"
|
| 292 |
+
matches = re.findall(pattern, script_text, re.DOTALL | re.IGNORECASE)
|
| 293 |
+
results = []
|
| 294 |
+
for shot_num, title, content in matches:
|
| 295 |
+
clean_title = title.replace("**", "").replace("##", "").strip()
|
| 296 |
+
safe_title = re.sub(r'[\\/*?:"<>|]', "", clean_title).strip().replace(" ", "_")
|
| 297 |
+
if len(safe_title) > 40: safe_title = safe_title[:40]
|
| 298 |
+
filename_base = f"Shot_{int(shot_num):03d}_{safe_title}"
|
| 299 |
+
clean_p = content.replace("\n", " ").replace("**", "").replace("##", "").strip()
|
| 300 |
+
clean_p = re.sub(r'\s+', ' ', clean_p)
|
| 301 |
+
if len(clean_p) > 10:
|
| 302 |
+
results.append({"filename": filename_base, "prompt": clean_p})
|
| 303 |
+
return results
|
| 304 |
+
|
| 305 |
+
def generate_single_video_task(prompt, filename_base, save_dir, video_api_key, topic):
|
| 306 |
+
"""生成单视频:使用 VIDEO API KEY"""
|
| 307 |
+
if not prompt: return None
|
| 308 |
+
clean_prompt = prompt.replace("--ar 16:9", "").replace("16:9", "")
|
| 309 |
+
final_prompt = (
|
| 310 |
+
f"Wide screen 16x9 video. {topic} manufacturing documentary blockbuster. "
|
| 311 |
+
f"**BBC/Discovery Style, Hyper-Realistic, 8K, No Sci-Fi.** "
|
| 312 |
+
f"**Ultimate Decompressive Immersion, Massive Screen Density, Edge-to-Edge Filling.** "
|
| 313 |
+
f"**Editorial Continuity, Smooth Transitions, Perfect Loop.** "
|
| 314 |
+
f"**Completed Action Trajectory, Object Lands Successfully.** "
|
| 315 |
+
f"**Pure Diegetic Audio, No Music, Decompressive Immersion Sounds.** "
|
| 316 |
+
f"**Extremely Detailed Texture, Physics-based Motion, Human-Machine Collaboration.** "
|
| 317 |
+
f"{clean_prompt} --ar 16x9"
|
| 318 |
+
)
|
| 319 |
+
url = f"{MERCHANT_BASE_URL}/v1/chat/completions"
|
| 320 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {video_api_key.strip()}"}
|
| 321 |
+
data = {
|
| 322 |
+
"model": VEO_MODEL,
|
| 323 |
+
"messages": [{"role": "user", "content": final_prompt}],
|
| 324 |
+
"stream": False, "size": VIDEO_SIZE, "seconds": 8, "aspect_ratio": "16:9"
|
| 325 |
+
}
|
| 326 |
+
fname = f"{filename_base}.mp4"
|
| 327 |
+
save_path = os.path.join(save_dir, fname)
|
| 328 |
+
try:
|
| 329 |
+
resp = requests.post(url, headers=headers, json=data, timeout=300)
|
| 330 |
+
if resp.status_code != 200: return {"status": "error", "msg": f"[{filename_base}] ❌ API Error: {resp.status_code}"}
|
| 331 |
+
try:
|
| 332 |
+
content = resp.json()['choices'][0]['message']['content']
|
| 333 |
+
url_match = re.search(r'(https?://[^\s)"]+)', content)
|
| 334 |
+
if not url_match: return {"status": "error", "msg": f"[{filename_base}] ❌ No URL found"}
|
| 335 |
+
vid_data = requests.get(url_match.group(1).split(')')[0]).content
|
| 336 |
+
with open(save_path, "wb") as f: f.write(vid_data)
|
| 337 |
+
return {"status": "success", "file": save_path, "msg": f"✅ [渲染成功] {fname}"}
|
| 338 |
+
except Exception as e: return {"status": "error", "msg": f"[{filename_base}] ❌ Parse Error: {e}"}
|
| 339 |
+
except Exception as e: return {"status": "error", "msg": f"[{filename_base}] ❌ Network Error: {e}"}
|
| 340 |
+
|
| 341 |
+
def step3_generate_videos(topic, script_text, video_api_key, progress=gr.Progress()):
|
| 342 |
+
"""阶段三:批量生成视频"""
|
| 343 |
+
if not script_text: yield "❌ 脚本内容为空,请先执行第二步", None, None; return
|
| 344 |
+
if not video_api_key: yield "❌ 请先输入 Video API Key", None, None; return
|
| 345 |
+
|
| 346 |
+
timestamp = int(time.time())
|
| 347 |
+
safe_topic = re.sub(r'[\\/*?:"<>|]', "", topic).replace(" ", "_") if topic else "Untitled"
|
| 348 |
+
base_dir = "AutoSaved_Videos"
|
| 349 |
+
session_dir = os.path.join(base_dir, f"{safe_topic}_{timestamp}")
|
| 350 |
+
os.makedirs(session_dir, exist_ok=True)
|
| 351 |
+
|
| 352 |
+
logs = [f"🚀 [渲染启动] 开始批量生成视频 (使用 Video 专用 Key)...", f"📂 归档目录: {os.path.abspath(session_dir)}"]
|
| 353 |
+
yield "\n".join(logs), None, None
|
| 354 |
+
|
| 355 |
+
with open(os.path.join(session_dir, "script.txt"), "w", encoding="utf-8") as f:
|
| 356 |
+
f.write(script_text)
|
| 357 |
+
|
| 358 |
+
prompts_data = extract_prompts_with_titles(script_text)
|
| 359 |
+
if not prompts_data:
|
| 360 |
+
logs.append("❌ 脚本格式解析失败,未找到有效 Prompt"); yield "\n".join(logs), None, None; return
|
| 361 |
+
|
| 362 |
+
logs.append(f"🎥 任务队列建立完成:共 {len(prompts_data)} 个镜头。正在向 Veo 发送并发请求...")
|
| 363 |
+
yield "\n".join(logs), None, None
|
| 364 |
+
|
| 365 |
+
work_list = prompts_data
|
| 366 |
+
generated_files = []
|
| 367 |
+
|
| 368 |
+
with ThreadPoolExecutor(max_workers=len(work_list)) as executor:
|
| 369 |
+
futures = {
|
| 370 |
+
executor.submit(generate_single_video_task, item['prompt'], item['filename'], session_dir, video_api_key, topic): item['filename']
|
| 371 |
+
for item in work_list
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
completed = 0
|
| 375 |
+
for future in as_completed(futures):
|
| 376 |
+
res = future.result()
|
| 377 |
+
completed += 1
|
| 378 |
+
progress(completed/len(work_list), desc=f"渲染中 {completed}/{len(work_list)}")
|
| 379 |
+
if res:
|
| 380 |
+
if res['status'] == 'success':
|
| 381 |
+
logs.append(f"✅ [{completed}/{len(work_list)}] 视频就绪: {res['msg'].split(' ')[-1]}")
|
| 382 |
+
generated_files.append(res['file'])
|
| 383 |
+
else:
|
| 384 |
+
logs.append(f"❌ [{completed}/{len(work_list)}] 失败: {res['msg']}")
|
| 385 |
+
|
| 386 |
+
yield "\n".join(logs[-15:]), generated_files, None
|
| 387 |
+
|
| 388 |
+
if generated_files:
|
| 389 |
+
generated_files.sort()
|
| 390 |
+
zip_name = f"{session_dir}.zip"
|
| 391 |
+
shutil.make_archive(session_dir, 'zip', session_dir)
|
| 392 |
+
logs.append(f"\n🎉 [全部完成] 已打包 ZIP,请点击右侧下载。");
|
| 393 |
+
yield "\n".join(logs), generated_files, zip_name
|
| 394 |
+
else:
|
| 395 |
+
logs.append("\n❌ 全部失败,无视频生成"); yield "\n".join(logs), None, None
|
| 396 |
+
|
| 397 |
+
# === 界面 ===
|
| 398 |
+
with gr.Blocks(title="Veo Ultimate + Viral Decompressive Immersion (超级全量版)") as app:
|
| 399 |
+
gr.Markdown("# 🏭 终极工业大片 + 极致解压 (Super Hybrid V16 - 最终全量版)")
|
| 400 |
+
gr.Markdown("核心升级:**[双API]** + **[红线资产锁]** + **[全量历史回溯]** + **[30镜头大批次]**")
|
| 401 |
+
|
| 402 |
+
with gr.Row(variant="panel"):
|
| 403 |
+
api_key_input = gr.Textbox(
|
| 404 |
+
label="🔑 LLM API Key (架构师+导演)",
|
| 405 |
+
value=DEFAULT_LLM_API_KEY,
|
| 406 |
+
type="password",
|
| 407 |
+
placeholder="用于生成架构和剧本 (Gemini)"
|
| 408 |
+
)
|
| 409 |
+
video_api_key_input = gr.Textbox(
|
| 410 |
+
label="🎬 Video API Key (Veo 渲染专用)",
|
| 411 |
+
value=DEFAULT_VIDEO_API_KEY,
|
| 412 |
+
type="password",
|
| 413 |
+
placeholder="用于生成视频 (Veo)"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
with gr.Row(variant="panel"):
|
| 417 |
+
with gr.Column(scale=1):
|
| 418 |
+
topic_input = gr.Textbox(label="1. 输入产品名称", placeholder="例如:Apple Juice, Ceramic Plate, Steel Gear")
|
| 419 |
+
with gr.Accordion("🛠️ 角色1:首席工艺工程师 (全生命周期技术)", open=False):
|
| 420 |
+
architect_prompt_input = gr.Textbox(label="Engineer System Prompt", value=DEFAULT_ARCHITECT_PROMPT, lines=8)
|
| 421 |
+
plan_btn = gr.Button("🛠️ 第一步:生成工艺说明书 (含红线资产)", variant="secondary")
|
| 422 |
+
|
| 423 |
+
with gr.Column(scale=2):
|
| 424 |
+
architecture_output = gr.Textbox(
|
| 425 |
+
label="2. 确认说明书 (检查:[MINIMAL_ASSET_LOCK] 是否存在)",
|
| 426 |
+
lines=10,
|
| 427 |
+
placeholder="点击左侧按钮生成工艺...",
|
| 428 |
+
interactive=True
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
with gr.Row():
|
| 432 |
+
with gr.Column(scale=1):
|
| 433 |
+
count_slider = gr.Slider(minimum=1, maximum=200, value=120, step=1, label="3. 镜头数量 (不低于120)")
|
| 434 |
+
|
| 435 |
+
script_btn = gr.Button("📝 第二步:导演介入-解压沉浸分镜", variant="primary")
|
| 436 |
+
video_btn = gr.Button("🎬 第三步:开始批量渲染视频 (Video API)", variant="stop")
|
| 437 |
+
|
| 438 |
+
with gr.Column(scale=2):
|
| 439 |
+
with gr.Accordion("🎭 角色2:IMAX 导演 (负责资产锁定与美学)", open=False):
|
| 440 |
+
system_prompt_input = gr.Textbox(label="Director System Prompt", value=DEFAULT_DIRECTOR_PROMPT, lines=8)
|
| 441 |
+
|
| 442 |
+
with gr.Row():
|
| 443 |
+
log_out = gr.Textbox(label="运行日志 (实时反馈)", lines=12)
|
| 444 |
+
script_out = gr.Textbox(label="最终脚本", lines=12, interactive=True)
|
| 445 |
+
zip_out = gr.File(label="下载生成结果 (文件列表 & ZIP)")
|
| 446 |
+
|
| 447 |
+
# 绑定事件
|
| 448 |
+
plan_btn.click(
|
| 449 |
+
generate_process_architecture,
|
| 450 |
+
inputs=[topic_input, api_key_input, architect_prompt_input],
|
| 451 |
+
outputs=[architecture_output]
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
script_btn.click(
|
| 455 |
+
step2_generate_script,
|
| 456 |
+
inputs=[topic_input, architecture_output, count_slider, system_prompt_input, api_key_input],
|
| 457 |
+
outputs=[log_out, script_out]
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
video_btn.click(
|
| 461 |
+
step3_generate_videos,
|
| 462 |
+
inputs=[topic_input, script_out, video_api_key_input],
|
| 463 |
+
outputs=[log_out, zip_out, zip_out]
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
app.launch()
|