Update app.py
Browse files1234567891011121314151616 unmodified lines333435363738394041424344454647484950515253545556578 unmodified lines66676869707172737475767778798081828384858687888990912 unmodified lines94959697989910043 unmodified lines14414514614714814915015122 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961972 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362374 unmodified lines2422432442452462472482492502512522532542552562572582 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003011 unmodified line30330430530630730830931031131223 unmodified lines3363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893908 unmodified lines3994004014024034044054064074084094104113 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. "8 unmodified lines)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..."},2 unmodified lines【绝对铁律】1. **必须返回与输入数量一致的 Prompt**。2. 每个 Prompt 内部必须包含 8 个硬切画面。3. 风格必须是高燃、快速、唐卡视觉。4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。"""43 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 类 =================1 unmodified lineclass DirectorAgent:def __init__(self):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"}def rewrite_failed_prompt(self, old_prompt, level):if level == 1: system_instruction = "The previous video prompt failed. REWRITE it to be SAFER. REMOVE ALL references to children."else: system_instruction = "Prompt FAILED. Rewrite EXTREMELY CONCISE (under 10 words)."payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_instruction}, {"role": "user", "content": f"Failed: {old_prompt}"}]}try:resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=60)if resp.status_code == 200: return resp.json()['choices'][0]['message']['content'].strip()23 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"}resp = requests.post(url, headers=self.headers, files=files, data=data, timeout=600)if resp.status_code == 200:res_json = resp.json()if 'words' in res_json or 'segments' in res_json: return res_jsontime.sleep(5)except: time.sleep(5)return Noneclass VideoAgent:def __init__(self, director_instance=None):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}self.director = director_instancedef worker_task(self, prompt, global_video_idx, log_queue, save_dir):save_path = os.path.join(save_dir, f"clip_{global_video_idx+1:04d}.mp4")if os.path.exists(save_path) and os.path.getsize(save_path) > 1000: return save_pathcurrent_prompt_core = promptfor rewrite_cycle in range(3):if rewrite_cycle > 0:try: new_core = self.director.rewrite_failed_prompt(current_prompt_core, rewrite_cycle); current_prompt_core = new_core if new_core else current_prompt_coreexcept: passfinal_prompt = (f"{FORCE_STYLE_PREFIX} {current_prompt_core} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")for attempt in range(5):try:files_payload = {'model': (None, VEO_MODEL), 'prompt': (None, final_prompt), 'seconds': (None, str(VIDEO_DURATION_STR)), 'size': (None, VIDEO_SIZE)}req = requests.post(f"{MERCHANT_BASE_URL}/v1/videos", headers=self.headers, files=files_payload, timeout=60)if req.status_code != 200: time.sleep(2); continuetask_id = req.json().get("id")if not task_id: continuelog_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中...")start_time = time.time()while True:if time.time() - start_time > 600: breakstatus_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30)8 unmodified lineselif status == "failed": breaktime.sleep(3)else: time.sleep(3)except: time.sleep(3)return None# ================= 渲染核心 =================def render_atomic_group_final(group_id, vid_path, target_duration, global_start, log_queue, output_filename):log_queue.put(f"🟫 [Group {group_id}] 渲染中 (时长:{target_duration:.1f}s)...")try:raw_clip = VideoFileClip(vid_path)if target_duration < 0.5: target_duration = 0.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 lines33343536373839404142434445464748495051525354555657585960616263646566676869708 unmodified lines7980818283848586878889909192939495969798991001011021031041052 unmodified lines10810911011111211311443 unmodified lines15815916016116216316416522 unmodified lines1881891901911921931941951961971981992002012022 unmodified lines2052062072082092102112122132142152162172182192202212222232242252262272282294 unmodified lines2342352362372382392402412422432 unmodified lines2462472482492502512522532542552562572582592602612622632642652662671 unmodified line26927027127227327427527627727827928028128228328428528628728828929029129223 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144158 unmodified lines4244254264274284294304314324334344354364374384394403 unmodified lines44444544644744844945045145245345445545645745845946046146246346446546646746811 unmodified lines4804814824834844854864874884894901 unmodified line492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842import 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# ================= 配置区域 =================# 视频生成的 API Key (Sora, LLM 等)YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"# Whisper Key (仅当不使用本地JSON时才需要)WHISPER_API_KEY = "sk-swiXot5QTrrJQ5zu8oBiIpPAQLfB9SLM6te6LH4rLP9l771m"MERCHANT_BASE_URL = "https://yunwu.ai"# 核心模型配置SORA_MODEL = "sora-2-all" # 模型名称VIDEO_SIZE = "720p" # 分辨率VIDEO_DURATION = 15 # 时长ORIENTATION = "landscape" # 横屏TEXT_MODEL = "gemini-3-pro-preview-thinking"WHISPER_MODEL = "whisper-1"SEGMENTS_PER_VIDEO = 15 # 15个短句对应15秒视频VIDEOS_PER_BATCH = 10TASKS_ROOT_DIR = "tasks_data"# 🔥🔥 极限并发保持 🔥🔥VIDEO_WORKERS = 5000LLM_WORKERS = 5000RENDER_PARALLELISM = 4 # 渲染线程改回 4 以防爆内存# 全局渲染锁GLOBAL_RENDER_LOCK = threading.Lock()FORCE_STYLE_PREFIX = ("A sacred Tibetan Thangka painting style on aged cotton canvas. "8 unmodified lines)FORCE_STYLE_SUFFIX = (" , highly detailed Thangka line work (Goujin), traditional cloth texture, masterpiece, ""bright lighting, bright scene, well-lit.")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, dark, dim, shadows, night.")DEFAULT_GEN_SYSTEM = """你是一位专门制作【极速快闪蒙太奇】视频的唐卡艺术导演。你的任务是将输入的 **文案段落**(每段包含15个短句),批量转化为 **对应数量的独立视频** 的提示词。【输入格式】你将收到类似这样的输入:Video 1 Segments: [0-1s]... [1-2s]... [14-15s]...Video 2 Segments: ......【输出目标格式 (JSON List)】必须返回一个包含对应数量对象的 JSON 列表,每个对象对应一个 15秒视频。格式示例:[{"id": 1, "prompt": "(0s-1s) Scene A --HARD CUT TO--> (1s-2s) Scene B..."},2 unmodified lines【绝对铁律】1. **必须返回与输入数量一致的 Prompt**。2. 每个 Prompt 内部必须包含 15 个硬切画面。3. 风格必须是高燃、快速、唐卡视觉。4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。"""43 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 类 =================1 unmodified lineclass 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 triggered a SAFETY FILTER. ""Your task: REWRITE the prompt to be 100% SAFE. ""1. REMOVE ALL references to human figures, bodies, or children. ""2. Focus ONLY on objects, scenery, architecture, or abstract energy. ""3. Keep the visual style but change the subject to something neutral.")else:system_instruction = ("Prompt FAILED multiple times due to safety or errors. ""REWRITE as EXTREMELY CONCISE, ABSTRACT, and ARTISTIC. ""Use fewer than 10 words. No humans. Just pure visual atmosphere.")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()23 unmodified linesclass AudioAgent:def __init__(self):self.headers = {"Authorization": f"Bearer {WHISPER_API_KEY}"}def compress_audio(self, input_path, logger_func, force=False):if not force and os.path.getsize(input_path) < 24 * 1024 * 1024: return input_pathprefix = "🔊 [强压模式]" if force else "📦 [普通压缩]"logger_func(f"{prefix} 正在压缩音频: {os.path.basename(input_path)}...")output_path = input_path.rsplit('.', 1)[0] + f"_compressed_{int(time.time())}.mp3"try:bitrate = "16k" if force else "32k"subprocess.run(["ffmpeg", "-y", "-i", input_path, "-ar", "16000", "-ac", "1", "-b:a", bitrate, output_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)return output_pathexcept: return input_pathdef _execute_transcribe(self, file_path, max_attempts, logger_func):url = "https://api.apimart.ai/v1/audio/transcriptions"for attempt in range(max_attempts):try:logger_func(f"🎙️ Whisper (Apimart) 识别中 ({attempt+1}/{max_attempts})...")with open(file_path, "rb") as f:files = {"file": (os.path.basename(file_path), f, "audio/mp3")}data = {"model": "whisper-1", "language": "zh", "response_format": "verbose_json"}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_jsonlogger_func(f"⚠️ 识别失败 (HTTP {resp.status_code}),重试中...")time.sleep(3)except Exception as e:logger_func(f"⚠️ 请求异常: {e}")time.sleep(3)return Nonedef transcribe_audio_with_retry(self, audio_path, logger_func):logger_func("🎙️ [Phase 1] 首次识别尝试...")initial_path = self.compress_audio(audio_path, logger_func, force=False)res = self._execute_transcribe(initial_path, 5, logger_func)if res: return reslogger_func("⚠️ [Phase 1] 失败,启动 [Phase 2] 极限压缩重试...")compressed_path = self.compress_audio(audio_path, logger_func, force=True)res = self._execute_transcribe(compressed_path, 5, logger_func)if res: return reslogger_func("❌ Whisper 最终失败,将使用纯字数比例分配。")return Noneclass VideoAgent:def __init__(self, director_instance=None):self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"}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:log_queue.put(f"♻️ [视频{global_video_idx+1}] 第 {rewrite_cycle} 次触发安全改写...")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:payload = {"images": [],"model": SORA_MODEL,"orientation": ORIENTATION,"prompt": final_prompt,"size": VIDEO_SIZE,"duration": VIDEO_DURATION,"watermark": False,"private": True}req = requests.post(f"{MERCHANT_BASE_URL}/v1/video/create", headers=self.headers, json=payload, timeout=60)if req.status_code != 200:log_queue.put(f"⚠️ [API Error {req.status_code}] {req.text[:100]}")if req.status_code == 400: breaktime.sleep(2); continuetask_id = req.json().get("id")if not task_id: continuelog_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中 (Cycle {rewrite_cycle})...")start_time = time.time()while True:if time.time() - start_time > 600: breakstatus_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30)8 unmodified lineselif status == "failed": breaktime.sleep(3)else: time.sleep(3)except Exception as e:log_queue.put(f"⚠️ 生成异常: {e}")time.sleep(3)log_queue.put(f"❌ 视频{global_video_idx+1} 彻底失败 (已尝试 3个Prompt版本 x 5次网络请求)")return None# ================= 渲染核心 =================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"🏭 启动 V9.2 生产线 (Sora版)...")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(f"⚠️ Whisper 最终失败,使用字数比例分配 (总长: {total_audio:.1f}s)")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# ----------------- 后台工作线程 -----------------# 🔥 修改:接受 local_json_path 参数def background_worker(task_id, full_text, audio_path, system_prompt, original_filename, local_json_path):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]# 🔥🔥🔥 核心修改:优先读取本地 JSON 🔥🔥🔥whisper_result = Noneif local_json_path and os.path.exists(local_json_path):log_wrapper(f"📂 发现本地 Whisper JSON: {os.path.basename(local_json_path)}")try:with open(local_json_path, 'r', encoding='utf-8') as f:whisper_result = json.load(f)log_wrapper("✅ 本地 JSON 加载成功,跳过 API 调用。")# 如果用户没有填文案,尝试从 JSON 中提取if not full_text.strip():if 'text' in whisper_result:full_text = whisper_result['text']log_wrapper("📄 从 JSON 中自动提取了全文文案。")else:# 尝试从 segments 拼接full_text = "".join([s['text'] for s in whisper_result.get('segments', [])])log_wrapper("📄 从 JSON Segments 中拼接了全文文案。")except Exception as e:log_wrapper(f"❌ 本地 JSON 读取失败: {e},将尝试使用 API。")whisper_result = None# 只有在没有本地结果时才调用 APIif whisper_result is None:log_wrapper("🎙️ 正在调用 Whisper API (未提供本地JSON或读取失败)...")audio_agent = AudioAgent()whisper_result = audio_agent.transcribe_audio_with_retry(local_audio_path, log_wrapper)if not full_text.strip():log_wrapper("❌ 错误:无法获取文案(请手动填写或确保 JSON 包含 text 字段)。")task_manager.update_status(task_id, "failed")returnraw_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} 个视频任务 (每视频15秒)。")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 生成与视频渲染并发中 (并发数: {VIDEO_WORKERS})...")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: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, json_file, system_prompt, manual_text):final_text = manual_textoriginal_fname = "project"local_json_path = Noneif json_file is not None:local_json_path = json_file.nameif 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: pass# 如果有 JSON 且文案为空,允许通过(后台会自动提取)if not final_text.strip() and not local_json_path: return "❌ 文案不能为空 (除非上传了JSON)", Noneif not audio_file: return "❌ 缺音频", Nonetask_id, task_dir = task_manager.create_task(original_fname)# 🔥 传入 local_json_patht = threading.Thread(target=background_worker, args=(task_id, final_text, audio_file, system_prompt, original_fname, local_json_path))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.2 Sora Edition (Limit Broken + Local)") as demo:gr.Markdown("## 🎬 Veo V9.2 Sora Edition (Limit Broken + Local Whisper)")gr.Markdown("🌟 **特性**:5000并发、支持本地 JSON 上传(省钱)、智能安全改写")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="文案内容 (留空则从JSON自动读取)", lines=8)audio_input = gr.Audio(label="2. 上传音频 (必选)", type="filepath")# 🔥 新增 JSON 上传控件json_input = gr.File(label="3. (省钱) 上传本地 Whisper JSON", file_types=[".json"])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,# 🔥 增加 json_input[txt_input, audio_input, json_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+459-227