Update app.py
Browse files5 unmodified lines67891011121 unmodified line14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421434 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152168 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914925 unmodified linesimport requestsimport zipfileimport queueimport threadingfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completed1 unmodified line# 1. 平台鉴权YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"MERCHANT_BASE_URL = "https://yunwu.ai" # 用户指定的基础URL# 2. 模型核心配置 (VEO 修改版)VEO_MODEL = "veo_3_1-fast" # 改为 VEO 模型VIDEO_SIZE = "16x9" # 改为 16:9 画幅TEXT_MODEL = "gemini-3-pro-preview-thinking"VIDEO_DURATION = 8 # 改为 8秒# 3. 系统配置# ⚠️ 这里是基础目录,具体文件会存入带时间戳的子目录BASE_OUTPUT_DIR = "project_thangka_veo"VIDEO_WORKERS = 50 # 视频渲染并发数LOGIC_WORKERS = 10 # 逻辑处理并发数CONFIG_FILE = "prompt_config.json" # 改回默认配置文件名# ================= 风格与动态核武器 (保持西藏唐卡风格) =================# 【强制风格词 - 头部注入】: 核心风格定调FORCE_STYLE_PREFIX = ("A sacred Tibetan Thangka painting style on aged cotton canvas. ""Rich mineral pigment colors (ground lapis lazuli, malachite, cinnabar, precious gold lines). ""Intricate religious patterns, solemn deities, flat perspective with divine aura. ")# 【强制动态助推器 - 中段注入】FORCE_MOTION_BOOSTER = (" , (EXTREME DYNAMIC MOTION: wind blowing hair and clothes, fast moving clouds, action lines, ""cinematic lighting, dynamic camera angle, depth of field), ")# 【强制材质与细节 - 尾部注入】FORCE_STYLE_SUFFIX = (" , highly detailed Thangka line work (Goujin), traditional cloth painting texture, symmetrical composition, exquisite craftsmanship, religious art masterpiece.")# 【强制负向词 - 防御层】FORCE_NEGATIVE_PROMPT = (" --no photorealistic, realistic, real photo, 4k footage, 3d render, cgi, unreal engine, ""photograph, camera footage, blurry, deformed, modern, western style, ""static, still image, frozen, stationary, standing still, talking head, interview style, text, watermark.")# ================= 默认提示词 (已修改为 8秒 Veo 结构) =================DEFAULT_SPLITTER_PROMPT = """你是一位精通西藏唐卡叙事艺术的大师。你的任务是将输入的长文本,根据**唐卡长卷画面的视觉转换逻辑**,拆解成适合制作 8秒 动态视频的“分镜段落”。【拆分铁律】****最高铁律,每个段落不可以超过120个字,如果识别到超过则删除目前这一段,从前面一句话截止。1.**字数控制**:每个段落对应解说词长度约 **100-120字**。2. **意群完整**:必须在句号或逻辑结束处切分,保持叙事的连贯性。3. **输出格式**:只返回 JSON 字符串列表。格式:["段落1内容...", "段落2内容..."]【输入文本】(等待输入...)"""# ⚠️ 修改点:适配 8秒 和 新的时间切片逻辑DEFAULT_GEN_PROMPT = """你是一位西藏唐卡艺术绘画大师,擅长描绘动态的宗教与神话故事。将输入的中文解说词,转化为符合【全动态 + 硬切分镜】要求的英文视频提示词。【画面绝对铁律 (Iron Laws)】1. **禁止静止**:绝对不要出现 "standing", "sitting", "talking", "waiting"。画面中的人物、神兽或环境必须处于动态之中。2. **环境联动**:如果没有大动作,必须描述 "Wind blowing prayer flags", "Clouds moving fast around mountains", "Divine flames flickering"。3. **8秒硬切结构 (8s Structure)**:必须将提示词写成 3 个时间段的硬切描述,时间节点严格按照以下要求:格式必须包含:"(0s-3s)... (3s-6s)... (6s-8s)..."【风格去真实化 - 唐卡专用】- 必须使用 "A sacred Thangka painting of..." 开头。- 严禁使用 "A video of...", "Real footage of...", "Ink painting...", "Illustration..."【输出示例】{"0": "A sacred Thangka painting of a mythological warrior riding a divine horse fast across stylized mountains (0s-3s); Hard cut to a close up of his golden sword clashing with a demon's shield emitting sparks (3s-6s); Hard cut to the horse leaping over a swirling cloud canyon (6s-8s)."}【任务】请处理以下片段列表,返回 JSON 对象:(等待输入...)"""# ================= 辅助函数:UI透视逻辑 =================def debug_prompt_assembly(dummy_content):"""用于 UI 展示:完全复制 Worker 内部的组装逻辑"""if not dummy_content:dummy_content = "A sacred Thangka painting of a mythological warrior riding a divine horse..."# ⚠️ 这里必须与 worker_task 中的逻辑保持 100% 一致final = (f"{FORCE_STYLE_PREFIX} {dummy_content} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")# 清洗空格final = re.sub(r'\s+', ' ', final).replace(", ,", ",").replace("..", ".")return final# ================= 配置管理类 =================class ConfigManager:@staticmethoddef load_config():defaults = {"splitter_prompt": DEFAULT_SPLITTER_PROMPT,"gen_prompt": DEFAULT_GEN_PROMPT}if os.path.exists(CONFIG_FILE):try:with open(CONFIG_FILE, "r", encoding="utf-8") as f:saved = json.load(f)defaults.update(saved)except Exception as e:print(f"配置文件读取错误: {e}")return defaults@staticmethoddef save_config(splitter_prompt, gen_prompt):try:with open(CONFIG_FILE, "w", encoding="utf-8") as f:json.dump({"splitter_prompt": splitter_prompt,"gen_prompt": gen_prompt}, f, ensure_ascii=False, indent=4)return "✅ 配置已保存!"except Exception as e:return f"❌ 保存失败: {e}"# ================= 核心逻辑类 =================4 unmodified lines"Content-Type": "application/json"}def llm_split_text(self, text_chunk, system_prompt):"""Step 1: 语义切分 (包含重试机制)"""payload = {"model": TEXT_MODEL,"messages": [{"role": "system", "content": system_prompt},{"role": "user", "content": f"请切分以下文本:\n{text_chunk}"}],"response_format": {"type": "json_object"}}for _ in range(3):try:resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=60)if resp.status_code == 200:content = resp.json()['choices'][0]['message']['content'].strip()if "```json" in content: content = content.split("```json")[1].split("```")[0]elif "```" in content: content = content.split("```")[1].split("```")[0]try:result = json.loads(content)if isinstance(result, list): return resultif isinstance(result, dict):# 尝试找 dict 里的 listfor v in result.values():if isinstance(v, list): return vreturn [text_chunk]except: passexcept: time.sleep(1)print("⚠️ LLM 切分失败,使用正则兜底...")return [text_chunk[i:i+120] for i in range(0, len(text_chunk), 120)]def generate_prompts_for_segments(self, segments, system_prompt):"""Step 2: 画面生成 (包含重试机制)"""if not segments: return {}input_list_str = "\n".join([f"ID {i}: {text}" for i, text in enumerate(segments)])payload = {"model": TEXT_MODEL,"messages": [{"role": "system", "content": system_prompt},{"role": "user", "content": f"Generate prompts for these {len(segments)} segments:\n{input_list_str}"}],"response_format": {"type": "json_object"}}for _ in range(3):try:resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=120)if resp.status_code == 200:content = resp.json()['choices'][0]['message']['content'].strip()if "```json" in content: content = content.split("```json")[1].split("```")[0]elif "```" in content: content = content.split("```")[1].split("```")[0]result_dict = json.loads(content)final_map = {}for k, v in result_dict.items():final_map[int(k)] = vreturn final_mapexcept Exception as e:time.sleep(2)return {}class VideoAgent:def __init__(self):8 unmodified linesif res: return resreturn None# ⚠️ 植入暴力重试 + 僵死超时检测逻辑def worker_task(self, prompt, idx, log_queue, save_dir):save_path = os.path.join(save_dir, f"clip_{idx+1:03d}.mp4")# 检查本地(极少数情况)if os.path.exists(save_path) and os.path.getsize(save_path) > 1000:log_queue.put(f"✅ [镜头{idx+1}] 本地已有,跳过。")return save_pathfinal_prompt = (f"{FORCE_STYLE_PREFIX} {prompt} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")# -----------------------------------------------# 🔄 5次重试循环 (Retry Loop)# -----------------------------------------------MAX_RETRIES = 5TASK_TIMEOUT = 600 # 10分钟超时for attempt in range(MAX_RETRIES):prefix_log = f"[镜头{idx+1} | 尝试{attempt+1}/{MAX_RETRIES}]"# 1. 提交任务task_id = Nonetry:create_url = f"{MERCHANT_BASE_URL}/v1/video/create"# ⚠️⚠️⚠️ Veo 模型 Payload 修改 ⚠️⚠️⚠️payload = {"images": [],"model": VEO_MODEL, # 使用配置的 VEO_MODEL"size": VIDEO_SIZE, # 使用配置的 16x9"prompt": final_prompt,"duration": VIDEO_DURATION, # 使用配置的 8秒"watermark": False,"audio": False,"private": True}req = requests.post(create_url, headers=self.headers, json=payload, timeout=60)task_id = req.json().get('data', {}).get('id') or req.json().get('id')if not task_id:log_queue.put(f"⚠️ {prefix_log} 提交失败: {req.text[:30]},准备重试...")time.sleep(2)continueexcept Exception as e:log_queue.put(f"⚠️ {prefix_log} 网络提交错误: {e}")time.sleep(2)continue# 2. 轮询监控 (带超时机制)start_time = time.time()while True:# ⏰ 全局超时检测if time.time() - start_time > TASK_TIMEOUT:log_queue.put(f"⏳ {prefix_log} 任务执行超时(>10min),判定为僵死,强制重试!")breaktime.sleep(5)try:res = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30).json()status = res.get('data', {}).get('status') or res.get('status')if status in ['succeeded', 'success', 'completed']:url = self.deep_find_url(res)if url:log_queue.put(f"⬇️ {prefix_log} 渲染成功,下载中...")v_content = requests.get(url).contentwith open(save_path, "wb") as f: f.write(v_content)log_queue.put(f"✅ [镜头{idx+1}] 下载完毕!")return save_path # 彻底成功,返回elif status == 'failed':fail_msg = res.get('fail_reason') or "未知"log_queue.put(f"❌ {prefix_log} 平台返回失败: {fail_msg},准备重试...")breakexcept Exception as e:# 网络轮询偶尔报错不影响,继续轮询pass# 如果走到这里,说明 while 被 break 了,休息一下继续time.sleep(2)log_queue.put(f"💀 [镜头{idx+1}] 5次重试全部失败,放弃。")return None# ================= 业务流程 (完整逻辑) =================def create_zip_package(file_paths, output_dir):timestamp = int(time.time())zip_name = f"Thangka_Veo_{timestamp}.zip"zip_path = os.path.join(output_dir, zip_name)with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:for file in file_paths:if file and os.path.exists(file): zf.write(file, os.path.basename(file))return zip_pathdef process_one_block_logic(director, block_text, block_id, splitter_prompt, gen_prompt):"""原子化处理:大块 -> 切分 -> 1次API生成Prompt"""segments = director.llm_split_text(block_text, splitter_prompt)if not segments: return block_id, [], {}prompts_map = director.generate_prompts_for_segments(segments, gen_prompt)return block_id, segments, prompts_mapdef process_pipeline(full_text, splitter_prompt, gen_prompt):"""主控流程:物理切分 -> 逻辑并发 -> 视频渲染并发 -> 打包"""if not full_text.strip():yield "❌ 文案不能为空", Nonereturn# ⚠️ 每次运行创建一个唯一的时间戳文件夹timestamp_str = datetime.now().strftime('%Y%m%d_%H%M%S')current_run_dir = os.path.join(BASE_OUTPUT_DIR, f"Task_{timestamp_str}")os.makedirs(current_run_dir, exist_ok=True)log_queue = queue.Queue()logs = []def log(msg):logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")return "\n".join(logs[-300:])yield log(f"🚀 初始化 VEO 引擎... 本次输出目录: {current_run_dir}"), Nonedirector = DirectorAgent()cameraman = VideoAgent()# Step 1: 物理分块raw_blocks = []curr = ""for char in full_text:curr += charif len(curr) >= 1000 and char in ['。', '!', '?', '\n']:raw_blocks.append(curr)curr = ""if curr: raw_blocks.append(curr)yield log(f"📚 长文预处理:物理切分为 {len(raw_blocks)} 个大块。"), Noneyield log(f"⚡️ 正在并发处理所有大块的逻辑 (切分+写分镜)..."), None# Step 2: 并发逻辑处理logic_futures = []block_results = {}with ThreadPoolExecutor(max_workers=LOGIC_WORKERS) as logic_executor:for i, block in enumerate(raw_blocks):f = logic_executor.submit(process_one_block_logic, director, block, i, splitter_prompt, gen_prompt)logic_futures.append(f)for future in as_completed(logic_futures):b_id, segs, p_map = future.result()block_results[b_id] = (segs, p_map)yield log(f"✅ 第 {b_id+1} 大块逻辑处理完成:生成 {len(segs)} 个分镜"), Noneyield log(f"🎬 逻辑层全部完成,准备提交 {VIDEO_WORKERS} 路并发渲染..."), None# Step 3: 渲染video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)video_futures = []global_idx = 0sorted_blocks = sorted(block_results.items())for b_id, (segments, prompts_map) in sorted_blocks:for local_i, text in enumerate(segments):# 获取 Promptprompt = prompts_map.get(local_i)# 降级处理if not prompt:prompt = f"Scene showing: {text[:50]}"log_queue.put(f"⚠️ [镜头{global_idx+1}] 降级提示词")# ⚠️ 将 current_run_dir 传给 worker,强制存到新文件夹f = video_executor.submit(cameraman.worker_task, prompt, global_idx, log_queue, current_run_dir)video_futures.append((global_idx, f))global_idx += 1total_videos = global_idxyield log(f"🚀 已提交 {total_videos} 个 VEO 视频任务,渲染中..."), None# Step 4: 监控done_count = 0while done_count < total_videos:while not log_queue.empty(): yield log(log_queue.get()), Nonedone_count = sum(1 for _, f in video_futures if f.done())time.sleep(0.5)# Step 5: 打包video_paths = [None] * total_videosfor idx, fut in video_futures:try: video_paths[idx] = fut.result()except: passvideo_executor.shutdown(wait=True)valid = [f for f in video_paths if f]if valid:yield log(f"📦 打包 {len(valid)} 个视频..."), Noneyield log("🎉 完成!"), create_zip_package(valid, current_run_dir)else:yield log("❌ 无视频生成"), None# ================= UI 界面 =================cfg = ConfigManager.load_config()def ui_run(text, p1, p2):# 将生成器透传给 Gradioyield from process_pipeline(text, p1, p2)with gr.Blocks(title="Veo 西藏唐卡·风格锁死版") as demo:gr.Markdown(f"## 🎬 Veo 视频生成器 ({VEO_MODEL} 唐卡版)")gr.Markdown("🛡️ **铁律执行中**:Veo 8秒模型 + 强制西藏唐卡风格 + 16x9 画幅")with gr.Row():# 左侧:输入与核心操作with gr.Column(scale=3):in_text = gr.Textbox(label="输入长文案", lines=8, placeholder="粘贴数千字文案...")# --- 提示词透视区 ---with gr.Accordion("🔬 铁律组装透视 (Iron Law Inspector)", open=True):gr.Markdown("👇 **所见即所得**:展示系统如何将你的内容“强制”包装。灰色背景部分为锁死区域。")with gr.Row():preview_input = gr.Textbox(label="模拟 AI 生成的画面描述 (可修改测试)",value="A sacred Thangka painting of a mythological warrior riding a divine horse...",interactive=True,scale=2)preview_btn = gr.Button("⚡ 查看最终组装结果", scale=1)preview_output = gr.Textbox(label="📨 最终发送给 Veo 的 Prompt (实际效果)",lines=6,interactive=False,)# --------------------btn = gr.Button("🚀 启动全自动生成", variant="primary")out_log = gr.Textbox(label="执行日志", lines=10)out_file = gr.File(label="结果下载")# 右侧:配置with gr.Column(scale=2):with gr.Accordion("⚙️ 双阶提示词配置", open=False):p_split = gr.Textbox(label="1. 语义分割提示词", value=cfg["splitter_prompt"], lines=10)p_gen = gr.Textbox(label="2. 画面生成提示词 (动态铁律)", value=cfg["gen_prompt"], lines=15)save_btn = gr.Button("💾 保存配置")save_msg = gr.Label()# 事件绑定# 1. 预览逻辑preview_input.change(fn=debug_prompt_assembly, inputs=preview_input, outputs=preview_output)preview_btn.click(fn=debug_prompt_assembly, inputs=preview_input, outputs=preview_output)demo.load(fn=debug_prompt_assembly, inputs=preview_input, outputs=preview_output)# 2. 运行逻辑btn.click(ui_run, [in_text, p_split, p_gen], [out_log, out_file])save_btn.click(ConfigManager.save_config, [p_split, p_gen], save_msg)if __name__ == "__main__":demo.queue().launch(server_name="0.0.0.0", inbrowser=True)5 unmodified lines67891011121 unmodified line14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091104 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581598 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643655 unmodified linesimport requestsimport zipfileimport queueimport mathfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completed1 unmodified line# 1. 平台鉴权YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"MERCHANT_BASE_URL = "https://yunwu.ai"# 2. 模型核心配置 (VEO 硬切版)VEO_MODEL = "veo_3_1-fast" # Veo 模型VIDEO_SIZE = "16x9" # 16:9 画幅TEXT_MODEL = "gemini-3-pro-preview-thinking"VIDEO_DURATION = 8 # 锁定 8秒SEGMENTS_PER_VIDEO = 8 # 8秒对应8个片段VIDEOS_PER_BATCH = 10 # ⚠️ 修改点:每次LLM生成10个视频的PromptTOTAL_SEGS_PER_LLM = 80 # 每次LLM处理 80 个片段 (10 * 8)# 3. 系统配置BASE_OUTPUT_DIR = "project_thangka_montage_batch"VIDEO_WORKERS = 150 # ⚠️ 修改点:视频渲染并发数提升至 150LLM_WORKERS = 5 # LLM 并发数稍微降低,因为单次负载大了CONFIG_FILE = "montage_config.json"# ================= 风格与动态核武器 (保持不变) =================FORCE_STYLE_PREFIX = ("A sacred Tibetan Thangka painting style on aged cotton canvas. ""Rich mineral pigment colors (ground lapis lazuli, malachite, cinnabar, gold lines). ""Solemn deities, flat perspective with divine aura. ")FORCE_MOTION_BOOSTER = (" , (EXTREME VISUAL VELOCITY: hard cuts every second, stroboscopic editing style, ""hyper-lapse speed, visual explosion, distinct unrelated scenes, frantic energy, ""kaleidoscope effect, elements constantly morphing and breaking, no continuity), ")FORCE_STYLE_SUFFIX = (" , highly detailed Thangka line work (Goujin), traditional cloth texture, masterpiece.")FORCE_NEGATIVE_PROMPT = (" --no slow motion, static, still image, frozen, continuity, smooth transition, ""photorealistic, realistic, 3d render, cgi, blurry, deformed, modern, watermark.")# ================= 批量 Prompt 生成系统 (⚠️ 核心修改) =================DEFAULT_GEN_SYSTEM = """你是一位专门制作【极速快闪蒙太奇】视频的唐卡艺术导演。你的任务是将输入的 **80个短句**(分为10组,每组8句),批量转化为 **10个独立视频** 的提示词。【输入格式】你将收到类似这样的输入:Video 1 Segments: [0-1s]... [1-2s]...Video 2 Segments: [0-1s]......Video 10 Segments: ...【输出目标格式 (JSON List)】必须返回一个包含 10 个对象的 JSON 列表,每个对象对应一个 8秒视频。格式示例:[{"id": 1, "prompt": "(0s-1s) Scene A --HARD CUT TO--> (1s-2s) Scene B..."},{"id": 2, "prompt": "(0s-1s) Scene C --HARD CUT TO--> (1s-2s) Scene D..."},...]【绝对铁律】1. **必须返回 10 个 Prompt**,每个 Prompt 严格对应输入的每一组。2. 每个 Prompt 内部必须包含 8 个硬切画面 `(0s-1s)... (7s-8s)`。3. 风格必须是高燃、快速、唐卡视觉。"""# ================= 工具函数:暴力切分算法 (保持不变) =================def strict_text_splitter(text):chunks = []current_chunk = ""valid_count = 0punctuations = set(",。!?;:、,.;:!?\n\t ")for char in text:current_chunk += charif char not in punctuations:valid_count += 1should_cut = Falseif 15 <= valid_count <= 25:if char in punctuations: should_cut = Trueif valid_count > 25: should_cut = Trueif should_cut:if current_chunk.strip(): chunks.append(current_chunk.strip())current_chunk = ""valid_count = 0if current_chunk.strip(): chunks.append(current_chunk.strip())return chunks# ================= 核心逻辑类 =================4 unmodified lines"Content-Type": "application/json"}def generate_batch_prompts(self, batch_data, system_prompt):"""一次性生成10个视频的Prompt"""# batch_data 是一个 list,包含 10 个组,每个组 8 句话# 组装 Promptuser_msg = "Please generate prompts for the following 10 videos:\n\n"for i, group in enumerate(batch_data):video_text = " | ".join([f"({s}s) {txt}" for s, txt in enumerate(group)])user_msg += f"Video {i+1} Segments: {video_text}\n"payload = {"model": TEXT_MODEL,"messages": [{"role": "system", "content": system_prompt},{"role": "user", "content": user_msg}],"response_format": {"type": "json_object"}}for _ in range(3):try:resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=120)if resp.status_code == 200:content = resp.json()['choices'][0]['message']['content']if "```json" in content: content = content.split("```json")[1].split("```")[0]elif "```" in content: content = content.split("```")[1].split("```")[0]data = json.loads(content)# 兼容 LLM 可能返回 {"prompts": [...]} 或者 直接 [...]if isinstance(data, dict):# 尝试找列表字段for v in data.values():if isinstance(v, list): return vif isinstance(data, list): return dataexcept Exception as e:print(f"LLM Batch Error: {e}")time.sleep(1)# 兜底:生成 10 个简单的占位符return [{"prompt": f"Thangka video batch fallback {i}"} for i in range(len(batch_data))]class VideoAgent:def __init__(self):8 unmodified linesif res: return resreturn Nonedef worker_task(self, prompt, global_video_idx, log_queue, save_dir):"""单个视频渲染任务"""save_path = os.path.join(save_dir, f"clip_{global_video_idx+1:04d}.mp4")if os.path.exists(save_path) and os.path.getsize(save_path) > 1000:log_queue.put(f"✅ [视频{global_video_idx+1}] 本地已有,跳过。")return save_pathfinal_prompt = (f"{FORCE_STYLE_PREFIX} {prompt} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")MAX_RETRIES = 5for attempt in range(MAX_RETRIES):prefix = f"[视频{global_video_idx+1}]"try:# 提交任务payload = {"model": VEO_MODEL,"size": VIDEO_SIZE,"prompt": final_prompt,"duration": VIDEO_DURATION,"watermark": False, "audio": False, "private": True}req = requests.post(f"{MERCHANT_BASE_URL}/v1/video/create", headers=self.headers, json=payload, timeout=60)# 错误处理if req.status_code != 200:log_queue.put(f"⚠️ {prefix} Http Error: {req.status_code}")time.sleep(2)continuetask_id = req.json().get('data', {}).get('id') or req.json().get('id')if not task_id:log_queue.put(f"⚠️ {prefix} 无 Task ID")time.sleep(2)continue# 轮询start_t = time.time()while time.time() - start_t < 600:time.sleep(5)res = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30).json()status = res.get('data', {}).get('status') or res.get('status')if status in ['succeeded', 'success', 'completed']:url = self.deep_find_url(res)if url:log_queue.put(f"⬇️ {prefix} 渲染完成,下载中...")with open(save_path, "wb") as f: f.write(requests.get(url).content)return save_pathelif status == 'failed':log_queue.put(f"❌ {prefix} 失败: {res.get('fail_reason')}")breakexcept Exception as e:log_queue.put(f"⚠️ {prefix} 异常: {e}")time.sleep(2)return None# ================= 业务流程 (批量流水线) =================def create_zip_package(file_paths, output_dir):timestamp = int(time.time())zip_path = os.path.join(output_dir, f"Batch_Veo_{timestamp}.zip")with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:for file in file_paths:if file and os.path.exists(file): zf.write(file, os.path.basename(file))return zip_pathdef process_pipeline(full_text, gen_system_prompt):if not full_text.strip(): yield "❌ 文案不能为空", None; returntimestamp_str = datetime.now().strftime('%Y%m%d_%H%M%S')current_run_dir = os.path.join(BASE_OUTPUT_DIR, f"Task_{timestamp_str}")os.makedirs(current_run_dir, exist_ok=True)log_queue = queue.Queue()logs = []def log(msg):logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")return "\n".join(logs[-300:])yield log("🚀 启动【150并发·极速流水线】..."), None# 1. 切分与重组raw_segments = strict_text_splitter(full_text)total_segments = len(raw_segments)# 按照 8个片段 = 1个视频 组合video_tasks = []for i in range(0, total_segments, SEGMENTS_PER_VIDEO):video_tasks.append(raw_segments[i : i + SEGMENTS_PER_VIDEO])total_videos = len(video_tasks)if total_videos == 0: yield log("❌ 内容太短,无法生成"), None; return# 按照 10个视频 = 1个 LLM Batch 组合llm_batches = []for i in range(0, total_videos, VIDEOS_PER_BATCH):llm_batches.append(video_tasks[i : i + VIDEOS_PER_BATCH])total_batches = len(llm_batches)yield log(f"📦 任务拆解:共 {total_videos} 个视频,拆分为 {total_batches} 个 LLM 批次。"), None# 初始化资源director = DirectorAgent()cameraman = VideoAgent()# 线程池video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)video_futures = [] # 存储 (index, future)# 2. LLM 批次处理 + 即时分发# 我们用一个较小的线程池来跑 LLM,避免把 LLM 请求发炸了with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor:llm_futures = {} # {future: batch_index}for batch_idx, batch_data in enumerate(llm_batches):f = llm_executor.submit(director.generate_batch_prompts, batch_data, gen_system_prompt)llm_futures[f] = batch_idx# 3. 动态接收 LLM 结果并立即分发渲染completed_batches = 0for future in as_completed(llm_futures):batch_idx = llm_futures[future]try:prompts_list = future.result() # 这是一个包含 10 个 prompt dict 的 listcompleted_batches += 1yield log(f"🧠 [Batch {batch_idx+1}] 提示词生成完毕,立即派发 {len(prompts_list)} 个渲染任务..."), None# 计算这个 Batch 对应的全局视频 ID 起始位置start_video_id = batch_idx * VIDEOS_PER_BATCHfor local_i, item in enumerate(prompts_list):prompt_text = item.get("prompt", "") if isinstance(item, dict) else str(item)if not prompt_text: continueglobal_id = start_video_id + local_iif global_id >= total_videos: break # 防止溢出# 🔥 立即提交给 150 并发的 Video Executorvf = video_executor.submit(cameraman.worker_task, prompt_text, global_id, log_queue, current_run_dir)video_futures.append((global_id, vf))except Exception as e:yield log(f"⚠️ [Batch {batch_idx+1}] LLM 处理失败: {e}"), Noneyield log(f"🎬 所有 {total_batches} 个 LLM 批次处理完毕。正在全速渲染..."), None# 4. 监控视频渲染进度video_paths = [None] * total_videosdone_count = 0while done_count < len(video_futures):while not log_queue.empty(): yield log(log_queue.get()), Nonedone_count = sum(1 for _, f in video_futures if f.done())time.sleep(1) # 降低刷新频率# 收集结果for idx, f in video_futures:try: video_paths[idx] = f.result()except: passvideo_executor.shutdown(wait=True)# 5. 打包valid_files = [f for f in video_paths if f]if valid_files:zip_file = create_zip_package(valid_files, current_run_dir)yield log(f"🎉 任务结束!成功 {len(valid_files)}/{total_videos}"), zip_fileelse:yield log("❌ 无视频生成"), None# ================= UI 界面 =================with gr.Blocks(title="Veo 150并发集群版") as demo:gr.Markdown(f"## 🎬 Veo 工业级批量生成器 (80秒/批次)")gr.Markdown("🚀 **架构**:1个LLM请求生成10个视频Prompt -> 瞬间分发给150个渲染Worker")with gr.Row():with gr.Column(scale=3):in_text = gr.Textbox(label="输入文案", lines=8, placeholder="在此粘贴超长文案...")btn = gr.Button("🚀 启动集群渲染 (150并发)", variant="primary")out_log = gr.Textbox(label="集群日志", lines=12)out_file = gr.File(label="结果下载")with gr.Column(scale=2):with gr.Accordion("⚙️ LLM 设定", open=True):system_p = gr.Textbox(label="System Prompt", value=DEFAULT_GEN_SYSTEM, lines=15)btn.click(process_pipeline, [in_text, system_p], [out_log, out_file])if __name__ == "__main__":demo.queue().launch(server_name="0.0.0.0", inbrowser=True)
app.py+219-346