Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831import sysimport subprocessimport osimport shutilimport timeimport jsonimport requestsimport zipfileimport queueimport reimport threadingimport globimport tracebackfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom difflib import SequenceMatcher
# ==========================================# 0. 环境自动修复# ==========================================def install_package(package, pip_name=None): pip_name = pip_name or package try: __import__(package) except ImportError: print(f"📦 正在自动安装缺失库: {pip_name} ...") subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])
install_package("moviepy", "moviepy==1.0.3") install_package("whisper", "openai-whisper")install_package("opencc", "opencc-python-reimplemented") install_package("PIL", "Pillow")
import gradio as grimport openccfrom moviepy.editor import VideoFileClip, AudioFileClip, vfx
# ================= 配置区域 =================
# 视频生成的 API Key (Sora, LLM 等) - 保持云雾原有 KeyYUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"
# Apifox/Apimart 专用 Whisper KeyWHISPER_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 = 10
# 建议在 HF Settings 挂载 Persistent Storage 到此目录 (如 /data/tasks_data)TASKS_ROOT_DIR = "tasks_data"
# 🔥🔥 极限并发修改 🔥🔥VIDEO_WORKERS = 5000 # 视频生成并发拉满到 5000LLM_WORKERS = 5000 # 提示词生成并发拉满到 5000RENDER_PARALLELISM = 32 # 渲染线程适当增加(过高会爆内存)
# 全局渲染锁GLOBAL_RENDER_LOCK = threading.Lock()
FORCE_STYLE_PREFIX = ( "A sacred Tibetan Thangka painting style on aged cotton canvas. " "Rich mineral pigment colors (ground lapis lazuli, malachite, cinnabar, gold lines). " "Solemn deities, flat perspective with divine aura. ")
FORCE_MOTION_BOOSTER = ( " , (EXTREME VISUAL VELOCITY: hard cuts every second, stroboscopic editing style, " "hyper-lapse speed, visual explosion, distinct unrelated scenes, frantic energy, " "kaleidoscope effect, elements constantly morphing and breaking, no continuity), ")
FORCE_STYLE_SUFFIX = ( " , highly detailed Thangka line work (Goujin), traditional cloth texture, masterpiece, " "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..."}, ...]
【绝对铁律】1. **必须返回与输入数量一致的 Prompt**。2. 每个 Prompt 内部必须包含 15 个硬切画面。3. 风格必须是高燃、快速、唐卡视觉。4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。"""
# ================= 核心工具函数 =================
def strict_text_splitter(text): chunks = [] current_chunk = "" valid_count = 0 punctuations = set(",。!?;:、,.;:!?\n\t ") for char in text: current_chunk += char if char not in punctuations: valid_count += 1 should_cut = False if 15 <= valid_count <= 25: if char in punctuations: should_cut = True if valid_count > 25: should_cut = True if should_cut: if current_chunk.strip(): chunks.append(current_chunk.strip()) current_chunk = "" valid_count = 0 if current_chunk.strip(): chunks.append(current_chunk.strip()) if len(chunks) > 1 and len(chunks[-1]) < 8: last_short = chunks.pop() chunks[-1] += last_short return chunks
def normalize_text(text): return re.sub(r"[^\w]", "", text)
def format_timestamp(seconds): millis = int((seconds - int(seconds)) * 1000) seconds = int(seconds) minutes = seconds // 60 hours = minutes // 60 minutes %= 60 seconds %= 60 return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"
def generate_srt_file(subtitle_data, output_path): with open(output_path, 'w', encoding='utf-8') as f: for i, sub in enumerate(subtitle_data): start_str = format_timestamp(sub['start']) end_str = format_timestamp(sub['end']) text = sub['text'] f.write(f"{i+1}\n{start_str} --> {end_str}\n{text}\n\n") return output_path
def 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) except: truth_text_trad = truth_text_raw truth_clean = truth_text_trad.replace("\n", "") corrected_segments = [] truth_cursor = 0 for i, seg in enumerate(whisper_segments): whisper_text = seg['text'] if not whisper_text.strip(): continue search_window = len(whisper_text) + 20 search_area = truth_clean[truth_cursor : truth_cursor + search_window] matcher = SequenceMatcher(None, whisper_text, search_area) match = matcher.find_longest_match(0, len(whisper_text), 0, len(search_area)) if match.size > 1: current_text_len = match.b + match.size final_len = max(len(whisper_text), current_text_len) else: final_len = len(whisper_text) if truth_cursor + final_len > len(truth_clean): final_len = len(truth_clean) - truth_cursor corrected_text = truth_clean[truth_cursor : truth_cursor + final_len] truth_cursor += final_len corrected_segments.append({"start": seg['start'], "end": seg['end'], "text": corrected_text}) if truth_cursor >= len(truth_clean): break return corrected_segments
def 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 = 0 for seg_list in text_segments: group_text = normalize_text("".join(seg_list)) length = len(group_text) group_char_ranges.append((current_char_idx, current_char_idx + length)) source_full_text += group_text current_char_idx += length
char_time_map = {} whisper_full_text = "" w_cursor = 0 for seg in whisper_segments: seg_text = normalize_text(seg['text']) if not seg_text: continue start_t = seg['start'] end_t = seg['end'] duration = end_t - start_t seg_len = len(seg_text) seg_start_idx = w_cursor for i in range(seg_len): t = start_t + (i / seg_len) * duration char_time_map[seg_start_idx + i] = t whisper_full_text += seg_text w_cursor += seg_len
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): source_to_whisper_index[i1 + k] = j1 + k elif tag == 'replace': s_len = i2 - i1 w_len = j2 - j1 for 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.0 for i, (start_char, end_char) in enumerate(group_char_ranges): found_time = None for offset in range(min(5, end_char - start_char)): target = start_char + offset if target in source_to_whisper_index: w_idx = source_to_whisper_index[target] if w_idx in char_time_map: found_time = char_time_map[w_idx] break if found_time is not None: if found_time < last_valid_time: found_time = last_valid_time cut_points.append(found_time) last_valid_time = found_time else: 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_start final_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): self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"} # 🔥 核心修改:改写安全提示词的逻辑 (Level 1 & 2) 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() except: pass return old_prompt
def generate_batch_prompts(self, batch_data, system_prompt): user_msg = f"Generate prompts for {len(batch_data)} videos:\n\n" for i, group in enumerate(batch_data): video_text = " | ".join([f"({s}s) {txt}" for s, txt in enumerate(group)]) user_msg += f"Video {i+1} Segments: {video_text}\n" payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}], "response_format": {"type": "json_object"}} for _ in range(3): try: resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=120) if resp.status_code == 200: content = resp.json()['choices'][0]['message']['content'] if "```json" in content: content = content.split("```json")[1].split("```")[0] elif "```" in content: content = content.split("```")[1].split("```")[0] data = json.loads(content) if isinstance(data, dict): for v in data.values(): if isinstance(v, list): return v if isinstance(data, list): return data except: time.sleep(1) return [{"prompt": f"Fallback prompt {i}"} for i in range(len(batch_data))]
class AudioAgent: def __init__(self): self.headers = {"Authorization": f"Bearer {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_path prefix = "🔊 [强压模式]" 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_path except: return input_path
def _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_json logger_func(f"⚠️ 识别失败 (HTTP {resp.status_code}),重试中...") if resp.status_code != 200: try: logger_func(f"错误详情: {resp.text[:200]}") except: pass time.sleep(3) except Exception as e: logger_func(f"⚠️ 请求异常: {e}") time.sleep(3) return None
def 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 res
logger_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 res logger_func("❌ Whisper 最终失败,将使用纯字数比例分配。") return None
class VideoAgent: def __init__(self, director_instance=None): self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"} self.director = director_instance # 🔥 核心修改:Worker 任务逻辑(包含重试与改写) def worker_task(self, prompt, global_video_idx, log_queue, save_dir): save_path = os.path.join(save_dir, f"clip_{global_video_idx+1:04d}.mp4") if os.path.exists(save_path) and os.path.getsize(save_path) > 1000: return save_path current_prompt_core = prompt # 🔥 外层循环:3次改写机会 (初始 + 改写1 + 改写2) for 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_core except: pass final_prompt = (f"{FORCE_STYLE_PREFIX} {current_prompt_core} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}") final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".") # 🔥 内层循环:5次网络/超时重试 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]}") # 如果是 400 Bad Request,通常是敏感词问题,直接跳出内层循环去改写 if req.status_code == 400: break time.sleep(2); continue task_id = req.json().get("id") if not task_id: continue log_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中 (Cycle {rewrite_cycle})...") start_time = time.time() while True: if time.time() - start_time > 600: break status_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30) if status_resp.status_code == 200: status = status_resp.json().get("status") if status == "completed": video_url = status_resp.json().get("video_url") if video_url: with open(save_path, "wb") as f: f.write(requests.get(video_url, timeout=120).content) log_queue.put(f"⬇️ 视频{global_video_idx+1} 下载完成") return save_path elif status == "failed": # 状态明确为 failed,跳出查询,进入重试或改写 break time.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.5 speed_factor = raw_clip.duration / target_duration video_clip = raw_clip.fx(vfx.speedx, factor=speed_factor) video_clip.write_videofile(output_filename, fps=24, codec="libx264", audio=False, threads=2, preset='ultrafast', ffmpeg_params=["-crf", "26"], logger=None) video_clip.close(); raw_clip.close() return True except Exception as e: logger_func(f"❌ [Group {group_id}] 渲染失败: {e}") return False
def 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 False
final_subtitle_data = [] srt_path = output_zip_path.replace(".zip", ".srt") if whisper_result and 'segments' in whisper_result: final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], 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]
video_files = sorted(video_files) total_items = min(len(video_files), len(segment_durations)) temp_dir = os.path.dirname(output_zip_path); chunk_dir = os.path.join(temp_dir, "chunks_temp"); os.makedirs(chunk_dir, exist_ok=True) global_cursor = 0.0; group_configs = [] for i in range(total_items): target_d = segment_durations[i] group_configs.append({'id': i + 1, 'vid': video_files[i], 'dur': target_d, 'start': global_cursor, 'out': os.path.join(chunk_dir, f"part_{i+1:04d}.mp4")}) global_cursor += target_d
completed_count = 0 with ThreadPoolExecutor(max_workers=RENDER_PARALLELISM) as renderer: future_map = {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 += 1
logger_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: for p in valid_chunks: f.write(f"file '{os.path.abspath(p)}'\n") try: subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) 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 True except Exception as e: logger_func(f"❌ 拼接/打包失败: {e}") return False
def 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_dir os.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_dir
def 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: pass print(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 None log_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 tasks
def 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_manager self.tid = task_id def put(self, message): self.tm.log(self.tid, message) def get(self): return None def 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_id if original_filename: zip_basename = os.path.splitext(original_filename)[0] raw_segments = strict_text_splitter(full_text) video_text_groups = [] # SEGMENTS_PER_VIDEO 保持 15 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秒)。") 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 生成与视频渲染并发中 (并发数: {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_BATCH for i, p_obj in enumerate(prompts): p_text = p_obj.get("prompt", "") if isinstance(p_obj, dict) else str(p_obj) gid = start_id + i if gid < total_videos: # 传入 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): break time.sleep(2)
video_paths = [None] * total_videos for 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_text original_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 = content original_fname = os.path.basename(txt_file.name) except: pass if not final_text.strip(): return "❌ 文案不能为空", None if not audio_file: return "❌ 缺音频", None
task_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_id
def 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, None info = task_manager.get_task_info(task_id) if not info: return "任务不存在", None, None return 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)") as demo: gr.Markdown("## 🎬 Veo V9.2 Sora Edition (5000 Concurrency)") gr.Markdown("🌟 **特性**:Limit Broken (5000并发)、Apifox Whisper、智能安全改写") 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.pyAdded+831