Update app.py
Browse files1234567891011121314151616 unmodified lines3334353637383940414243444546474849505152535455565786 unmodified lines14414514614714814915015122 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961972 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362374 unmodified lines2422432442452462472482492502512522532542552562572582 unmodified lines26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630728 unmodified lines3363373383393403413423433443453463473483493503513523533543553567 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538638738815 unmodified lines4044054064074084094104113 unmodified lines41541641741841942042142242342442542642742842943043143243343443543643743843944011 unmodified lines4524534544554564574584594604614621 unmodified line464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610import 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 SequenceMatcher16 unmodified linesimport 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. "86 unmodified linesf.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)22 unmodified linesif 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))2 unmodified linessource_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):4 unmodified linesfor 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 + offset2 unmodified linesif 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."28 unmodified linesclass 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"}7 unmodified linesclass 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:15 unmodified lines# ================= 渲染核心 =================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.53 unmodified linesvideo_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]11 unmodified linescompleted_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:1 unmodified linetry: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)1234567891011121314151616 unmodified lines33343536373839404142434445464748495051525354555657585960616263646586 unmodified lines15215315415515615715815922 unmodified lines1821831841851861871881891901911921931941951962 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222234 unmodified lines2282292302312322332342352362372 unmodified lines24024124224324424524624724824925025125225325425525625725825926026126226326426526626726828 unmodified lines2972982993003013023033043053063073083093103113123133143153163173187 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735815 unmodified lines3743753763773783793803813 unmodified lines38538638738838939039139239339439539639739839940040140240340440540640740840911 unmodified lines4214224234244254264274284294304311 unmodified line433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747import sysimport subprocessimport osimport shutilimport timeimport jsonimport requestsimport zipfileimport queueimport reimport threadingimport globimport tracebackfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher16 unmodified linesimport gradio as grimport openccfrom moviepy.editor import VideoFileClip, AudioFileClip, vfx# ================= 配置区域 =================# 原有通用 Key (用于视频生成和 LLM)YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"# 新增 Whisper 专用 KeyWHISPER_API_KEY = "sk-DHQ9p46YjdM86SxSGJCL6MmRpVLRYBnPBRH7dNTtYpmyuW47"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 = 10# 建议在 HF Settings 挂载 Persistent Storage 到此目录 (如 /data/tasks_data)TASKS_ROOT_DIR = "tasks_data"VIDEO_WORKERS = 150LLM_WORKERS = 5RENDER_PARALLELISM = 4# 🔥 全局渲染锁:确保同一时间只有一个任务在进行高负载的 ffmpeg 拼接GLOBAL_RENDER_LOCK = threading.Lock()FORCE_STYLE_PREFIX = ("A sacred Tibetan Thangka painting style on aged cotton canvas. "86 unmodified linesf.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, logger_func):logger_func("🔄 正在执行【字幕真理修正】...")try:cc = opencc.OpenCC('s2t')truth_text_trad = cc.convert(truth_text_raw)22 unmodified linesif truth_cursor >= len(truth_clean): breakreturn corrected_segmentsdef 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)return [max(5.0, (l/total_len)*total_audio_duration) for l in lengths]source_full_text = ""group_char_ranges = []current_char_idx = 0for seg_list in text_segments:group_text = normalize_text("".join(seg_list))2 unmodified linessource_full_text += group_textcurrent_char_idx += lengthchar_time_map = {}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)seg_start_idx = w_cursorfor 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_lenmatcher = 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):4 unmodified linesfor 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)cut_points = []last_valid_time = 0.0for i, (start_char, end_char) in enumerate(group_char_ranges):found_time = Nonefor offset in range(min(5, end_char - start_char)):target = start_char + offset2 unmodified linesif 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)video_durations = []for i in range(len(text_segments)):t_start = cut_points[i]t_end = cut_points[i+1]dur = t_end - t_startfinal_dur = max(2.0, dur)video_durations.append(final_dur)logger_func(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):# 保持原 Keyself.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."28 unmodified linesclass AudioAgent:def __init__(self):# 🔥 修改:使用专用的 Whisper Keyself.headers = {"Authorization": f"Bearer {WHISPER_API_KEY}"}def compress_audio(self, input_path, logger_func):if os.path.getsize(input_path) < 24 * 1024 * 1024: return input_pathlogger_func(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, logger_func):upload_path = self.compress_audio(audio_path, logger_func)url = f"{MERCHANT_BASE_URL}/v1/audio/transcriptions"for attempt in range(3):try:logger_func(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"}7 unmodified linesclass VideoAgent:def __init__(self, director_instance=None):# 保持原 Keyself.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}self.director = director_instance# 这里的 log_queue 可以是 Queue,也可以是 LogQueueAdapterdef 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:15 unmodified lines# ================= 渲染核心 =================def render_atomic_group_final(group_id, vid_path, target_duration, global_start, logger_func, output_filename):logger_func(f"🟫 [Group {group_id}] 渲染中 (时长:{target_duration:.1f}s)...")try:raw_clip = VideoFileClip(vid_path)if target_duration < 0.5: target_duration = 0.53 unmodified linesvideo_clip.close(); raw_clip.close()return Trueexcept Exception as e:logger_func(f"❌ [Group {group_id}] 渲染失败: {e}")return Falsedef align_and_edit_videos_production(video_files, audio_path, text_segments, whisper_result, full_truth_text, logger_func, output_zip_path):logger_func(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'], logger_func)logger_func(f"📝 生成SRT: {os.path.basename(srt_path)}")generate_srt_file(final_subtitle_data, srt_path)if whisper_result and 'segments' in whisper_result:segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio, logger_func)else:logger_func("⚠️ 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]11 unmodified linescompleted_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'], logger_func, cfg['out']): cfg['id'] for cfg in group_configs}for f in as_completed(future_map):if f.result(): completed_count += 1logger_func("🔗 最终拼接...")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:1 unmodified linetry: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)logger_func("🎵 注入音频...")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)logger_func("📦 打包 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:logger_func(f"❌ 拼接/打包失败: {e}")return Falsedef create_zip_package(file_paths, output_dir):timestamp = int(time.time()); zip_path = os.path.join(output_dir, f"Backup_Raw_{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# ================= V9.1 异步架构 =================class TaskManager:def __init__(self, root_dir=TASKS_ROOT_DIR):self.root_dir = root_diros.makedirs(self.root_dir, exist_ok=True)def create_task(self, original_filename="project"):timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')clean_name = os.path.splitext(original_filename)[0]clean_name = re.sub(r'[\\/*?:"<>|]', "", clean_name)task_id = f"{clean_name}_{timestamp}"task_dir = os.path.join(self.root_dir, task_id)os.makedirs(task_dir, exist_ok=True)with open(os.path.join(task_dir, "log.txt"), "w", encoding="utf-8") as f:f.write(f"[{datetime.now().strftime('%H:%M:%S')}] 任务创建成功: {task_id}\n")self.update_status(task_id, "running", progress=0)return task_id, task_dirdef log(self, task_id, message):timestamp = datetime.now().strftime('%H:%M:%S')log_line = f"[{timestamp}] {message}\n"log_path = os.path.join(self.root_dir, task_id, "log.txt")try:with open(log_path, "a", encoding="utf-8") as f:f.write(log_line)except: passprint(f"[{task_id}] {message}")def update_status(self, task_id, status, result_path=None, progress=0):status_path = os.path.join(self.root_dir, task_id, "status.json")data = {"status": status,"last_update": time.time(),"progress": progress,"result": result_path}with open(status_path, "w", encoding="utf-8") as f:json.dump(data, f)def get_task_info(self, task_id):task_dir = os.path.join(self.root_dir, task_id)if not os.path.exists(task_dir): return Nonelog_content = ""try:with open(os.path.join(task_dir, "log.txt"), "r", encoding="utf-8") as f:log_content = f.read()except: log_content = "日志读取中..."status_data = {}try:with open(os.path.join(task_dir, "status.json"), "r", encoding="utf-8") as f:status_data = json.load(f)except: status_data = {"status": "unknown"}return {"id": task_id,"log": log_content,"status": status_data.get("status"),"result": status_data.get("result")}def list_tasks(self):tasks = []if not os.path.exists(self.root_dir): return []for d in os.listdir(self.root_dir):full_path = os.path.join(self.root_dir, d)if os.path.isdir(full_path):tasks.append(d)tasks.sort(key=lambda x: os.path.getmtime(os.path.join(self.root_dir, x)), reverse=True)return tasksdef clear_all_tasks(self):try:shutil.rmtree(self.root_dir)os.makedirs(self.root_dir, exist_ok=True)return True, "✅ 存储已清空,所有历史任务已删除。"except Exception as e:return False, f"❌ 清空失败: {e}"task_manager = TaskManager()# --- 日志适配器 ---class LogQueueAdapter:def __init__(self, task_manager, task_id):self.tm = task_managerself.tid = task_iddef put(self, message):self.tm.log(self.tid, message)def get(self): return Nonedef empty(self): return True# ----------------- 后台工作线程 -----------------def background_worker(task_id, full_text, audio_path, system_prompt, original_filename):task_dir = os.path.join(task_manager.root_dir, task_id)logger = LogQueueAdapter(task_manager, task_id)def log_wrapper(msg):task_manager.log(task_id, msg)try:log_wrapper("🚀 后台进程启动,请放心刷新页面。")local_audio_path = os.path.join(task_dir, "original_audio.mp3")shutil.copy(audio_path, local_audio_path)zip_basename = task_idif original_filename:zip_basename = os.path.splitext(original_filename)[0]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)log_wrapper(f"📄 共 {len(raw_segments)} 小节,{total_videos} 个视频任务。")log_wrapper("🎙️ Whisper 任务提交...")audio_agent = AudioAgent()whisper_result = audio_agent.transcribe_audio_with_retry(local_audio_path, log_wrapper)director = 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])log_wrapper(f"🧠 Prompt 生成与视频渲染并发中...")with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor:llm_future_map = {llm_executor.submit(director.generate_batch_prompts, batch, 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:# 传入 logger (LogQueueAdapter) 以捕获详细日志future_task = video_executor.submit(cameraman.worker_task, p_text, gid, logger, task_dir)video_futures.append((gid, future_task))log_wrapper(f"⚡ Batch {b_idx+1} Prompt OK")except Exception as e:log_wrapper(f"⚠️ Batch Error: {e}")log_wrapper("⏳ 等待所有视频素材就绪...")while True:done_count = sum(1 for _, f in video_futures if f.done())if done_count >= len(video_futures): breaktime.sleep(2)video_paths = [None] * total_videosfor idx, f in video_futures:try: video_paths[idx] = f.result()except Exception as e: log_wrapper(f"❌ 视频 {idx+1} 线程崩溃: {str(e)}")valid_videos = [v for v in video_paths if v]log_wrapper(f"🎬 素材下载完毕 ({len(valid_videos)}/{total_videos})")if len(valid_videos) > 0:output_zip = os.path.join(task_dir, f"{zip_basename}.zip")# 🔥🔥 全局锁:强制串行渲染 🔥🔥log_wrapper("🔒 正在申请全局渲染锁 (防止多任务同时渲染导致内存溢出)...")with GLOBAL_RENDER_LOCK:log_wrapper("🟢 获得渲染锁,开始最终合成...")success = align_and_edit_videos_production(valid_videos, local_audio_path, video_text_groups[:len(valid_videos)], whisper_result, full_text, log_wrapper, output_zip)log_wrapper("⚪ 渲���结束,释放锁。")if success:log_wrapper("🎉🎉🎉 打包成功!")task_manager.update_status(task_id, "completed", result_path=output_zip)else:log_wrapper("⚠️ 拼接失败,打包原始素材")bk_zip = create_zip_package(valid_videos, task_dir)task_manager.update_status(task_id, "failed", result_path=bk_zip)else:log_wrapper("❌ 无视频生成 (请检查上方日志)")task_manager.update_status(task_id, "failed")except Exception as e:log_wrapper(f"💥 致命错误: {traceback.format_exc()}")task_manager.update_status(task_id, "error")# ================= 交互层 =================def submit_new_task(txt_file, audio_file, system_prompt, manual_text):final_text = manual_textoriginal_fname = "project"if txt_file is not None:try:with open(txt_file.name, 'r', encoding='utf-8') as f:content = f.read()if content.strip():final_text = contentoriginal_fname = os.path.basename(txt_file.name)except: passif not final_text.strip(): return "❌ 文案不能为空", Noneif not audio_file: return "❌ 缺音频", Nonetask_id, task_dir = task_manager.create_task(original_fname)t = threading.Thread(target=background_worker, args=(task_id, final_text, audio_file, system_prompt, original_fname))t.start()return f"✅ 任务已后台启动!ID: {task_id}\n请切换到【任务监控】标签页查看进度。", task_iddef refresh_task_list():tasks = task_manager.list_tasks()return gr.Dropdown(choices=tasks, value=tasks[0] if tasks else None)def get_task_details(task_id):if not task_id: return "请选择任务", None, Noneinfo = task_manager.get_task_info(task_id)if not info: return "任务不存在", None, Nonereturn info['log'], info['result'], f"当前状态: {info['status']}"def handle_clear_storage():success, msg = task_manager.clear_all_tasks()# 清空后刷新列表return msg, gr.Dropdown(choices=[], value=None)# ================= UI 构建 =================with gr.Blocks(title="Veo V9.1 Async Pro") as demo:gr.Markdown("## 🎬 Veo V9.1 异步任务系统 (并发安全版)")gr.Markdown("🌟 **特性**:日志修正、全局渲染排队锁(防OOM)、一键清空存储")with gr.Tabs():with gr.Tab("🚀 提交新任务"):with gr.Row():with gr.Column():txt_input = gr.File(label="1. 拖入文案TXT (可选)", file_types=[".txt"])text_box = gr.Textbox(label="文案内容", lines=8)audio_input = gr.Audio(label="2. 上传音频", type="filepath")sys_prompt = gr.Textbox(label="System Prompt", value=DEFAULT_GEN_SYSTEM, lines=3, visible=False)submit_btn = gr.Button("🔥 立即启动后台任务", variant="primary")with gr.Column():submit_result = gr.Textbox(label="提交结果", lines=2)new_task_id_storage = gr.State()with gr.Tab("📺 任务监控"):with gr.Row():with gr.Column(scale=1):refresh_list_btn = gr.Button("🔄 刷新任务列表")task_dropdown = gr.Dropdown(label="选择历史任务", choices=[], interactive=True)status_display = gr.Label("当前状态: 准备就绪")download_file = gr.File(label="下载成品 (ZIP)")# 🔴 新增:红色清空按钮gr.Markdown("---")clear_btn = gr.Button("🗑️ 危险:清空所有任务数据", variant="stop")clear_msg = gr.Label("")with gr.Column(scale=3):log_monitor = gr.Textbox(label="运行日志 (自动刷新)", lines=25, max_lines=25)auto_timer = gr.Timer(2)# --- 事件绑定 ---def on_file_upload(f):if f: return open(f.name, 'r', encoding='utf-8').read()return ""txt_input.change(on_file_upload, txt_input, text_box)submit_btn.click(submit_new_task,[txt_input, audio_input, sys_prompt, text_box],[submit_result, new_task_id_storage])def auto_select_new_task(new_id):all_tasks = task_manager.list_tasks()return gr.Dropdown(choices=all_tasks, value=new_id)submit_btn.click(auto_select_new_task, new_task_id_storage, task_dropdown)refresh_list_btn.click(refresh_task_list, outputs=task_dropdown)auto_timer.tick(get_task_details, inputs=[task_dropdown], outputs=[log_monitor, download_file, status_display])task_dropdown.change(get_task_details, inputs=[task_dropdown], outputs=[log_monitor, download_file, status_display])# 绑定清空按钮事件clear_btn.click(handle_clear_storage, outputs=[clear_msg, task_dropdown])demo.load(refresh_task_list, outputs=task_dropdown)if __name__ == "__main__":demo.queue().launch(server_name="0.0.0.0", inbrowser=True)
app.py+333-196