Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363712 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381 unmodified line140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365import gradio as grimport osimport reimport timeimport jsonimport requestsimport zipfileimport queueimport mathfrom datetime import datetimefrom 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个视频的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. "12 unmodified lines)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# ================= 核心逻辑类 =================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 句话# 组装 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)1 unmodified linecontent = 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):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 dataif 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 vres = self.deep_find_url(v)if 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565712 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233241 unmodified line326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610import sysimport subprocessimport osimport tracebackimport shutilimport timeimport jsonimport requestsimport zipfileimport queueimport mathimport reimport numpy as npfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher# ==========================================# 0. 环境自动修复# ==========================================def install_package(package, pip_name=None):pip_name = pip_name or packagetry:__import__(package)except ImportError:print(f"📦 正在自动安装缺失库: {pip_name} ...")subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])install_package("moviepy", "moviepy==1.0.3")install_package("whisper", "openai-whisper")install_package("opencc", "opencc-python-reimplemented")install_package("PIL", "Pillow")import gradio as grimport openccfrom moviepy.editor import VideoFileClip, AudioFileClip, vfx, CompositeVideoClip# ================= 配置区域 =================YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"MERCHANT_BASE_URL = "https://yunwu.ai"VEO_MODEL = "veo3.1-fast-components"VIDEO_SIZE = "16x9"VIDEO_DURATION_STR = "8"TEXT_MODEL = "gemini-3-pro-preview-thinking"WHISPER_MODEL = "whisper-1"SEGMENTS_PER_VIDEO = 8VIDEOS_PER_BATCH = 10BASE_OUTPUT_DIR = "project_thangka_final_v8_9_anchor"VIDEO_WORKERS = 150LLM_WORKERS = 5RENDER_PARALLELISM = 4FORCE_STYLE_PREFIX = ("A sacred Tibetan Thangka painting style on aged cotton canvas. "12 unmodified lines)FORCE_NEGATIVE_PROMPT = (" --no child, children, kid, baby, toddler, minor, schoolboy, schoolgirl, young boy, young girl, ""slow motion, static, still image, frozen, continuity, smooth transition, ""photorealistic, realistic, 3d render, cgi, blurry, deformed, modern, watermark.")DEFAULT_GEN_SYSTEM = """你是一位专门制作【极速快闪蒙太奇】视频的唐卡艺术导演。你的任务是将输入的 **文案段落**(每段包含8个短句),批量转化为 **对应数量的独立视频** 的提示词。【输入格式】你将收到类似这样的输入:Video 1 Segments: [0-1s]... [1-2s]...Video 2 Segments: ......【输出目标格式 (JSON List)】必须返回一个包含对应数量对象的 JSON 列表,每个对象对应一个 8秒视频。格式示例:[{"id": 1, "prompt": "(0s-1s) Scene A --HARD CUT TO--> (1s-2s) Scene B..."},...]【绝对铁律】1. **必须返回与输入数量一致的 Prompt**。2. 每个 Prompt 内部必须包含 8 个硬切画面。3. 风格必须是高燃、快速、唐卡视觉。4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。"""# ================= 核心工具函数 =================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())if len(chunks) > 1 and len(chunks[-1]) < 8:last_short = chunks.pop()chunks[-1] += last_shortreturn chunksdef normalize_text(text):return re.sub(r"[^\w]", "", text)def format_timestamp(seconds):millis = int((seconds - int(seconds)) * 1000)seconds = int(seconds)minutes = seconds // 60hours = minutes // 60minutes %= 60seconds %= 60return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"def generate_srt_file(subtitle_data, output_path):with open(output_path, 'w', encoding='utf-8') as f:for i, sub in enumerate(subtitle_data):start_str = format_timestamp(sub['start'])end_str = format_timestamp(sub['end'])text = sub['text']f.write(f"{i+1}\n{start_str} --> {end_str}\n{text}\n\n")return output_pathdef align_transcript_with_truth(truth_text_raw, whisper_segments, log_queue):log_queue.put("🔄 正在执行【字幕真理修正】...")try:cc = opencc.OpenCC('s2t')truth_text_trad = cc.convert(truth_text_raw)except:truth_text_trad = truth_text_rawtruth_clean = truth_text_trad.replace("\n", "")corrected_segments = []truth_cursor = 0for i, seg in enumerate(whisper_segments):whisper_text = seg['text']if not whisper_text.strip(): continuesearch_window = len(whisper_text) + 20search_area = truth_clean[truth_cursor : truth_cursor + search_window]matcher = SequenceMatcher(None, whisper_text, search_area)match = matcher.find_longest_match(0, len(whisper_text), 0, len(search_area))if match.size > 1:current_text_len = match.b + match.sizefinal_len = max(len(whisper_text), current_text_len)else:final_len = len(whisper_text)if truth_cursor + final_len > len(truth_clean):final_len = len(truth_clean) - truth_cursorcorrected_text = truth_clean[truth_cursor : truth_cursor + final_len]truth_cursor += final_lencorrected_segments.append({"start": seg['start'], "end": seg['end'], "text": corrected_text})if truth_cursor >= len(truth_clean): breakreturn corrected_segments# ================= 核心算法:V8.9 锚点纠偏对齐 (Anchor Correction) =================def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue):"""V8.9 核心逻辑:锚点纠偏 + 局部线性插值解决停顿累积误差问题,确保“字音同步,误差不过夜”。"""log_queue.put("⚓ 正在执行锚点纠偏对齐 (V8.9 Anti-Drift)...")if not whisper_segments:lengths = [len("".join(seg)) for seg in text_segments]total_len = sum(lengths)return [max(5.0, (l/total_len)*total_audio_duration) for l in lengths]# 1. 扁平化源文案,并记录每个 Group 的【绝对字符索引区间】source_full_text = ""group_char_ranges = [] # [(start_idx, end_idx), ...]current_char_idx = 0for seg_list in text_segments:group_text = normalize_text("".join(seg_list))length = len(group_text)group_char_ranges.append((current_char_idx, current_char_idx + length))source_full_text += group_textcurrent_char_idx += length# 2. 扁平化 Whisper,建立【字符 -> 时间戳】的精确映射表# 关键改进:这里会保留 Whisper 原生的时间锚点,只在锚点内部插值char_time_map = {} # {char_global_index_in_whisper: timestamp}whisper_full_text = ""w_cursor = 0for seg in whisper_segments:seg_text = normalize_text(seg['text'])if not seg_text: continuestart_t = seg['start']end_t = seg['end']duration = end_t - start_tseg_len = len(seg_text)# 记录这段 Whisper 对应全局文本的索引范围seg_start_idx = w_cursor# 局部插值:只在这一句 Whisper 内部平分时间# 这样即便这一句和下一句之间有 10秒停顿,也不会影响插值计算for i in range(seg_len):t = start_t + (i / seg_len) * durationchar_time_map[seg_start_idx + i] = twhisper_full_text += seg_textw_cursor += seg_len# 3. 全局对齐:找出 Source Text 每个字符对应 Whisper Text 的哪个字���matcher = SequenceMatcher(None, source_full_text, whisper_full_text)source_to_whisper_index = {}for tag, i1, i2, j1, j2 in matcher.get_opcodes():if tag == 'equal':for k in range(i2 - i1):source_to_whisper_index[i1 + k] = j1 + kelif tag == 'replace':s_len = i2 - i1w_len = j2 - j1for k in range(s_len):w_idx = j1 + int((k / s_len) * w_len)source_to_whisper_index[i1 + k] = min(w_idx, j2 - 1)# insert/delete 不处理,保持空缺# 4. 计算切割点 (Cut Points)# 逻辑:查找每个 Group 的【开始字符】对应的时间戳cut_points = []last_valid_time = 0.0for i, (start_char, end_char) in enumerate(group_char_ranges):# 找这个 Group 第一个字对应的时间# 如果第一个字没对上,就找第二个字... 最多找5个字found_time = Nonefor offset in range(min(5, end_char - start_char)):target = start_char + offsetif target in source_to_whisper_index:w_idx = source_to_whisper_index[target]if w_idx in char_time_map:found_time = char_time_map[w_idx]breakif found_time is not None:# 必须保证时间单调递增if found_time < last_valid_time:found_time = last_valid_timecut_points.append(found_time)last_valid_time = found_timeelse:# 如果完全没找到(极其罕见),就沿用上一个时间cut_points.append(last_valid_time)# 添加结束点 (音频总长)cut_points.append(total_audio_duration)# 5. 生成最终 Durations 并处理停顿间隙video_durations = []for i in range(len(text_segments)):t_start = cut_points[i]t_end = cut_points[i+1]# 核心逻辑:这里的 t_end 实际上是【下一段话的开始时间】# 所以 t_end - t_start 已经自动包含了【这一段话说完后的停顿时间】# 比如:Group 1 结束在 5s,Group 2 开始在 7s (中间停顿2s)# 那么 Group 1 的时长就是 7s - 0s = 7s。# 画面会一直延续到 Group 2 开始说话,完美覆盖停顿。dur = t_end - t_start# 最小保底final_dur = max(2.0, dur)video_durations.append(final_dur)log_queue.put(f"⚓ [Group {i+1}] 锚点: {t_start:.2f}s -> {t_end:.2f}s (时长: {final_dur:.2f}s)")return video_durations# ================= Agent 类 =================class DirectorAgent:def __init__(self):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"}def rewrite_failed_prompt(self, old_prompt, level):if level == 1: system_instruction = "The previous video prompt failed. REWRITE it to be SAFER. REMOVE ALL references to children."else: system_instruction = "Prompt FAILED. Rewrite EXTREMELY CONCISE (under 10 words)."payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_instruction}, {"role": "user", "content": f"Failed: {old_prompt}"}]}try:resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=60)if resp.status_code == 200: return resp.json()['choices'][0]['message']['content'].strip()except: passreturn old_promptdef generate_batch_prompts(self, batch_data, system_prompt):user_msg = f"Generate prompts for {len(batch_data)} 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)1 unmodified linecontent = 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)if isinstance(data, dict):for v in data.values():if isinstance(v, list): return vif isinstance(data, list): return dataexcept: time.sleep(1)return [{"prompt": f"Fallback prompt {i}"} for i in range(len(batch_data))]class AudioAgent:def __init__(self):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}def compress_audio(self, input_path, log_queue):if os.path.getsize(input_path) < 24 * 1024 * 1024: return input_pathlog_queue.put(f"📦 音频文件过大,正在压缩...")output_path = input_path.rsplit('.', 1)[0] + "_compressed.mp3"try:subprocess.run(["ffmpeg", "-y", "-i", input_path, "-ar", "16000", "-ac", "1", "-b:a", "32k", output_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)return output_pathexcept: return input_pathdef transcribe_audio_with_retry(self, audio_path, log_queue):upload_path = self.compress_audio(audio_path, log_queue)url = f"{MERCHANT_BASE_URL}/v1/audio/transcriptions"for attempt in range(3):try:log_queue.put(f"🎙️ Whisper 识别中 ({attempt+1}/3)...")with open(upload_path, "rb") as f:files = {"file": (os.path.basename(upload_path), f, "audio/mp3")}data = {"model": WHISPER_MODEL, "response_format": "verbose_json", "timestamp_granularities[]": "segment"}resp = requests.post(url, headers=self.headers, files=files, data=data, timeout=600)if resp.status_code == 200:res_json = resp.json()if 'words' in res_json or 'segments' in res_json: return res_jsontime.sleep(5)except: time.sleep(5)return Noneclass VideoAgent:def __init__(self, director_instance=None):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}self.director = director_instancedef 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: return save_pathcurrent_prompt_core = promptfor rewrite_cycle in range(3):if rewrite_cycle > 0:try: new_core = self.director.rewrite_failed_prompt(current_prompt_core, rewrite_cycle); current_prompt_core = new_core if new_core else current_prompt_coreexcept: passfinal_prompt = (f"{FORCE_STYLE_PREFIX} {current_prompt_core} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")for attempt in range(5):try:files_payload = {'model': (None, VEO_MODEL), 'prompt': (None, final_prompt), 'seconds': (None, str(VIDEO_DURATION_STR)), 'size': (None, VIDEO_SIZE)}req = requests.post(f"{MERCHANT_BASE_URL}/v1/videos", headers=self.headers, files=files_payload, timeout=60)if req.status_code != 200: time.sleep(2); continuetask_id = req.json().get("id")if not task_id: continuelog_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中...")start_time = time.time()while True:if time.time() - start_time > 600: breakstatus_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30)if status_resp.status_code == 200:status = status_resp.json().get("status")if status == "completed":video_url = status_resp.json().get("video_url")if video_url:with open(save_path, "wb") as f: f.write(requests.get(video_url, timeout=120).content)log_queue.put(f"⬇️ 视频{global_video_idx+1} 下载完成")return save_pathelif status == "failed": breaktime.sleep(3)else: time.sleep(3)except: time.sleep(3)return None# ================= 渲染核心 =================def render_atomic_group_final(group_id, vid_path, target_duration, global_start, log_queue, output_filename):log_queue.put(f"🟫 [Group {group_id}] 渲染中 (时长:{target_duration:.1f}s)...")try:raw_clip = VideoFileClip(vid_path)if target_duration < 0.5: target_duration = 0.5speed_factor = raw_clip.duration / target_durationvideo_clip = raw_clip.fx(vfx.speedx, factor=speed_factor)video_clip.write_videofile(output_filename, fps=24, codec="libx264", audio=False, threads=2, preset='ultrafast', ffmpeg_params=["-crf", "26"], logger=None)video_clip.close(); raw_clip.close()return Trueexcept Exception as e:log_queue.put(f"❌ [Group {group_id}] 渲染失败: {e}")return Falsedef align_and_edit_videos_production(video_files, audio_path, text_segments, whisper_result, full_truth_text, log_queue, output_zip_path):log_queue.put(f"🏭 启动 V8.9 生产线 (锚点纠偏版)...")try: ac = AudioFileClip(audio_path); total_audio = ac.duration; ac.close()except: return Falsefinal_subtitle_data = []srt_path = output_zip_path.replace(".zip", ".srt")if whisper_result and 'segments' in whisper_result:final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], log_queue)log_queue.put(f"📝 生成SRT: {os.path.basename(srt_path)}")generate_srt_file(final_subtitle_data, srt_path)if whisper_result and 'segments' in whisper_result:# 🔥 V8.9 核心调用segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio, log_queue)else:log_queue.put("⚠️ Whisper 失败,使用纯字数比例分配")lengths = [len("".join(s)) for s in text_segments]total_len = sum(lengths)segment_durations = [(l/total_len)*total_audio for l in lengths]video_files = sorted(video_files)total_items = min(len(video_files), len(segment_durations))temp_dir = os.path.dirname(output_zip_path); chunk_dir = os.path.join(temp_dir, "chunks_temp"); os.makedirs(chunk_dir, exist_ok=True)global_cursor = 0.0; group_configs = []for i in range(total_items):target_d = segment_durations[i]group_configs.append({'id': i + 1, 'vid': video_files[i], 'dur': target_d, 'start': global_cursor, 'out': os.path.join(chunk_dir, f"part_{i+1:04d}.mp4")})global_cursor += target_dcompleted_count = 0with ThreadPoolExecutor(max_workers=RENDER_PARALLELISM) as renderer:future_map = {renderer.submit(render_atomic_group_final, cfg['id'], cfg['vid'], cfg['dur'], cfg['start'], log_queue, cfg['out']): cfg['id'] for cfg in group_configs}for f in as_completed(future_map):if f.result(): completed_count += 1log_queue.put("🔗 最终拼接...")list_file_path = os.path.join(chunk_dir, "concat_list.txt"); temp_silent_full = os.path.join(chunk_dir, "full_silent.mp4"); final_mp4_path = output_zip_path.replace(".zip", ".mp4")valid_chunks = sorted([os.path.join(chunk_dir, f) for f in os.listdir(chunk_dir) if f.startswith("part_") and f.endswith(".mp4")])with open(list_file_path, "w", encoding="utf-8") as f:for p in valid_chunks: f.write(f"file '{os.path.abspath(p)}'\n")try:subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)log_queue.put("🎵 注入音频...")subprocess.run(["ffmpeg", "-y", "-i", temp_silent_full, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-map", "0:v:0", "-map", "1:a:0", "-shortest", final_mp4_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)shutil.rmtree(chunk_dir, ignore_errors=True)log_queue.put("📦 打包 ZIP...")with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:zf.write(final_mp4_path, os.path.basename(final_mp4_path))if os.path.exists(srt_path): zf.write(srt_path, os.path.basename(srt_path))return Trueexcept Exception as e:log_queue.put(f"❌ 拼接/打包失败: {e}")return Falsedef 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# ================= 辅助函数:读取TXT文件 =================def read_txt_file(file_obj):if file_obj is None:return ""try:with open(file_obj.name, 'r', encoding='utf-8') as f:return f.read()except Exception as e:return f"读取失败: {str(e)}"# ================= 主流程函数 =================def process_pipeline(full_text, audio_file, gen_system_prompt, txt_file_ref):if not full_text.strip(): yield "❌ 文案不能为空", None; returnif not audio_file: 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 update_ui(new_msg=None):if new_msg: logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {new_msg}")return "\n".join(logs[-100:]), Noneyield update_ui("🚀 系统启动 (V8.9 锚点纠偏版)...")# === 决定 ZIP 文件名 ===zip_basename = "Project_Package_V8_9"if txt_file_ref is not None:try:# 提取上传文件的文件名(不含扩展名)original_filename = os.path.basename(txt_file_ref.name)zip_basename = os.path.splitext(original_filename)[0]yield update_ui(f"🏷️ 将使用文件名打包: {zip_basename}.zip")except:passraw_segments = strict_text_splitter(full_text)video_text_groups = []for i in range(0, len(raw_segments), SEGMENTS_PER_VIDEO): video_text_groups.append(raw_segments[i : i + SEGMENTS_PER_VIDEO])total_videos = len(video_text_groups)yield update_ui(f"📄 共 {len(raw_segments)} 小节,{total_videos} 个视频任务。")yield update_ui("🎙️ Whisper 任务提交...")audio_agent = AudioAgent()whisper_future = ThreadPoolExecutor(1).submit(audio_agent.transcribe_audio_with_retry, audio_file, log_queue)director = DirectorAgent(); cameraman = VideoAgent(director_instance=director)llm_batches = []; video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS); video_futures = []for i in range(0, total_videos, VIDEOS_PER_BATCH): llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH])yield update_ui(f"🧠 Prompt 生成与视频渲染并发中...")with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor:llm_future_map = {llm_executor.submit(director.generate_batch_prompts, batch, gen_system_prompt): b_idx for b_idx, batch in enumerate(llm_batches)}for future in as_completed(llm_future_map):b_idx = llm_future_map[future]try:prompts = future.result(); start_id = b_idx * VIDEOS_PER_BATCHfor i, p_obj in enumerate(prompts):p_text = p_obj.get("prompt", "") if isinstance(p_obj, dict) else str(p_obj)gid = start_id + iif gid < total_videos: video_futures.append((gid, video_executor.submit(cameraman.worker_task, p_text, gid, log_queue, current_run_dir)))yield update_ui(f"⚡ Batch {b_idx+1} Prompt OK")except: passyield update_ui("⏳ 等待所有视频素材就绪...")video_paths = [None] * total_videos; last_log_time = 0while True:has_new_log = Falsewhile not log_queue.empty(): msg = log_queue.get(); logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}"); has_new_log = Truedone_count = sum(1 for _, f in video_futures if f.done()); whisper_done = whisper_future.done()if has_new_log or (time.time() - last_log_time > 1): yield update_ui(); last_log_time = time.time()if done_count >= len(video_futures) and whisper_done: breaktime.sleep(0.5)for idx, f in video_futures:try: video_paths[idx] = f.result()except: passvalid_videos = [v for v in video_paths if v]; yield update_ui(f"🎬 素材下载完毕 ({len(valid_videos)}/{total_videos})")try: whisper_result = whisper_future.result()except: whisper_result = Noneif len(valid_videos) > 0:# 使用之前提取的文件名output_zip = os.path.join(current_run_dir, f"{zip_basename}.zip")success = Falsewith ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(align_and_edit_videos_production, valid_videos, audio_file, video_text_groups[:len(valid_videos)], whisper_result, full_text, log_queue, output_zip)while not future.done():flushed = Falsewhile not log_queue.empty(): yield update_ui(log_queue.get()); flushed = Trueif not flushed: time.sleep(0.1)while not log_queue.empty(): yield update_ui(log_queue.get())success = future.result()if success: yield update_ui("🎉🎉🎉 打包成功!"), output_zipelse: yield update_ui("⚠️ 失败"), create_zip_package(valid_videos, current_run_dir)else: yield update_ui("❌ 无视频生成"), Nonewith gr.Blocks(title="Veo V8.9 Anchor Correction") as demo:gr.Markdown("## 🎬 Veo V8.9 锚点纠偏版")gr.Markdown("🌟 **特性**:分段锚定插值 + 自动吸收停顿 + 误差每句清零")with gr.Row():with gr.Column():# 新增:直接上传TXT文件txt_input_file = gr.File(label="0. 拖入文案TXT文件 (解析后自动填入下方)", file_types=[".txt"])in_text = gr.Textbox(label="1. 解析后的文案 (可手动修改)", lines=8)in_audio = gr.Audio(label="2. 上传TTS音频", type="filepath")btn = gr.Button("🚀 启动生产", variant="primary")with gr.Column():out_log = gr.Textbox(label="实时执行日志", lines=20)out_file = gr.File(label="最终成品 (ZIP包)")with gr.Accordion("⚙️ LLM 设定", open=False):system_p = gr.Textbox(label="System Prompt", value=DEFAULT_GEN_SYSTEM, lines=5)# 绑定事件:上传文件后,读取内容并填入 in_texttxt_input_file.change(read_txt_file, inputs=txt_input_file, outputs=in_text)# 绑定事件:点击按钮时,额外传入 txt_input_file 以便获取文件名btn.click(process_pipeline, [in_text, in_audio, system_p, txt_input_file], [out_log, out_file])if __name__ == "__main__":demo.queue().launch(server_name="0.0.0.0", inbrowser=True)
app.py+480-235