Update app.py
Browse files10 unmodified lines1112131415161722 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510627 unmodified lines13413513613713813914014114214314414514614714814915015115243 unmodified lines19619719819920020120228 unmodified lines23123223323423523623723823924024124237 unmodified lines280281282283284285286107 unmodified lines39439539639739839940040140240340440569 unmodified lines4754764774784794804815 unmodified lines48748848949049149249318 unmodified lines5125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745756 unmodified lines5825835845855865875881 unmodified line5905915925935945955965975985996006016026036046056066076086096104 unmodified lines6156166176186196206216226236246256266272 unmodified lines6306316326336346356368 unmodified lines6456466476486496506517 unmodified lines65966066166266366466520 unmodified lines68668768868969069169269369449 unmodified lines7447457467477487497507517527537547557567572 unmodified lines76076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479513 unmodified lines809810811812813814815116 unmodified lines93293393493593693793839 unmodified lines97897998098198298398498513 unmodified lines999100010011002100310041005124 unmodified lines1130113111321133113411351136113759 unmodified lines11971198119912001201120212034 unmodified lines120812091210121112121213121410 unmodified linesimport threadingimport globimport tracebackimport copy # 核心新增:用于处理字幕数据from datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher22 unmodified lines# ================= 配置区域 (V24 暴力直链抓取版) =================# FFmpeg 路径配置(解决 PATH 问题)import shutilFFMPEG_PATH = shutil.which("ffmpeg") or "/usr/bin/ffmpeg" # 自动查找或使用默认路径# 1. 🟢 LLM 配置 (用于写提示词 - Yunwu)LLM_API_KEY = "sk-nkNoclHt8HeZ0FFe7SeCDmIhf9XF0PGrHeCeHyLv6UT5LK5R"LLM_BASE_URL = "https://yunwu.ai/v1/chat/completions"TEXT_MODEL = "gemini-3-pro-preview-thinking"# 2. 🔴 视频配置 (用于生成视频 - Flow2API)VIDEO_API_KEY = "zz2026021"VIDEO_BASE_URL = "http://154.40.59.124:8000/flow/v1/videos"# veo_3_1 + fast (快速模式) + landscape (横屏)SORA_MODEL = "veo_3_1-fast-landscape"# 3. 语音配置WHISPER_API_KEY = "sk-swiXot5QTrrJQ5zu8oBiIpPAQLfB9SLM6te6LH4rLP9l771m"# 任务参数 (8段式逻辑)SEGMENTS_PER_VIDEO = 8 # 8个短句 -> 8个1.0秒镜头 (总计8秒)VIDEOS_PER_BATCH = 5 # LLM 并发批次大小VIDEO_DURATION = 8.0 # 目标时长# 任务存储路径TASKS_ROOT_DIR = "tasks_data_thangka_v24"# 🔥🔥 极限并发设置 (分离逻辑) 🔥🔥# 【修改点 1】生成请求并发拉高到 200VIDEO_WORKERS = 200LLM_WORKERS = 100RENDER_PARALLELISM = 4# 【修改点 2】下载并发限制信号量 (直链模式下解锁到100)DOWNLOAD_SEMAPHORE = threading.Semaphore(100)# 全局渲染锁GLOBAL_RENDER_LOCK = threading.Lock()# ================= 提示词工程 (8段式逻辑保持不变) =================# 风格简化 + 强制高速运动注入FORCE_STYLE_PREFIX = ("Thangka style. ")# 强制每一秒都是高速运动,倍率不夸张但必须动FORCE_MOTION_BOOSTER = (" , (FAST MOTION: camera moving forward rapidly, elements transforming, ""dynamic composition, wind blowing, flying objects, energy flowing, no static scenes), ")FORCE_STYLE_SUFFIX = (" , traditional cloth texture, masterpiece.")FORCE_NEGATIVE_PROMPT = (" --no static, still image, frozen, slow motion, standing still, paused, ""photorealistic, realistic, 3d render, cgi, blurry, deformed, watermark.")# 🔥 System Prompt:8段式 + 1.0s时间段映射DEFAULT_GEN_SYSTEM = """你是一位精通“唐卡艺术”与“高速动态视觉”的视频导演。你的任务是将输入的 **8个文案片段**,严格转化为 **8个对应的时间戳画面描述**。27 unmodified lines...]"""# ================= 核心工具函数 =================def extract_url_robust(content):src_match = re.search(r"src=['\"](https?://[^'\"]+)['\"]", content)if src_match:return src_match.group(1)url_match = re.search(r'(https?://[^\s)"]+)', content)if url_match:url = url_match.group(1)if "googleapis" in url or ".mp4" in url:return urlreturn Nonedef parse_time_str(time_str):try:43 unmodified linescurrent_chunk += charif char not in punctuations: valid_count += 1should_cut = False# 15-25字切割if 15 <= valid_count <= 25:if char in punctuations: should_cut = Trueif valid_count > 25: should_cut = True28 unmodified linesf.write(f"{i+1}\n{start_str} --> {end_str}\n{text}\n\n")return output_path# 【新增功能】视频完整性校验def verify_video_integrity(file_path):if not os.path.exists(file_path): return False# 1. 检查文件大小 (小于 1KB 肯定不对)if os.path.getsize(file_path) < 1024: return False# 2. 尝试用 MoviePy 打开try:clip = VideoFileClip(file_path)duration = clip.duration37 unmodified linesdef calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, logger_func):logger_func("⚓ 正在执行锚点纠偏对齐 (V8.9 Anti-Drift)...")if not whisper_segments:lengths = [len("".join(seg)) for seg in text_segments]total_len = sum(lengths)107 unmodified linesreturn "Sacred Thangka patterns floating in the sky, peace and holy."def generate_batch_prompts(self, batch_data, system_prompt):# 1.0s 间隔逻辑user_msg = f"Please generate prompts for the following {len(batch_data)} videos:\n\n"for i, group in enumerate(batch_data):segment_text = ""for seg_idx, txt in enumerate(group):time_point = seg_idx * 1.0 # 1.0秒间隔segment_text += f"({time_point:.1f}s) {txt} | "user_msg += f"Video {i+1} Segments (Strict 1.0s Mapping): {segment_text}\n"69 unmodified lineslogger_func("❌ Whisper 最终失败,将使用纯字数比例分配。")return None# ================= 视频生成 Agent (核心修改:1:1复刻程序B逻辑) =================class VideoAgent:def __init__(self, director_instance=None):5 unmodified linesfinal_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("..", ".")# POST /videospayload = {"prompt": final_prompt,"model": SORA_MODEL,18 unmodified lineslog_queue.put(f"🔹 ID: {task_id},轮询中...")status_url = f"{VIDEO_BASE_URL}/{task_id}"max_retries = 120 # 10分钟超时 (程序B是10分钟)for _ in range(max_retries):time.sleep(5) # 程序B 间隔3秒,这里保持5秒稳一点try:# ==========================================# 🔥 [核心修改点 1] 1:1 复刻:带 params={"detail": "true"}# ==========================================s_resp = requests.get(status_url, headers=self.headers, params={"detail": "true"}, timeout=60)if s_resp.status_code == 200:s_data = s_resp.json()status = str(s_data.get("status") or s_data.get("state") or "").upper()if status in ["SUCCEEDED", "SUCCESS", "COMPLETED"]:# ==========================================# 🔥 [核心修改点 2] 1:1 复刻:解析逻辑# ==========================================download_link = None# 1. 尝试从 detail 字段获取detail_info = s_data.get("detail", {})download_link = detail_info.get("download_url") if isinstance(detail_info, dict) else None# 2. 如果 detail 是字符串,尝试 JSON 反序列化if not download_link and isinstance(detail_info, str):try:detail_json = json.loads(detail_info)download_link = detail_json.get("download_url")except: pass# 3. 如果还是没有,尝试从 /content 接口获取 (Redirect 模式)if not download_link:try:content_url = f"{VIDEO_BASE_URL}/{task_id}/content"# allow_redirects=False 以便捕获 302 跳转链接,而不是下载文件res_content = requests.get(content_url, headers=self.headers, allow_redirects=False, stream=True, timeout=30)if res_content.status_code in [301, 302, 303, 307, 308]:download_link = res_content.headers.get('Location')elif res_content.status_code == 200:# 如果是 200,可能是直接的文件流download_link = content_urlexcept: passif download_link:log_queue.put(f"⚡️ [视频{global_video_idx+1}] 捕获直链: ...{download_link[-30:]}")return download_linkelse:log_queue.put(f"⚠️ [视频{global_video_idx+1}] 任务成功但未找到链接,API响应: {str(s_data)[:100]}...")return Noneelif status in ["FAILED", "ERROR", "FAILURE"]:error_msg = s_data.get("detail", "未知错误")log_queue.put(f"❌ 失败: {error_msg}")return Noneexcept Exception as e:# log_queue.put(f"轮询异常: {e}")passlog_queue.put(f"❌ 生成超时")6 unmodified linesdef 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:# 检查现有文件完整性if verify_video_integrity(save_path):log_queue.put(f"⏭️ [跳过] 视频{global_video_idx+1} 已存在且有效。")return save_path1 unmodified linelog_queue.put(f"🗑️ [删除] 视频{global_video_idx+1} 已存在但损坏,重新生成。")os.remove(save_path)# 【核心修改点】带重试机制 + 信号量控制 + 完整性校验 的安全下载函数def safe_download_with_limit(url):# 获取下载信号量(最多100个并发)with DOWNLOAD_SEMAPHORE:download_attempts = 3for d_i in range(download_attempts):try:log_queue.put(f"⬇️ [视频{global_video_idx+1}] 开始下载 (尝试 {d_i+1})...")# 这里的 requests.get(url) 会直接访问 Google 直链with requests.get(url, headers=self.headers, stream=True, timeout=600) as r:if r.status_code == 200:with open(save_path, 'wb') as f:for chunk in r.iter_content(chunk_size=8192): f.write(chunk)# 下载后立即校验if verify_video_integrity(save_path):return Trueelse:4 unmodified lineslog_queue.put(f"⚠️ 下载拒绝 HTTP {r.status_code}")except Exception as e:log_queue.put(f"⚠️ 下载异常: {e}")time.sleep(2) # 失败等待return Falsecurrent_prompt = prompt# ==================== 阶段 1: 原始 Prompt ====================for i in range(3):url = self._call_api(current_prompt, global_video_idx, log_queue, f"Round 1-{i+1}")if url:2 unmodified linesreturn save_pathtime.sleep(2)# ==================== 阶段 2: 第一次改写 ====================log_queue.put(f"🛡️ [视频{global_video_idx+1}] 启动一级改写...")try:current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=1)8 unmodified linesreturn save_pathtime.sleep(2)# ==================== 阶段 3: 第二次改写 ====================log_queue.put(f"🛡️🛡️ [视频{global_video_idx+1}] 启动二级改写...")try:current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=2)7 unmodified linesreturn save_pathtime.sleep(2)# ==================== 阶段 4: 最终兜底 ====================log_queue.put(f"🧘 [视频{global_video_idx+1}] 使用兜底词...")for i in range(2):url = self._call_api(self.FINAL_FALLBACK_PROMPT, global_video_idx, log_queue, f"Fallback-{i+1}")20 unmodified lineslogger_func(f"❌ [Group {group_id}] 渲染失败: {e}")return False# --- 新增功能:去标点函数 ---def remove_punctuation(text):# 去除中英文常见标点和特殊符号,保留文字和数字return re.sub(r"[,。!?;:、,.;:!?\"'«»(){}\[\]\s]", "", text)def align_and_edit_videos_production(video_files, audio_path, text_segments, whisper_result, full_truth_text, logger_func, output_zip_path):49 unmodified linesfor p in valid_chunks: f.write(f"file '{os.path.abspath(p)}'\n")try:# 1. 拼接无声视频 (Concat)subprocess.run([FFMPEG_PATH, "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)# 2. 准备烧录用的字幕 (去标点)burn_srt_path = os.path.join(chunk_dir, "burn_subs.srt")burn_subs_data = []if final_subtitle_data:# 深拷贝一份,以免影响原始SRTburn_subs_data = copy.deepcopy(final_subtitle_data)for item in burn_subs_data:item['text'] = remove_punctuation(item['text'])2 unmodified lineselse:with open(burn_srt_path, 'w') as f: f.write("")# 3. 最终渲染:合并音频 + 烧录字幕 (使用 libx264 重编码)logger_func("🎵 注入音频并烧录硬字幕 (Rendering)...")ffmpeg_cmd = [FFMPEG_PATH, "-y","-i", temp_silent_full,"-i", audio_path]# 如果有字幕文件,添加 subtitles 滤镜# Fontsize=18, MarginV=25 可根据需要微调if os.path.exists(burn_srt_path) and os.path.getsize(burn_srt_path) > 0:style = "Fontsize=18,PrimaryColour=&HFFFFFF&,Outline=1,Shadow=0,MarginV=25"burn_path_esc = os.path.abspath(burn_srt_path).replace("\\", "/") # 路径处理ffmpeg_cmd.extend(["-vf", f"subtitles='{burn_path_esc}':force_style='{style}'"])ffmpeg_cmd.extend(["-c:v", "libx264", # 必须重编码才能烧录"-preset", "fast", # 编码速度 (veryfast/fast/medium)"-crf", "23", # 画质控制 (18-28, 越小越好)"-c:a", "aac","-map", "0:v:0","-map", "1:a:0","-shortest",final_mp4_path])subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)# 清理临时文件shutil.rmtree(chunk_dir, ignore_errors=True)logger_func("📦 打包 ZIP...")13 unmodified linesif file and os.path.exists(file): zf.write(file, os.path.basename(file))return zip_path# ================= Task Manager & Data Persistence =================class TaskManager:def __init__(self, root_dir=TASKS_ROOT_DIR):116 unmodified linesdef log_wrapper(msg): task_manager.log(task_id, msg)try:log_wrapper("🚀 任务启动/恢复中 (V24 - 暴力直链版)...")local_audio_path = os.path.join(task_dir, "original_audio.mp3")if not is_resume:39 unmodified linesdirector = DirectorAgent(); cameraman = VideoAgent(director_instance=director)llm_batches = []; video_futures = []# 【修改点】使用 VIDEO_WORKERS = 200 的线程池处理“生成请求”video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)for i in range(0, total_videos, VIDEOS_PER_BATCH): llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH])13 unmodified linesgid = start_id + iif gid < total_videos:all_collected_prompts[gid] = p_text# 提交所有任务到大线程池future_task = video_executor.submit(cameraman.worker_task, p_text, gid, logger, task_dir)video_futures.append((gid, future_task))124 unmodified lineswith gr.Blocks(title="Veo V24 Thangka Direct") as demo:gr.Markdown("## 🎬 Veo V24 Force-Direct Link (8x1.0s Thangka Mode)")gr.Markdown("🌟 **特性**:暴力搜索Google直链(download_url) + 8镜头/1.0秒流畅模式 + 并发请求(200) + 硬字幕烧录(No Punc)")with gr.Tabs():with gr.Tab("🚀 批量提交任务"):gr.Markdown("### 批量上传区域 (每格需包含: txt + mp3 + srt)")59 unmodified linesffmpeg_test = shutil.which("ffmpeg")if ffmpeg_test:print(f" FFmpeg 找到: {ffmpeg_test}")globals()['FFMPEG_PATH'] = ffmpeg_testelse:print("错误: 找不到 FFmpeg")4 unmodified linesfor temp_dir in temp_dirs:try:os.makedirs(temp_dir, exist_ok=True)os.chmod(temp_dir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)print(f"已设置 {temp_dir} 权限")except Exception as e:10 unmodified lines1112131415161722 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838427 unmodified lines11211311411511611711811943 unmodified lines16316416516616716828 unmodified lines19719819920020120220320420537 unmodified lines243244245246247248107 unmodified lines35635735835936036136236336436536669 unmodified lines4364374384394404414425 unmodified lines44844945045145245345418 unmodified lines4734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425436 unmodified lines5505515525535545551 unmodified line5575585595605615625635645655665675685695705715725734 unmodified lines5785795805815825835845855865875885892 unmodified lines5925935945955965975988 unmodified lines6076086096106116126137 unmodified lines62162262362462562662720 unmodified lines64864965065165265365449 unmodified lines7047057067077087097107117127137142 unmodified lines71771871972072172272372472572672772872973073173273373473573673773873974013 unmodified lines754755756757758759760116 unmodified lines87787887988088188288339 unmodified lines92392492592692792813 unmodified lines942943944945946947124 unmodified lines107210731074107510761077107859 unmodified lines1138113911401141114211434 unmodified lines11481149115011511152115310 unmodified linesimport threadingimport globimport tracebackimport copyfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher22 unmodified lines# ================= 配置区域 (V24 暴力直链抓取版) =================# FFmpeg 路径配置import shutilFFMPEG_PATH = shutil.which("ffmpeg") or "/usr/bin/ffmpeg"# 1. LLM 配置LLM_API_KEY = "sk-nkNoclHt8HeZ0FFe7SeCDmIhf9XF0PGrHeCeHyLv6UT5LK5R"LLM_BASE_URL = "https://yunwu.ai/v1/chat/completions"TEXT_MODEL = "gemini-3-pro-preview-thinking"# 2. 视频配置VIDEO_API_KEY = "zz2026021"VIDEO_BASE_URL = "http://154.40.59.124:8000/flow/v1/videos"SORA_MODEL = "veo_3_1-fast-landscape"# 3. 语音配置WHISPER_API_KEY = "sk-swiXot5QTrrJQ5zu8oBiIpPAQLfB9SLM6te6LH4rLP9l771m"# 任务参数SEGMENTS_PER_VIDEO = 8VIDEOS_PER_BATCH = 5VIDEO_DURATION = 8.0# 任务存储路径TASKS_ROOT_DIR = "tasks_data_thangka_v24"# 并发设置VIDEO_WORKERS = 200LLM_WORKERS = 100RENDER_PARALLELISM = 4DOWNLOAD_SEMAPHORE = threading.Semaphore(100)GLOBAL_RENDER_LOCK = threading.Lock()# ================= 提示词工程 =================FORCE_STYLE_PREFIX = "Thangka style. "FORCE_MOTION_BOOSTER = " , (FAST MOTION: camera moving forward rapidly, elements transforming, dynamic composition, wind blowing, flying objects, energy flowing, no static scenes), "FORCE_STYLE_SUFFIX = " , traditional cloth texture, masterpiece."FORCE_NEGATIVE_PROMPT = " --no static, still image, frozen, slow motion, standing still, paused, photorealistic, realistic, 3d render, cgi, blurry, deformed, watermark."DEFAULT_GEN_SYSTEM = """你是一位精通“唐卡艺术”与“高速动态视觉”的视频导演。你的任务是将输入的 **8个文案片段**,严格转化为 **8个对应的时间戳画面描述**。27 unmodified lines...]"""# ================= 核心工具函数 =================def parse_time_str(time_str):try:43 unmodified linescurrent_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 = True28 unmodified linesf.write(f"{i+1}\n{start_str} --> {end_str}\n{text}\n\n")return output_pathdef verify_video_integrity(file_path):if not os.path.exists(file_path): return Falseif os.path.getsize(file_path) < 1024: return Falsetry:clip = VideoFileClip(file_path)duration = clip.duration37 unmodified linesdef calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, logger_func):logger_func("⚓ 正在执行锚点纠偏对齐 (V8.9 Anti-Drift)...")if not whisper_segments:lengths = [len("".join(seg)) for seg in text_segments]total_len = sum(lengths)107 unmodified linesreturn "Sacred Thangka patterns floating in the sky, peace and holy."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):segment_text = ""for seg_idx, txt in enumerate(group):time_point = seg_idx * 1.0segment_text += f"({time_point:.1f}s) {txt} | "user_msg += f"Video {i+1} Segments (Strict 1.0s Mapping): {segment_text}\n"69 unmodified lineslogger_func("❌ Whisper 最终失败,将使用纯字数比例分配。")return None# ================= 视频生成 Agent (核心修改:1:1复刻程序B) =================class VideoAgent:def __init__(self, director_instance=None):5 unmodified linesfinal_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("..", ".")# 1. POST 创建任务payload = {"prompt": final_prompt,"model": SORA_MODEL,18 unmodified lineslog_queue.put(f"🔹 ID: {task_id},轮询中...")# 2. GET 查询状态check_url = f"{VIDEO_BASE_URL}/{task_id}"max_retries = 120 # 10分钟超时start_time = time.time()for _ in range(max_retries):# Program B uses explicit sleep 3stime.sleep(3)elapsed = int(time.time() - start_time)if elapsed > 600:log_queue.put(f"⚠️ 任务超时,ID: {task_id}")breaktry:# [核心] 严格按照程序B:添加 detail=true 参数res_status = requests.get(check_url, headers=self.headers, params={"detail": "true"}, timeout=60)if res_status.status_code != 200:continue # 失败则继续轮询status_data = res_status.json()status = str(status_data.get("status") or status_data.get("state") or "").upper()if status in ["SUCCEEDED", "SUCCESS", "COMPLETED"]:# 3. 从 detail 字段直接解析 download_url (参考程序B)detail_info = status_data.get("detail", {})download_link = None# 尝试从字典直接获取if isinstance(detail_info, dict):download_link = detail_info.get("download_url")# 如果是字符串,尝试解析JSONif not download_link and isinstance(detail_info, str):try:detail_json = json.loads(detail_info)download_link = detail_json.get("download_url")except: pass# 兜底:尝试 /content 重定向 (allow_redirects=False)if not download_link:log_queue.put(f"⚠️ detail 中未找到链接,尝试探测 /content...")try:content_url = f"{VIDEO_BASE_URL}/{task_id}/content"# allow_redirects=False 以便捕获 302 跳转链接,而不是下载文件res_content = requests.get(content_url, headers=self.headers, allow_redirects=False, stream=True, timeout=30)if res_content.status_code in [301, 302, 303, 307, 308]:download_link = res_content.headers.get('Location')elif res_content.status_code == 200:download_link = content_urlexcept: passif download_link:log_queue.put(f"⚡️ [视频{global_video_idx+1}] 捕获直链: ...{download_link[-30:]}")return download_linkelse:log_queue.put(f"❌ 任务成功但未找到下载链接: {json.dumps(status_data, ensure_ascii=False)[:100]}")return Noneelif status in ["FAILED", "FAILURE"]:error_msg = status_data.get("detail", "未知错误")log_queue.put(f"❌ 生成失败: {error_msg}")return Noneexcept Exception as e:passlog_queue.put(f"❌ 生成超时")6 unmodified linesdef 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:if verify_video_integrity(save_path):log_queue.put(f"⏭️ [跳过] 视频{global_video_idx+1} 已存在且有效。")return save_path1 unmodified linelog_queue.put(f"🗑️ [删除] 视频{global_video_idx+1} 已存在但损坏,重新生成。")os.remove(save_path)def safe_download_with_limit(url):with DOWNLOAD_SEMAPHORE:download_attempts = 3for d_i in range(download_attempts):try:log_queue.put(f"⬇️ [视频{global_video_idx+1}] 开始下载 (尝试 {d_i+1})...")# 核心:使用程序B获取到的直链进行下载with requests.get(url, headers=self.headers, stream=True, timeout=600) as r:if r.status_code == 200:with open(save_path, 'wb') as f:for chunk in r.iter_content(chunk_size=8192): f.write(chunk)if verify_video_integrity(save_path):return Trueelse:4 unmodified lineslog_queue.put(f"⚠️ 下载拒绝 HTTP {r.status_code}")except Exception as e:log_queue.put(f"⚠️ 下载异常: {e}")time.sleep(2)return Falsecurrent_prompt = prompt# 阶段 1: 原始 Promptfor i in range(3):url = self._call_api(current_prompt, global_video_idx, log_queue, f"Round 1-{i+1}")if url:2 unmodified linesreturn save_pathtime.sleep(2)# 阶段 2: 第一次改写log_queue.put(f"🛡️ [视频{global_video_idx+1}] 启动一级改写...")try:current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=1)8 unmodified linesreturn save_pathtime.sleep(2)# 阶段 3: 第二次改写log_queue.put(f"🛡️🛡️ [视频{global_video_idx+1}] 启动二级改写...")try:current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=2)7 unmodified linesreturn save_pathtime.sleep(2)# 阶段 4: 最终兜底log_queue.put(f"🧘 [视频{global_video_idx+1}] 使用兜底词...")for i in range(2):url = self._call_api(self.FINAL_FALLBACK_PROMPT, global_video_idx, log_queue, f"Fallback-{i+1}")20 unmodified lineslogger_func(f"❌ [Group {group_id}] 渲染失败: {e}")return Falsedef remove_punctuation(text):return re.sub(r"[,。!?;:、,.;:!?\"'«»(){}\[\]\s]", "", text)def align_and_edit_videos_production(video_files, audio_path, text_segments, whisper_result, full_truth_text, logger_func, output_zip_path):49 unmodified linesfor p in valid_chunks: f.write(f"file '{os.path.abspath(p)}'\n")try:subprocess.run([FFMPEG_PATH, "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)burn_srt_path = os.path.join(chunk_dir, "burn_subs.srt")burn_subs_data = []if final_subtitle_data:burn_subs_data = copy.deepcopy(final_subtitle_data)for item in burn_subs_data:item['text'] = remove_punctuation(item['text'])2 unmodified lineselse:with open(burn_srt_path, 'w') as f: f.write("")logger_func("🎵 注入音频并烧录硬字幕 (Rendering)...")ffmpeg_cmd = [FFMPEG_PATH, "-y","-i", temp_silent_full,"-i", audio_path]if os.path.exists(burn_srt_path) and os.path.getsize(burn_srt_path) > 0:style = "Fontsize=18,PrimaryColour=&HFFFFFF&,Outline=1,Shadow=0,MarginV=25"burn_path_esc = os.path.abspath(burn_srt_path).replace("\\", "/")ffmpeg_cmd.extend(["-vf", f"subtitles='{burn_path_esc}':force_style='{style}'"])ffmpeg_cmd.extend(["-c:v", "libx264", "-preset", "fast", "-crf", "23", "-c:a", "aac","-map", "0:v:0", "-map", "1:a:0", "-shortest", final_mp4_path])subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)shutil.rmtree(chunk_dir, ignore_errors=True)logger_func("📦 打包 ZIP...")13 unmodified linesif file and os.path.exists(file): zf.write(file, os.path.basename(file))return zip_path# ================= Task Manager =================class TaskManager:def __init__(self, root_dir=TASKS_ROOT_DIR):116 unmodified linesdef log_wrapper(msg): task_manager.log(task_id, msg)try:log_wrapper("🚀 任务启动/恢复中 (V24 - 1:1复刻版)...")local_audio_path = os.path.join(task_dir, "original_audio.mp3")if not is_resume:39 unmodified linesdirector = DirectorAgent(); cameraman = VideoAgent(director_instance=director)llm_batches = []; video_futures = []video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)for i in range(0, total_videos, VIDEOS_PER_BATCH): llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH])13 unmodified linesgid = start_id + iif gid < total_videos:all_collected_prompts[gid] = p_textfuture_task = video_executor.submit(cameraman.worker_task, p_text, gid, logger, task_dir)video_futures.append((gid, future_task))124 unmodified lineswith gr.Blocks(title="Veo V24 Thangka Direct") as demo:gr.Markdown("## 🎬 Veo V24 Force-Direct Link (8x1.0s Thangka Mode)")with gr.Tabs():with gr.Tab("🚀 批量提交任务"):gr.Markdown("### 批量上传区域 (每格需包含: txt + mp3 + srt)")59 unmodified linesffmpeg_test = shutil.which("ffmpeg")if ffmpeg_test:print(f" FFmpeg 找到: {ffmpeg_test}")globals()['FFMPEG_PATH'] = ffmpeg_testelse:print("错误: 找不到 FFmpeg")4 unmodified linesfor temp_dir in temp_dirs:try:os.makedirs(temp_dir, exist_ok=True)os.chmod(temp_dir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)print(f"已设置 {temp_dir} 权限")except Exception as e:
app.py+89-150