Download app.py from elelabc/1s: direct link, hf CLI and curl.
- Browser
- Download file 28.3 kB
-
https://huggingface.co/spaces/elelabc/1s/resolve/main/app.py
- Command line
-
hf download hf://spaces/elelabc/1s/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elelabc/1s/resolve/main/app.py
28.3 kB
| import sys | |
| import subprocess | |
| import os | |
| import traceback | |
| import shutil | |
| import time | |
| import json | |
| import requests | |
| import zipfile | |
| import queue | |
| import math | |
| import re | |
| import numpy as np | |
| from datetime import datetime | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from difflib import SequenceMatcher | |
| # ========================================== | |
| # 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]) | |
| # 核心依赖 (无 requests_toolbelt) | |
| 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 opencc | |
| from PIL import Image, ImageDraw, ImageFont | |
| 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 | |
| VIDEOS_PER_BATCH = 10 | |
| # 4. 系统配置 (工业级完整参数) | |
| BASE_OUTPUT_DIR = "project_thangka_final_v8_5_srt" | |
| VIDEO_WORKERS = 150 | |
| LLM_WORKERS = 5 | |
| RENDER_PARALLELISM = 4 # 🔥 提升并行度:因为不渲染字幕了,CPU负载变低,可以开大一点 | |
| # 5. 风格与 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 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): | |
| """ 智能切分:15-25字 + 标点控制 """ | |
| 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) | |
| # ================= SRT 字幕生成工具 (新增) ================= | |
| def format_timestamp(seconds): | |
| """ 将秒数转换为 SRT 格式 (00:00:00,000) """ | |
| millis = int((seconds - int(seconds)) * 1000) | |
| seconds = int(seconds) | |
| minutes = seconds // 60 | |
| hours = minutes // 60 | |
| minutes %= 60 | |
| seconds %= 60 | |
| return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}" | |
| def generate_srt_file(subtitle_data, output_path): | |
| """ 生成 SRT 文件 """ | |
| 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_path | |
| # ================= 核心算法1:真理修正 (Text Grounding) ================= | |
| 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'] | |
| if not whisper_text.strip(): continue | |
| search_window = len(whisper_text) + 20 | |
| search_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.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": seg['start'], | |
| "end": seg['end'], | |
| "text": corrected_text | |
| }) | |
| if truth_cursor >= len(truth_clean): break | |
| return corrected_segments | |
| # ================= 核心算法2:V8.0 双锁前瞻对齐 ================= | |
| 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 [8.0] * len(text_segments) | |
| raw_durs = [(L / total_len) * total_audio_duration for L in lengths] | |
| return [max(d, 5.0) for d in raw_durs] | |
| def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue): | |
| if not whisper_segments: | |
| return estimate_durations_fallback(text_segments, total_audio_duration) | |
| video_durations = [] | |
| whisper_idx = 0 | |
| group_start_indices = [0] | |
| for i, segment_texts in enumerate(text_segments): | |
| truth_text = normalize_text("".join(segment_texts)) | |
| target_len = len(truth_text) | |
| acc_len = 0 | |
| acc_text_buffer = "" | |
| while whisper_idx < len(whisper_segments): | |
| seg_text = normalize_text(whisper_segments[whisper_idx]['text']) | |
| acc_text_buffer += seg_text | |
| acc_len += len(seg_text) | |
| whisper_idx += 1 | |
| ratio = acc_len / target_len if target_len > 0 else 1.0 | |
| is_length_in_range = (0.99 <= ratio <= 1.01) | |
| is_content_match = False | |
| if is_length_in_range: | |
| matcher = SequenceMatcher(None, acc_text_buffer, truth_text) | |
| if matcher.ratio() > 0.55: | |
| is_content_match = True | |
| is_overflow = (ratio > 1.01) | |
| if (is_length_in_range and is_content_match) or is_overflow: | |
| break | |
| group_start_indices.append(whisper_idx) | |
| for i in range(len(text_segments)): | |
| start_idx = group_start_indices[i] | |
| end_idx = group_start_indices[i+1] | |
| if start_idx < len(whisper_segments): | |
| t_start = whisper_segments[start_idx]['start'] | |
| else: | |
| t_start = total_audio_duration | |
| if i == len(text_segments) - 1: | |
| t_end = total_audio_duration | |
| else: | |
| if end_idx < len(whisper_segments): | |
| t_end = whisper_segments[end_idx]['start'] | |
| else: | |
| t_end = total_audio_duration | |
| duration = max(2.0, t_end - t_start) | |
| log_queue.put(f"✅ [V8精准对齐] Group {i+1}: {duration:.2f}s") | |
| video_durations.append(duration) | |
| 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. Please REWRITE it to be SAFER. REMOVE ALL references to children." | |
| else: | |
| system_instruction = "The prompt STILL failed. Please rewrite it to be EXTREMELY CONCISE (under 15 words)." | |
| payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_instruction}, {"role": "user", "content": f"Failed Prompt: {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: pass | |
| return old_prompt | |
| def generate_batch_prompts(self, batch_data, system_prompt): | |
| 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 compress_audio(self, input_path, log_queue): | |
| if os.path.getsize(input_path) < 24 * 1024 * 1024: return input_path | |
| log_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_path | |
| except: return input_path | |
| def 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_json | |
| time.sleep(5) | |
| except Exception as e: time.sleep(5) | |
| return None | |
| class VideoAgent: | |
| def __init__(self, director_instance=None): | |
| self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"} | |
| self.director = director_instance | |
| 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 | |
| current_prompt_core = prompt | |
| for rewrite_cycle in range(3): | |
| if rewrite_cycle > 0: | |
| try: | |
| new_core = self.director.rewrite_failed_prompt(current_prompt_core, rewrite_cycle) | |
| if new_core: current_prompt_core = new_core | |
| except: pass | |
| final_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); continue | |
| task_id = req.json().get("id") | |
| if not task_id: continue | |
| log_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中...") | |
| start_time = time.time() | |
| while True: | |
| if time.time() - start_time > 600: break | |
| status_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30) | |
| if status_resp.status_code == 200: | |
| status_data = status_resp.json() | |
| status = status_data.get("status") | |
| if status == "completed": | |
| video_url = status_data.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_path | |
| elif status == "failed": break | |
| time.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) | |
| speed_factor = raw_clip.duration / target_duration | |
| video_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 True | |
| except Exception as e: | |
| log_queue.put(f"❌ [Group {group_id}] 渲染失败: {e}") | |
| return False | |
| def 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.5 纯净版生产线 (SRT Export)...") | |
| try: | |
| ac = AudioFileClip(audio_path) | |
| total_audio = ac.duration | |
| ac.close() | |
| except: return False | |
| # 1. 字幕数据处理 (用于导出 SRT) | |
| final_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"📝 正在生成外挂字幕文件: {os.path.basename(srt_path)}") | |
| generate_srt_file(final_subtitle_data, srt_path) | |
| else: | |
| log_queue.put("⚠️ 无字幕数据,跳过 SRT 生成") | |
| # 2. 时长对齐计算 | |
| if whisper_result and 'segments' in whisper_result: | |
| segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio, log_queue) | |
| else: | |
| segment_durations = estimate_durations_fallback(text_segments, total_audio) | |
| video_files = sorted(video_files) | |
| total_items = min(len(video_files), len(segment_durations)) | |
| # 3. 原子化循环处理 (纯视频拉伸) | |
| 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_d | |
| completed_count = 0 | |
| with ThreadPoolExecutor(max_workers=RENDER_PARALLELISM) as renderer: | |
| future_map = {} | |
| for cfg in group_configs: | |
| f = renderer.submit( | |
| render_atomic_group_final, | |
| cfg['id'], cfg['vid'], cfg['dur'], cfg['start'], | |
| log_queue, cfg['out'] | |
| ) | |
| future_map[f] = cfg['id'] | |
| for f in as_completed(future_map): | |
| if f.result(): completed_count += 1 | |
| # 4. 物理拼接 | |
| log_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) | |
| # 5. 打包 Zip (MP4 + SRT) | |
| log_queue.put("📦 正在打包成品 (视频 + SRT)...") | |
| 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 True | |
| except Exception as e: | |
| log_queue.put(f"❌ 拼接失败: {e}") | |
| 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:]), None | |
| yield update_ui("🚀 系统启动 (V8.5 Pure + SRT)...") | |
| 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} 个视频任务。") | |
| 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 = [] | |
| 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 生成与视频渲染并发中...") | |
| 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 OK") | |
| except: pass | |
| yield update_ui("⏳ 等待所有视频素材就绪...") | |
| 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 update_ui() | |
| 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})") | |
| try: whisper_result = whisper_future.result() | |
| except: whisper_result = None | |
| if len(valid_videos) > 0: | |
| # 最终输出改为 Zip 文件 | |
| output_zip = os.path.join(current_run_dir, "Project_Package.zip") | |
| success = False | |
| with 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 = False | |
| while not log_queue.empty(): | |
| yield update_ui(log_queue.get()) | |
| flushed = True | |
| if 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("🎉🎉🎉 打包成功!请下载 ZIP 文件 (含视频和SRT)"), output_zip | |
| else: | |
| yield update_ui("⚠️ 合成部分失败,提供原始素材包"), create_zip_package(valid_videos, current_run_dir) | |
| else: | |
| yield update_ui("❌ 无视频生成"), None | |
| # ================= UI ================= | |
| with gr.Blocks(title="Veo V8.5 Pure & SRT") as demo: | |
| gr.Markdown("## 🎬 Veo 全自动音画工厂 (V8.5 纯净版 + SRT)") | |
| gr.Markdown("🌟 **特性**:导出无字幕纯净视频 + 配套繁体SRT字幕文件 + 打包下载") | |
| with gr.Row(): | |
| with gr.Column(): | |
| 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) | |
| 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) |