import gradio as gr import os import re import time import json import requests import zipfile import queue import math from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed # ================= 配置区域 ================= # 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个视频的Prompt TOTAL_SEGS_PER_LLM = 80 # 每次LLM处理 80 个片段 (10 * 8) # 3. 系统配置 BASE_OUTPUT_DIR = "project_thangka_montage_batch" VIDEO_WORKERS = 150 # ⚠️ 修改点:视频渲染并发数提升至 150 LLM_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 = 0 punctuations = set(",。!?;:、,.;:!?\n\t ") for char in text: current_chunk += char if char not in punctuations: valid_count += 1 should_cut = False if 15 <= valid_count <= 25: if char in punctuations: should_cut = True if valid_count > 25: should_cut = True if should_cut: if current_chunk.strip(): chunks.append(current_chunk.strip()) current_chunk = "" valid_count = 0 if current_chunk.strip(): chunks.append(current_chunk.strip()) return chunks # ================= 核心逻辑类 ================= class DirectorAgent: def __init__(self): self.headers = { "Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json" } def generate_batch_prompts(self, batch_data, system_prompt): """一次性生成10个视频的Prompt""" # batch_data 是一个 list,包含 10 个组,每个组 8 句话 # 组装 Prompt user_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 v if isinstance(data, list): return data except 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): self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"} def deep_find_url(self, data): if isinstance(data, str) and data.startswith('http') and ('.mp4' in data or '.mov' in data): return data if isinstance(data, dict): for k, v in data.items(): if k in ['url', 'video_url', 'output_url'] and isinstance(v, str) and v.startswith('http'): return v res = self.deep_find_url(v) if res: return res return None def 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_path final_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 = 5 for 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) continue task_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_path elif status == 'failed': log_queue.put(f"❌ {prefix} 失败: {res.get('fail_reason')}") break except 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_path def process_pipeline(full_text, gen_system_prompt): if not full_text.strip(): yield "❌ 文案不能为空", None; return 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("🚀 启动【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 = 0 for future in as_completed(llm_futures): batch_idx = llm_futures[future] try: prompts_list = future.result() # 这是一个包含 10 个 prompt dict 的 list completed_batches += 1 yield log(f"🧠 [Batch {batch_idx+1}] 提示词生成完毕,立即派发 {len(prompts_list)} 个渲染任务..."), None # 计算这个 Batch 对应的全局视频 ID 起始位置 start_video_id = batch_idx * VIDEOS_PER_BATCH for local_i, item in enumerate(prompts_list): prompt_text = item.get("prompt", "") if isinstance(item, dict) else str(item) if not prompt_text: continue global_id = start_video_id + local_i if global_id >= total_videos: break # 防止溢出 # 🔥 立即提交给 150 并发的 Video Executor vf = 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}"), None yield log(f"🎬 所有 {total_batches} 个 LLM 批次处理完毕。正在全速渲染..."), None # 4. 监控视频渲染进度 video_paths = [None] * total_videos done_count = 0 while done_count < len(video_futures): while not log_queue.empty(): yield log(log_queue.get()), None done_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: pass video_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_file else: 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)