Download app.py from elelabc/wenanni: direct link, hf CLI and curl.
- Browser
- Download file 27.6 kB
-
https://huggingface.co/spaces/elelabc/wenanni/resolve/main/app.py
- Command line
-
hf download hf://spaces/elelabc/wenanni/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elelabc/wenanni/resolve/main/app.py
27.6 kB
| import sys | |
| import subprocess | |
| import os | |
| # ========================================== | |
| # 0. 环境自动修复 | |
| # ========================================== | |
| def install_package(package, pip_name=None): | |
| pip_name = pip_name or package | |
| try: | |
| __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("PIL", "Pillow") | |
| install_package("numpy") | |
| install_package("opencc", "opencc-python-reimplemented") | |
| # ========================================== | |
| # 1. 正常导入库 | |
| # ========================================== | |
| import gradio as gr | |
| import re | |
| import time | |
| import json | |
| import requests | |
| import zipfile | |
| import queue | |
| import math | |
| import numpy as np | |
| from datetime import datetime | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from difflib import SequenceMatcher | |
| from PIL import Image, ImageDraw, ImageFont | |
| import opencc | |
| from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, vfx, ImageClip, CompositeVideoClip | |
| # ================= 配置区域 ================= | |
| # 1. 平台鉴权 | |
| YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8" | |
| MERCHANT_BASE_URL = "https://yunwu.ai" | |
| # 2. 模型配置 | |
| VEO_MODEL = "veo_3_1-fast" | |
| VIDEO_SIZE = "16x9" | |
| VIDEO_DURATION_STR = "8" | |
| # 3. 辅助配置 | |
| TEXT_MODEL = "gemini-3-pro-preview-thinking" | |
| WHISPER_MODEL = "whisper-1" | |
| SEGMENTS_PER_VIDEO = 8 # 8小段 = 1个大段 | |
| VIDEOS_PER_BATCH = 10 | |
| # 4. 系统配置 | |
| BASE_OUTPUT_DIR = "project_thangka_final_v6_5" | |
| VIDEO_WORKERS = 150 | |
| LLM_WORKERS = 5 | |
| # 5. 字幕配置 | |
| FONT_URL = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/TraditionalChinese/NotoSansCJKtc-Bold.otf" | |
| LOCAL_FONT_PATH = "NotoSansCJKtc-Bold.otf" | |
| SUBTITLE_FONT_SIZE = 45 | |
| SUBTITLE_BOTTOM_MARGIN = 80 | |
| # ================= 风格与 Prompt 核查 ================= | |
| 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." | |
| ) | |
| # 🔥 [修正] 动态化 System Prompt,移除硬编码数字 | |
| 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. 风格必须是高燃、快速、唐卡视觉。 | |
| """ | |
| # ================= 核心工具函数 ================= | |
| def download_font_if_missing(): | |
| if not os.path.exists(LOCAL_FONT_PATH): | |
| print(f"📥 正在下载繁体中文字体: {LOCAL_FONT_PATH} ...") | |
| try: | |
| r = requests.get(FONT_URL, stream=True) | |
| if r.status_code == 200: | |
| with open(LOCAL_FONT_PATH, 'wb') as f: | |
| for chunk in r.iter_content(chunk_size=1024): | |
| f.write(chunk) | |
| print("✅ 字体下载成功!") | |
| else: | |
| print("⚠️ 字体下载失败") | |
| except Exception as e: | |
| print(f"⚠️ 字体下载异常: {e}") | |
| 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 | |
| def normalize_text(text): | |
| return re.sub(r"[^\w]", "", text) | |
| # ================= 核心算法1:字幕真理修正 ================= | |
| def 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_raw | |
| truth_clean = truth_text_trad.replace("\n", "") | |
| corrected_segments = [] | |
| truth_cursor = 0 | |
| for i, seg in enumerate(whisper_segments): | |
| whisper_text = seg['text'] | |
| start_t = seg['start'] | |
| end_t = seg['end'] | |
| if not whisper_text.strip(): continue | |
| search_window_size = len(whisper_text) + 20 | |
| search_area = truth_clean[truth_cursor : truth_cursor + search_window_size] | |
| 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.size | |
| final_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_cursor | |
| corrected_text = truth_clean[truth_cursor : truth_cursor + final_len] | |
| truth_cursor += final_len | |
| corrected_segments.append({ | |
| "start": start_t, | |
| "end": end_t, | |
| "text": corrected_text | |
| }) | |
| if truth_cursor >= len(truth_clean): break | |
| return corrected_segments | |
| # ================= 核心算法2:三重锁对齐算法 (100字锁 + 16s锁 + 比例锁) ================= | |
| def estimate_durations_fallback(text_segments, total_audio_duration): | |
| lengths = [len("".join(seg)) for seg in text_segments] | |
| total_len = sum(lengths) | |
| if total_len == 0: return [16.0] * len(text_segments) | |
| raw_durs = [(L / total_len) * total_audio_duration for L in lengths] | |
| return [max(d, 16.0) for d in raw_durs] | |
| def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue): | |
| """ | |
| 智能对齐逻辑: | |
| 1. 遍历 Video Group。 | |
| 2. 在 Whisper 中寻找匹配段落。 | |
| 3. 🔥 纠错核心:只有当满足以下所有条件时,才承认匹配成功: | |
| a. 字数匹配比例 > 85% | |
| b. 累计字数 >= 100字 (防止短句误判) | |
| c. 累计时长 >= 16秒 (防止快进) | |
| """ | |
| if not whisper_segments: | |
| return estimate_durations_fallback(text_segments, total_audio_duration) | |
| video_durations = [] | |
| whisper_idx = 0 | |
| total_groups = len(text_segments) | |
| # 连续性保证:上一组的结束就是下一组的开始 | |
| last_group_end_time = 0.0 | |
| for i, segment_texts in enumerate(text_segments): | |
| full_text = "".join(segment_texts) | |
| target_len = len(normalize_text(full_text)) | |
| current_len = 0 | |
| group_start_time = None # 仅用于计算相对时长 | |
| # 🔥 循环查找匹配 | |
| while whisper_idx < len(whisper_segments): | |
| seg = whisper_segments[whisper_idx] | |
| seg_len = len(normalize_text(seg['text'])) | |
| if group_start_time is None: | |
| group_start_time = seg['start'] | |
| current_len += seg_len | |
| # 实时计算当前累积的时长 | |
| current_duration = seg['end'] - group_start_time | |
| whisper_idx += 1 | |
| # 条件1:文字匹配度 > 85% | |
| is_ratio_enough = (current_len >= target_len * 0.85) | |
| # 条件2:🔥 字数硬门槛 >= 100字 (除非原文就很短,但这里每组都>120字) | |
| is_chars_enough = (current_len >= 100) or (current_len >= target_len) | |
| # 条件3:🔥 时长硬门槛 >= 16秒 | |
| is_time_enough = (current_duration >= 16.0) | |
| if is_ratio_enough: | |
| if is_chars_enough and is_time_enough: | |
| # 完美匹配:三把锁全部打开 -> 锁定 | |
| break | |
| else: | |
| # 字数比例够了,但绝对字数太少 或 时间太短 -> 继续吞噬 | |
| # log_queue.put(f"⚠️ Group {i+1} 匹配不足: Len={current_len}, Time={current_duration:.1f}s") | |
| pass | |
| # 确定本组的时间:Start 必须严格等于上一组的 End | |
| start_t = last_group_end_time | |
| if i == total_groups - 1: | |
| # 最后一组:必须负责到底 | |
| end_t = total_audio_duration | |
| log_queue.put(f"🛑 [尾部] Group {i+1} 填满剩余音频至 {end_t}s") | |
| else: | |
| if whisper_idx > 0: | |
| # 正常情况:取当前 whisper 段落的结束时间 | |
| end_t = whisper_segments[whisper_idx-1]['end'] | |
| else: | |
| # 异常情况:没找到任何 whisper 数据 -> 兜底 | |
| end_t = start_t + 16.0 | |
| duration = end_t - start_t | |
| # 最终安全检查 (Double Check) | |
| if duration < 16.0: | |
| log_queue.put(f"⚠️ [强制拉伸] Group {i+1} 仅 {duration:.1f}s,修正为 16.0s") | |
| duration = 16.0 | |
| else: | |
| log_queue.put(f"✅ [精准对齐] Group {i+1}: {duration:.1f}s (字数:{current_len})") | |
| video_durations.append(duration) | |
| last_group_end_time = start_t + duration # 更新指针 | |
| # 最终全局归一化 | |
| current_total = sum(video_durations) | |
| if current_total > 0 and abs(current_total - total_audio_duration) > 0.5: | |
| ratio = total_audio_duration / current_total | |
| video_durations = [d * ratio for d in video_durations] | |
| log_queue.put(f"⚖️ [全局微调] 最终同步系数: {ratio:.3f}") | |
| return video_durations | |
| # ================= Agent 类定义 ================= | |
| 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): | |
| # 动态提示词:告诉LLM这是第几组 | |
| user_msg = f"Please generate prompts for the following {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) | |
| 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) | |
| if isinstance(data, dict): | |
| for v in data.values(): | |
| if isinstance(v, list): return v | |
| if isinstance(data, list): return data | |
| except: 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 transcribe_audio_with_retry(self, 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(audio_path, "rb") as f: | |
| files = {"file": (os.path.basename(audio_path), f, "audio/wav")} | |
| 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: | |
| log_queue.put("✅ [Whisper] 识别成功!") | |
| return res_json | |
| time.sleep(5) | |
| except Exception as e: | |
| log_queue.put(f"⚠️ [Whisper] 网络异常: {e}") | |
| time.sleep(5) | |
| return None | |
| # 🔥 VideoAgent (Highlight7 复刻版) | |
| class VideoAgent: | |
| def __init__(self): | |
| self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"} | |
| 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: | |
| 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("..", ".") | |
| for attempt in range(5): | |
| try: | |
| # 使用 Highlight7 的 /v1/chat/completions 伪装法 | |
| url = f"{MERCHANT_BASE_URL}/v1/chat/completions" | |
| payload = { | |
| "model": VEO_MODEL, | |
| "messages": [{"role": "user", "content": final_prompt}], | |
| "size": VIDEO_SIZE, | |
| "max_tokens": 16384 | |
| } | |
| req = requests.post(url, headers=self.headers, json=payload, timeout=600) | |
| if req.status_code != 200: | |
| try: err_msg = req.json() | |
| except: err_msg = req.text[:100] | |
| log_queue.put(f"❌ [API报错] 视频{global_video_idx+1}: {err_msg}") | |
| time.sleep(2) | |
| continue | |
| resp_json = req.json() | |
| content = resp_json['choices'][0]['message']['content'] | |
| url_match = re.search(r'(https?://[^\s)"]+)', content) | |
| if url_match: | |
| video_url = url_match.group(1) | |
| 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_path | |
| else: | |
| log_queue.put(f"⚠️ [API异常] 无URL: {content[:50]}") | |
| time.sleep(2); continue | |
| except Exception as e: | |
| log_queue.put(f"❌ [连接异常] {e}") | |
| time.sleep(3) | |
| return None | |
| # ================= 剪辑与字幕绘图 ================= | |
| def text_to_image_clip(text, duration, video_w, video_h): | |
| img = Image.new('RGBA', (video_w, video_h), (0, 0, 0, 0)) | |
| draw = ImageDraw.Draw(img) | |
| try: | |
| font = ImageFont.truetype(LOCAL_FONT_PATH, SUBTITLE_FONT_SIZE) | |
| except: | |
| font = ImageFont.load_default() | |
| try: | |
| left, top, right, bottom = draw.textbbox((0, 0), text, font=font) | |
| text_w = right - left | |
| text_h = bottom - top | |
| except: | |
| text_w, text_h = draw.textsize(text, font=font) | |
| x = (video_w - text_w) / 2 | |
| y = video_h - SUBTITLE_BOTTOM_MARGIN - text_h | |
| stroke_width = 3 | |
| draw.text((x-stroke_width, y), text, font=font, fill='black') | |
| draw.text((x+stroke_width, y), text, font=font, fill='black') | |
| draw.text((x, y-stroke_width), text, font=font, fill='black') | |
| draw.text((x, y+stroke_width), text, font=font, fill='black') | |
| draw.text((x, y), text, font=font, fill='white') | |
| return ImageClip(np.array(img), duration=duration) | |
| def create_subtitle_clips_pil(corrected_segments, video_w, video_h, log_queue): | |
| subtitle_clips = [] | |
| if not corrected_segments: return [] | |
| log_queue.put(f"🔤 正在绘制 {len(corrected_segments)} 条字幕图层...") | |
| for seg in corrected_segments: | |
| start_time = seg['start'] | |
| end_time = seg['end'] | |
| text = seg['text'].strip() | |
| duration = end_time - start_time | |
| if not text or duration <= 0: continue | |
| try: | |
| txt_clip = text_to_image_clip(text, duration, video_w, video_h) | |
| txt_clip = txt_clip.set_start(start_time).set_position(('center', 'top')) | |
| subtitle_clips.append(txt_clip) | |
| except Exception as e: | |
| print(f"字幕绘制错误: {e}") | |
| return subtitle_clips | |
| def align_and_edit_videos(video_files, audio_path, text_segments, whisper_result, full_truth_text, log_queue, output_path): | |
| log_queue.put("✂️ 进入智能剪辑实验室...") | |
| try: | |
| audio_clip = AudioFileClip(audio_path) | |
| total_audio_duration = audio_clip.duration | |
| audio_clip.close() | |
| except Exception as e: | |
| log_queue.put(f"❌ 音频文件读取失败: {e}") | |
| return False | |
| # 1. 修正字幕 | |
| final_subtitle_data = [] | |
| if whisper_result and 'segments' in whisper_result: | |
| final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], log_queue) | |
| else: | |
| log_queue.put("⚠️ Whisper 失败,无法生成字幕。") | |
| # 2. 视频对齐 (三重锁版) | |
| if whisper_result and 'segments' in whisper_result: | |
| segment_durations = calculate_video_durations_from_whisper( | |
| text_segments, | |
| whisper_result['segments'], | |
| total_audio_duration, | |
| log_queue | |
| ) | |
| else: | |
| segment_durations = estimate_durations_fallback(text_segments, total_audio_duration) | |
| # 3. 视频合成 | |
| final_clips = [] | |
| video_files = sorted(video_files) | |
| min_len = min(len(video_files), len(segment_durations)) | |
| log_queue.put(f"🎞️ 开始处理 {min_len} 个视频片段 (变速对齐中)...") | |
| for i in range(min_len): | |
| vid_path = video_files[i] | |
| target_d = segment_durations[i] | |
| try: | |
| clip = VideoFileClip(vid_path) | |
| factor = clip.duration / target_d | |
| new_clip = clip.fx(vfx.speedx, factor=factor) | |
| final_clips.append(new_clip) | |
| except: continue | |
| if not final_clips: return False | |
| log_queue.put("🔗 正在进行最终渲染...") | |
| try: | |
| concatenated_video = concatenate_videoclips(final_clips, method="compose") | |
| audio = AudioFileClip(audio_path) | |
| # 强制对齐 (此时视频总长应完美等于音频) | |
| concatenated_video = concatenated_video.set_audio(audio) | |
| concatenated_video = concatenated_video.set_duration(audio.duration) | |
| final_video_to_render = concatenated_video | |
| if final_subtitle_data: | |
| download_font_if_missing() | |
| sub_clips = create_subtitle_clips_pil(final_subtitle_data, concatenated_video.w, concatenated_video.h, log_queue) | |
| if sub_clips: | |
| log_queue.put(f"🖼️ 叠加字幕层...") | |
| final_video_to_render = CompositeVideoClip([concatenated_video] + sub_clips) | |
| final_video_to_render = final_video_to_render.set_audio(audio) | |
| final_video_to_render = final_video_to_render.set_duration(audio.duration) | |
| final_video_to_render.write_videofile(output_path, fps=24, codec="libx264", audio_codec="aac", threads=4, preset='medium', logger=None) | |
| audio.close() | |
| concatenated_video.close() | |
| if final_video_to_render != concatenated_video: final_video_to_render.close() | |
| for c in final_clips: c.close() | |
| return True | |
| except Exception as e: | |
| log_queue.put(f"❌ [渲染崩溃] {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return False | |
| # ================= 业务主流程 ================= | |
| 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, audio_file, gen_system_prompt): | |
| if not full_text.strip(): yield "❌ 文案不能为空", None; return | |
| if not audio_file: 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 update_ui(new_msg=None): | |
| if new_msg: logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {new_msg}") | |
| return "\n".join(logs[-100:]) | |
| yield update_ui("🚀 系统启动 (V6.5 动态提示词 + 字数硬门槛)..."), None | |
| download_font_if_missing() | |
| raw_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} 个视频。"), None | |
| yield update_ui("🎙️ Whisper 语音识别任务已提交..."), None | |
| audio_agent = AudioAgent() | |
| whisper_future = ThreadPoolExecutor(1).submit(audio_agent.transcribe_audio_with_retry, audio_file, log_queue) | |
| director = DirectorAgent() | |
| cameraman = VideoAgent() | |
| llm_batches = [] | |
| for i in range(0, total_videos, VIDEOS_PER_BATCH): | |
| llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH]) | |
| video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS) | |
| video_futures = [] | |
| yield update_ui(f"🧠 开始并行生成 Prompt..."), None | |
| with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor: | |
| llm_future_map = {} | |
| for b_idx, batch in enumerate(llm_batches): | |
| f = llm_executor.submit(director.generate_batch_prompts, batch, gen_system_prompt) | |
| llm_future_map[f] = b_idx | |
| for future in as_completed(llm_future_map): | |
| b_idx = llm_future_map[future] | |
| try: | |
| prompts = future.result() | |
| start_id = b_idx * VIDEOS_PER_BATCH | |
| for i, p_obj in enumerate(prompts): | |
| p_text = p_obj.get("prompt", "") if isinstance(p_obj, dict) else str(p_obj) | |
| gid = start_id + i | |
| if gid < total_videos: | |
| vf = video_executor.submit(cameraman.worker_task, p_text, gid, log_queue, current_run_dir) | |
| video_futures.append((gid, vf)) | |
| yield update_ui(f"⚡ [Batch {b_idx+1}] Prompt生成完毕"), None | |
| except Exception as e: | |
| yield update_ui(f"❌ [Batch {b_idx+1}] 失败: {e}"), None | |
| yield update_ui("⏳ 全速渲染中..."), None | |
| video_paths = [None] * total_videos | |
| last_log_time = 0 | |
| while True: | |
| has_new_log = False | |
| while not log_queue.empty(): | |
| msg = log_queue.get() | |
| logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}") | |
| has_new_log = True | |
| done_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 "\n".join(logs[-100:]), None | |
| last_log_time = time.time() | |
| if done_count >= len(video_futures) and whisper_done: break | |
| time.sleep(0.5) | |
| for idx, f in video_futures: | |
| try: video_paths[idx] = f.result() | |
| except: pass | |
| valid_videos = [v for v in video_paths if v] | |
| yield update_ui(f"🎬 视频素材准备就绪 ({len(valid_videos)}/{total_videos})"), None | |
| try: whisper_result = whisper_future.result() | |
| except: whisper_result = None | |
| if len(valid_videos) > 0: | |
| output_mp4 = os.path.join(current_run_dir, "final_synced_video.mp4") | |
| success = align_and_edit_videos(valid_videos, audio_file, video_text_groups[:len(valid_videos)], whisper_result, full_text, log_queue, output_mp4) | |
| while not log_queue.empty(): update_ui(log_queue.get()) | |
| if success: | |
| yield update_ui("🎉🎉🎉 恭喜!繁体精准字幕版生成成功!"), output_mp4 | |
| else: | |
| yield update_ui("⚠️ 自动剪辑失败,仅提供素材包"), create_zip_package(valid_videos, current_run_dir) | |
| else: | |
| yield update_ui("❌ 无有效视频"), None | |
| # ================= UI 界面 ================= | |
| with gr.Blocks(title="Veo V6.5") as demo: | |
| gr.Markdown("## 🎬 Veo 全自动音画工厂 (V6.5 动态版)") | |
| gr.Markdown("🌟 **特性**:字数锁(>100) | 动态Prompt | Highlight7 API") | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| in_text = gr.Textbox(label="1. 输入长文案", lines=8) | |
| in_audio = gr.Audio(label="2. 上传TTS音频", type="filepath") | |
| btn = gr.Button("🚀 启动", variant="primary") | |
| out_log = gr.Textbox(label="实时执行日志", lines=15) | |
| 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, in_audio, system_p], [out_log, out_file]) | |
| if __name__ == "__main__": | |
| demo.queue().launch(server_name="0.0.0.0", inbrowser=True) |