Update app.py
Browse files12 unmodified lines1314151617181916 unmodified lines3637383940414243442 unmodified lines474849505152535455565758596061626364656667686983 unmodified lines1531541551561571581591601611621634 unmodified lines1681691701711721731 unmodified line1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262271 unmodified line22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027152 unmodified lines32432532632732832919 unmodified lines3493503513523533543553564 unmodified lines36136236336436536626 unmodified lines39339439539639739839951 unmodified lines45145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648757 unmodified lines54554654754854955055186 unmodified lines63863964064164264364464564612 unmodified linesprint(f"📦 正在自动安装缺失库: {pip_name} ...")subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])# 核心依赖install_package("moviepy", "moviepy==1.0.3")install_package("whisper", "openai-whisper")install_package("PIL", "Pillow")16 unmodified linesfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcherfrom PIL import Image, ImageDraw, ImageFontimport openccfrom moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, vfx, ImageClip, CompositeVideoClip# ================= 配置区域 =================2 unmodified linesYUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"MERCHANT_BASE_URL = "https://yunwu.ai"# 2. 模型配置 (根据 API 文档修正)VEO_MODEL = "veo_3_1-fast"VIDEO_SIZE = "16x9" # 文档要求 16x9VIDEO_DURATION = "8" # 文档要求字符串 "8"# 3. 辅助模型TEXT_MODEL = "gemini-3-pro-preview-thinking"WHISPER_MODEL = "whisper-1"SEGMENTS_PER_VIDEO = 8VIDEOS_PER_BATCH = 10# 3. 系统配置BASE_OUTPUT_DIR = "project_thangka_hf_full"VIDEO_WORKERS = 150LLM_WORKERS = 5# 4. 字幕配置FONT_URL = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/TraditionalChinese/NotoSansCJKtc-Bold.otf"LOCAL_FONT_PATH = "NotoSansCJKtc-Bold.otf"SUBTITLE_FONT_SIZE = 4583 unmodified linesdef normalize_text(text):return re.sub(r"[^\w]", "", text)# ================= 1. 字幕真理修正算法 (以文案为准) =================def align_transcript_with_truth(truth_text_raw, whisper_segments, log_queue):log_queue.put("🔄 正在执行【真理修正算法】:使用上传文案替换 Whisper 识别文本...")try:cc = opencc.OpenCC('s2t')truth_text_trad = cc.convert(truth_text_raw)4 unmodified linescorrected_segments = []truth_cursor = 0for i, seg in enumerate(whisper_segments):whisper_text = seg['text']start_t = seg['start']1 unmodified lineif not whisper_text.strip(): continuesearch_window_size = len(whisper_text) + 20search_area = truth_clean[truth_cursor : truth_cursor + search_window_size]# 使用 SequenceMatcher 找最佳匹配matcher = SequenceMatcher(None, whisper_text, search_area)match = matcher.find_longest_match(0, len(whisper_text), 0, len(search_area))if match.size > 1:# 找到了相似片段current_text_len = match.b + match.sizefinal_len = max(len(whisper_text), current_text_len)else:# 没匹配上,强制按长度final_len = len(whisper_text)if truth_cursor + final_len > len(truth_clean):final_len = len(truth_clean) - truth_cursorcorrected_text = truth_clean[truth_cursor : truth_cursor + final_len]truth_cursor += final_lencorrected_segments.append({"start": start_t,"end": end_t,"text": corrected_text})if truth_cursor >= len(truth_clean): breaklog_queue.put(f"✅ 字幕修正完毕,生成 {len(corrected_segments)} 条繁体字幕。")return corrected_segments# ================= 2. 视频时长估算与对齐算法 (恢复的代码) =================def estimate_durations_fallback(text_segments, total_audio_duration):"""兜底算法:按字数比例分配时间"""lengths = [len("".join(seg)) for seg in text_segments]total_len = sum(lengths)if total_len == 0: return [float(VIDEO_DURATION)] * len(text_segments)return [(L / total_len) * total_audio_duration for L in lengths]def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue):"""尝试将 8秒的视频素材 对齐到 Whisper 的时间轴上。逻辑:1. 计算每段视频对应的文本大概在 Whisper 里是哪几句。2. 获取这几句 Whisper 的 start 和 end。3. 算出该段视频应该持续多久。"""if not whisper_segments:return estimate_durations_fallback(text_segments, total_audio_duration)1 unmodified linevideo_durations = []whisper_idx = 0for i, segment_texts in enumerate(text_segments):# 这段视频包含的文字full_text = "".join(segment_texts)clean_text = normalize_text(full_text)current_len = 0target_len = len(clean_text)start_time = Noneend_time = None# 在 Whisper segments 里往前走,直到凑够字数while whisper_idx < len(whisper_segments):seg = whisper_segments[whisper_idx]seg_len = len(normalize_text(seg['text']))if start_time is None: start_time = seg['start']end_time = seg['end']current_len += seg_lenwhisper_idx += 1# 如果凑够了大部分字数 (模糊匹配)if current_len >= target_len * 0.8:breakif start_time is not None and end_time is not None:dur = end_time - start_time# 最小 1 秒,防止视频过快if dur < 1.0: dur = 1.0video_durations.append(dur)else:# 没匹配到,给个平均值video_durations.append(float(VIDEO_DURATION))return video_durations# ================= 核心逻辑类 =================class DirectorAgent:def __init__(self):52 unmodified linesclass VideoAgent:def __init__(self):self.base_headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}def deep_find_url(self, data):19 unmodified linesform_data = {"model": VEO_MODEL,"prompt": final_prompt,"seconds": VIDEO_DURATION, # "8""size": VIDEO_SIZE, # "16x9""watermark": "false"}4 unmodified linestimeout=60)if req.status_code != 200:try: err_msg = req.json()except: err_msg = req.text[:100]26 unmodified linestime.sleep(2)return None# ================= 剪辑与绘图 =================def text_to_image_clip(text, duration, video_w, video_h):img = Image.new('RGBA', (video_w, video_h), (0, 0, 0, 0))51 unmodified lineslog_queue.put(f"❌ 音频文件读取失败: {e}")return False# 1. 字幕数据 (真理修正)final_subtitle_data = []if whisper_result and 'segments' in whisper_result:final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], log_queue)else:log_queue.put("⚠️ Whisper 失败,无法生成字幕。")# 2. 视频时长计算 (尝试使用 Whisper 时间轴对��,而非简单平分)# 恢复了复杂的 calculate_video_durations_from_whisperif final_subtitle_data:# 如果有修正后的字幕数据,直接用这个数据来计算每一段视频应该多长# 这里需要把 text_segments (剧本分段) 和 final_subtitle_data (时间轴) 对应起来# 简单起见,我们还是用 calculate_video_durations_from_whisper 配合原始 whisper result# 或者直接使用兜底算法保证稳定性# 为了稳健,我们使用 混合模式:segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio_duration, log_queue)else:segment_durations = estimate_durations_fallback(text_segments, total_audio_duration)# 3. 剪辑final_clips = []video_files = sorted(video_files)min_len = min(len(video_files), len(segment_durations))log_queue.put(f"🎞️ 开始处理 {min_len} 个视频片段...")for i in range(min_len):vid_path = video_files[i]target_d = segment_durations[i]try:clip = VideoFileClip(vid_path)factor = clip.duration / target_dnew_clip = clip.fx(vfx.speedx, factor=factor)final_clips.append(new_clip)57 unmodified linesif new_msg: logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {new_msg}")return "\n".join(logs[-100:])yield update_ui("🚀 系统启动 (完整功能版)..."), Nonedownload_font_if_missing()raw_segments = strict_text_splitter(full_text)86 unmodified lines# ================= UI 界面 =================with gr.Blocks(title="Veo Pro Full") as demo:gr.Markdown("## 🎬 Veo 全自动音画工厂 (完整功能版)")gr.Markdown("🌟 **功能全集**:API适配 | 智能字幕修正 | 精准视频对齐 | HF兼容")with gr.Row():with gr.Column(scale=3):in_text = gr.Textbox(label="1. 输入长文案", lines=8)12 unmodified lines1314151617181916 unmodified lines36373839404142434445462 unmodified lines495051525354555657585960616263646566676869707183 unmodified lines1551561571581591601611621631641651664 unmodified lines1711721731741751761771 unmodified line1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified line23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727852 unmodified lines33133233333433533633719 unmodified lines3573583593603613623633644 unmodified lines36937037137237337437526 unmodified lines40240340440540640740851 unmodified lines46046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649757 unmodified lines55555655755855956056186 unmodified lines64864965065165265365465565612 unmodified linesprint(f"📦 正在自动安装缺失库: {pip_name} ...")subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])# 核心依赖安装install_package("moviepy", "moviepy==1.0.3")install_package("whisper", "openai-whisper")install_package("PIL", "Pillow")16 unmodified linesfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher# 图形处理from PIL import Image, ImageDraw, ImageFontimport opencc# 视频处理from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, vfx, ImageClip, CompositeVideoClip# ================= 配置区域 =================2 unmodified linesYUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"MERCHANT_BASE_URL = "https://yunwu.ai"# 2. 模型配置 (严格按照您的API文档)VEO_MODEL = "veo_3_1-fast"VIDEO_SIZE = "16x9" # 文档要求 16x9VIDEO_DURATION_STR = "8" # 文档要求字符串 "8"# 3. 辅助配置TEXT_MODEL = "gemini-3-pro-preview-thinking"WHISPER_MODEL = "whisper-1"SEGMENTS_PER_VIDEO = 8VIDEOS_PER_BATCH = 10# 4. 系统配置BASE_OUTPUT_DIR = "project_thangka_final_release"VIDEO_WORKERS = 150LLM_WORKERS = 5# 5. 字幕配置 (繁体字体)FONT_URL = "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/TraditionalChinese/NotoSansCJKtc-Bold.otf"LOCAL_FONT_PATH = "NotoSansCJKtc-Bold.otf"SUBTITLE_FONT_SIZE = 4583 unmodified linesdef normalize_text(text):return re.sub(r"[^\w]", "", text)# ================= 核心算法1:字幕真理修正 (映射原文+转繁体) =================def align_transcript_with_truth(truth_text_raw, whisper_segments, log_queue):log_queue.put("🔄 正在执行【真理修正算法】:使用上传文案替换 Whisper 识别文本...")# 1. 准备繁体原文 (真理库)try:cc = opencc.OpenCC('s2t')truth_text_trad = cc.convert(truth_text_raw)4 unmodified linescorrected_segments = []truth_cursor = 0# 2. 遍历 Whisper 时间轴for i, seg in enumerate(whisper_segments):whisper_text = seg['text']start_t = seg['start']1 unmodified lineif not whisper_text.strip(): continue# 3. 在真理库中寻找最相似的片段# 截取一段窗口,避免全篇搜索效率低search_window_size = len(whisper_text) + 20search_area = truth_clean[truth_cursor : truth_cursor + search_window_size]# 使用 SequenceMatcher 进行模糊匹配matcher = SequenceMatcher(None, whisper_text, search_area)match = matcher.find_longest_match(0, len(whisper_text), 0, len(search_area))if match.size > 1:# 找到了对应原文current_text_len = match.b + match.sizefinal_len = max(len(whisper_text), current_text_len)else:# 没找到(可能是杂音),强制按长度截取,保证字幕不丢final_len = len(whisper_text)# 边界保护if truth_cursor + final_len > len(truth_clean):final_len = len(truth_clean) - truth_cursor# 4. 提取原文 (繁体, 无错别字)corrected_text = truth_clean[truth_cursor : truth_cursor + final_len]truth_cursor += final_lencorrected_segments.append({"start": start_t,"end": end_t,"text": corrected_text # 这里存的是真理文本})if truth_cursor >= len(truth_clean): breaklog_queue.put(f"✅ 字幕修正完毕,生成 {len(corrected_segments)} 条繁体字幕。")return corrected_segments# ================= 核心算法2:视频音画对齐 (变速慢放) =================def estimate_durations_fallback(text_segments, total_audio_duration):"""兜底算法:当 Whisper 失败时,按字数分配时长"""lengths = [len("".join(seg)) for seg in text_segments]total_len = sum(lengths)if total_len == 0: return [float(VIDEO_DURATION_STR)] * len(text_segments)return [(L / total_len) * total_audio_duration for L in lengths]def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue):"""逻辑:将 剧本分段 (text_segments) 与 Whisper 时间轴进行匹配,计算出每一段视频【应该】有多长,以便后续进行变速。"""if not whisper_segments:return estimate_durations_fallback(text_segments, total_audio_duration)1 unmodified linevideo_durations = []whisper_idx = 0# 遍历每一段视频对应的剧本for i, segment_texts in enumerate(text_segments):full_text = "".join(segment_texts)# 这一段视频理论上的总字数target_len = len(normalize_text(full_text))current_len = 0start_time = Noneend_time = None# 在 Whisper 结果中累加,直到凑够这段视频的字数while whisper_idx < len(whisper_segments):seg = whisper_segments[whisper_idx]seg_len = len(normalize_text(seg['text']))if start_time is None: start_time = seg['start']# 持续更新结束时间end_time = seg['end']current_len += seg_lenwhisper_idx += 1# 如果凑够了 80% 的字数,就认为这段视频的音频结束了if current_len >= target_len * 0.8:breakif start_time is not None and end_time is not None:dur = end_time - start_time# 限制最小 1 秒,防止视频被压缩得太快if dur < 1.0: dur = 1.0video_durations.append(dur)else:# 如果匹配失败,使用默认时长video_durations.append(float(VIDEO_DURATION_STR))return video_durations# ================= Agent 类定义 =================class DirectorAgent:def __init__(self):52 unmodified linesclass VideoAgent:def __init__(self):# Multipart 请求不需要手动设 Content-Typeself.base_headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"}def deep_find_url(self, data):19 unmodified linesform_data = {"model": VEO_MODEL,"prompt": final_prompt,"seconds": VIDEO_DURATION_STR, # "8""size": VIDEO_SIZE, # "16x9""watermark": "false"}4 unmodified linestimeout=60)# 错误显影if req.status_code != 200:try: err_msg = req.json()except: err_msg = req.text[:100]26 unmodified linestime.sleep(2)return None# ================= 剪辑与字幕绘图 =================def text_to_image_clip(text, duration, video_w, video_h):img = Image.new('RGBA', (video_w, video_h), (0, 0, 0, 0))51 unmodified lineslog_queue.put(f"❌ 音频文件读取失败: {e}")return False# 1. 修正字幕数据 (Truth Correction)final_subtitle_data = []if whisper_result and 'segments' in whisper_result:final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], log_queue)else:log_queue.put("⚠️ Whisper 失败,无法生成字幕。")# 2. 计算精准的视频时长 (Video Alignment)# 使用 calculate_video_durations_from_whisper 来确保视频慢放后时长 = 音频时长if whisper_result and 'segments' in whisper_result:segment_durations = calculate_video_durations_from_whisper(text_segments,whisper_result['segments'],total_audio_duration,log_queue)else:segment_durations = estimate_durations_fallback(text_segments, total_audio_duration)# 3. 视频合成final_clips = []video_files = sorted(video_files)min_len = min(len(video_files), len(segment_durations))log_queue.put(f"🎞️ 开始处理 {min_len} 个视频片段 (变速对齐中)...")for i in range(min_len):vid_path = video_files[i]target_d = segment_durations[i]try:clip = VideoFileClip(vid_path)# 核心:计算拉伸因子factor = clip.duration / target_dnew_clip = clip.fx(vfx.speedx, factor=factor)final_clips.append(new_clip)57 unmodified linesif new_msg: logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {new_msg}")return "\n".join(logs[-100:])yield update_ui("🚀 系统启动 (最终确认版)..."), Nonedownload_font_if_missing()raw_segments = strict_text_splitter(full_text)86 unmodified lines# ================= UI 界面 =================with gr.Blocks(title="Veo Pro Ultimate") as demo:gr.Markdown("## 🎬 Veo 全自动音画工厂 (最终交付版)")gr.Markdown("✅ 功能确认:\n1. 视频慢放对齐音频\n2. 字幕强制替换为繁体原文\n3. 视频接口适配 16x9")with gr.Row():with gr.Column(scale=3):in_text = gr.Textbox(label="1. 输入长文案", lines=8)
app.py+60-50