Spaces:
Sleeping

File size: 28,325 Bytes
f2079b3
 
b77f9ad
bfa48e3
 
 
 
 
 
 
 
 
 
 
 
 
f2079b3
 
b491001
f2079b3
 
 
 
 
 
 
 
 
b491001
f2079b3
 
c65a2ee
bfa48e3
c65a2ee
f2079b3
 
bfa48e3
f2079b3
 
 
bfa48e3
f2079b3
b77f9ad
 
 
 
 
 
 
31907ef
b373acc
31907ef
bfa48e3
94b94b4
ff4aa64
b77f9ad
f2079b3
1cbe8f7
bfa48e3
b77f9ad
b491001
5660418
bfa48e3
 
5660418
b77f9ad
5660418
b77f9ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfa48e3
 
b77f9ad
 
 
 
690c378
b77f9ad
 
 
 
690c378
b77f9ad
 
 
690c378
b77f9ad
 
 
 
 
 
 
690c378
ee2010a
b77f9ad
bfa48e3
b77f9ad
 
f2079b3
 
b77f9ad
5660418
b77f9ad
 
 
 
 
 
f2079b3
b77f9ad
 
 
 
 
 
 
 
 
 
 
f2079b3
 
 
5660418
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfa48e3
ee2010a
 
b491001
ee2010a
 
 
 
c65a2ee
ee2010a
 
 
 
 
 
 
 
bfa48e3
 
 
ee2010a
 
 
 
 
 
 
 
 
 
 
 
bfa48e3
ee2010a
 
 
 
bfa48e3
 
 
ee2010a
c65a2ee
ee2010a
 
 
5660418
94b94b4
 
 
 
bfa48e3
31907ef
bfa48e3
94b94b4
 
 
 
 
 
 
1cbe8f7
94b94b4
 
1cbe8f7
 
 
 
94b94b4
 
1cbe8f7
 
 
94b94b4
 
1cbe8f7
 
 
 
 
 
 
 
31907ef
1cbe8f7
 
 
 
94b94b4
1cbe8f7
 
 
 
 
31907ef
1cbe8f7
 
94b94b4
b491001
1cbe8f7
 
 
31907ef
1cbe8f7
 
 
 
 
b491001
1cbe8f7
 
 
94b94b4
 
5660418
b77f9ad
 
 
f2079b3
b491001
bfa48e3
 
5660418
bfa48e3
5660418
bfa48e3
 
 
 
 
 
b491001
b77f9ad
690c378
b77f9ad
 
 
bfa48e3
b491001
5660418
b77f9ad
 
 
 
 
 
 
 
 
 
 
f2079b3
 
 
 
 
 
b491001
bfa48e3
 
 
 
 
 
 
 
b491001
f2079b3
bfa48e3
f2079b3
 
 
bfa48e3
 
 
c65a2ee
f2079b3
 
 
bfa48e3
f2079b3
bfa48e3
f2079b3
b77f9ad
 
bfa48e3
 
 
b491001
b77f9ad
 
bfa48e3
 
b491001
bfa48e3
 
 
 
 
 
b491001
bfa48e3
 
b491001
bfa48e3
 
 
 
 
 
 
 
 
 
b491001
bfa48e3
 
b491001
bfa48e3
 
b491001
bfa48e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b77f9ad
 
5660418
bfa48e3
5660418
 
 
 
 
231a388
f2079b3
bfa48e3
 
 
 
5660418
 
bfa48e3
 
 
 
5660418
bfa48e3
 
 
 
 
 
 
 
 
f2079b3
bfa48e3
 
 
5660418
 
bfa48e3
 
 
 
 
 
231a388
5660418
ee2010a
5660418
bfa48e3
ee2010a
5660418
 
 
 
231a388
5660418
bfa48e3
 
94b94b4
bfa48e3
f2079b3
 
bfa48e3
f2079b3
5660418
 
bfa48e3
 
 
 
b491001
bfa48e3
 
 
b491001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5660418
b491001
 
 
 
 
 
5660418
 
bfa48e3
 
5660418
bfa48e3
b491001
 
 
 
 
bfa48e3
b491001
bfa48e3
 
f2079b3
bfa48e3
8c5173b
f2079b3
bfa48e3
 
5660418
8c5173b
f2079b3
bfa48e3
5660418
 
 
 
 
 
 
 
f2079b3
 
bfa48e3
 
b77f9ad
bfa48e3
 
 
 
 
 
 
b77f9ad
f2079b3
b491001
 
bfa48e3
b77f9ad
 
 
 
 
 
f2079b3
b491001
f2079b3
b491001
bfa48e3
5660418
b77f9ad
 
f2079b3
 
 
 
bfa48e3
b491001
bfa48e3
b491001
f2079b3
 
b77f9ad
bfa48e3
 
f2079b3
 
 
 
b77f9ad
f2079b3
 
b491001
b77f9ad
 
f2079b3
 
 
 
b77f9ad
f2079b3
 
b77f9ad
f2079b3
 
 
 
 
 
 
 
b491001
bfa48e3
b77f9ad
b491001
f2079b3
b77f9ad
f2079b3
 
 
 
 
 
 
b77f9ad
bfa48e3
f2079b3
b491001
f2079b3
bfa48e3
f2079b3
bfa48e3
b77f9ad
 
 
 
f2079b3
b491001
bfa48e3
 
 
 
 
5660418
 
231a388
1cbe8f7
 
 
 
 
5660418
1cbe8f7
 
 
8c5173b
1cbe8f7
 
8c5173b
 
5660418
1cbe8f7
 
8c5173b
231a388
f2079b3
5660418
f2079b3
5660418
b77f9ad
b491001
b77f9ad
bfa48e3
b77f9ad
5660418
 
 
bfa48e3
b77f9ad
b491001
c65a2ee
 
bfa48e3
b491001
5660418
 
b491001
 
bfa48e3
b491001
b77f9ad
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
import sys
import subprocess
import os
import traceback
import shutil
import time
import json
import requests
import zipfile
import queue
import math
import re
import numpy as np
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from 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])

# 核心依赖 (无 requests_toolbelt)
install_package("moviepy", "moviepy==1.0.3") 
install_package("whisper", "openai-whisper")
install_package("PIL", "Pillow") 
install_package("numpy")          
install_package("opencc", "opencc-python-reimplemented") 

# ==========================================
# 1. 导入库
# ==========================================
import gradio as gr
import opencc
from PIL import Image, ImageDraw, ImageFont
from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, vfx, ImageClip, CompositeVideoClip

# ================= 配置区域 =================

# 1. 平台鉴权
YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"
MERCHANT_BASE_URL = "https://yunwu.ai" 

# 2. 模型配置
VEO_MODEL = "veo_3_1-fast" 
VIDEO_SIZE = "16x9"        
VIDEO_DURATION_STR = "8"    

# 3. 辅助配置
TEXT_MODEL = "gemini-3-pro-preview-thinking"
WHISPER_MODEL = "whisper-1" 
SEGMENTS_PER_VIDEO = 8       
VIDEOS_PER_BATCH = 10        

# 4. 系统配置 (工业级完整参数)
BASE_OUTPUT_DIR = "project_thangka_final_v8_5_srt" 
VIDEO_WORKERS = 150       
LLM_WORKERS = 5           
RENDER_PARALLELISM = 4    # 🔥 提升并行度:因为不渲染字幕了,CPU负载变低,可以开大一点

# 5. 风格与 Prompt 核查
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."
)

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..."},
  ...
]

【绝对铁律】
1. **必须返回与输入数量一致的 Prompt**。
2. 每个 Prompt 内部必须包含 8 个硬切画面。
3. 风格必须是高燃、快速、唐卡视觉。
4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。
"""

# ================= 核心工具函数 =================

def strict_text_splitter(text):
    """ 智能切分:15-25字 + 标点控制 """
    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())
    return chunks

def normalize_text(text):
    return re.sub(r"[^\w]", "", text)

# ================= SRT 字幕生成工具 (新增) =================

def format_timestamp(seconds):
    """ 将秒数转换为 SRT 格式 (00:00:00,000) """
    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):
    """ 生成 SRT 文件 """
    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

# ================= 核心算法1:真理修正 (Text Grounding) =================

def 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)
    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

# ================= 核心算法2:V8.0 双锁前瞻对齐 =================

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 [8.0] * len(text_segments) 
    raw_durs = [(L / total_len) * total_audio_duration for L in lengths]
    return [max(d, 5.0) for d in raw_durs] 

def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, log_queue):
    if not whisper_segments:
        return estimate_durations_fallback(text_segments, total_audio_duration)
    
    video_durations = []
    whisper_idx = 0
    group_start_indices = [0] 
    
    for i, segment_texts in enumerate(text_segments):
        truth_text = normalize_text("".join(segment_texts))
        target_len = len(truth_text)
        acc_len = 0
        acc_text_buffer = ""
        
        while whisper_idx < len(whisper_segments):
            seg_text = normalize_text(whisper_segments[whisper_idx]['text'])
            acc_text_buffer += seg_text
            acc_len += len(seg_text)
            whisper_idx += 1
            
            ratio = acc_len / target_len if target_len > 0 else 1.0
            is_length_in_range = (0.99 <= ratio <= 1.01)
            
            is_content_match = False
            if is_length_in_range:
                matcher = SequenceMatcher(None, acc_text_buffer, truth_text)
                if matcher.ratio() > 0.55:
                    is_content_match = True
            
            is_overflow = (ratio > 1.01)

            if (is_length_in_range and is_content_match) or is_overflow:
                break
        
        group_start_indices.append(whisper_idx)

    for i in range(len(text_segments)):
        start_idx = group_start_indices[i]
        end_idx = group_start_indices[i+1]
        
        if start_idx < len(whisper_segments):
            t_start = whisper_segments[start_idx]['start']
        else:
            t_start = total_audio_duration 

        if i == len(text_segments) - 1:
            t_end = total_audio_duration
        else:
            if end_idx < len(whisper_segments):
                t_end = whisper_segments[end_idx]['start']
            else:
                t_end = total_audio_duration

        duration = max(2.0, t_end - t_start)
        log_queue.put(f"✅ [V8精准对齐] Group {i+1}: {duration:.2f}s")
        video_durations.append(duration)

    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. Please REWRITE it to be SAFER. REMOVE ALL references to children."
        else:
            system_instruction = "The prompt STILL failed. Please rewrite it to be EXTREMELY CONCISE (under 15 words)."
        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"Please generate prompts for the following {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 {YUNWU_API_KEY}"} 
        
    def compress_audio(self, input_path, log_queue):
        if os.path.getsize(input_path) < 24 * 1024 * 1024: return input_path
        log_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_path
        except: return input_path

    def 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_json
                time.sleep(5)
            except Exception as e: time.sleep(5)
        return None

class VideoAgent:
    def __init__(self, director_instance=None):
        self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}"} 
        self.director = director_instance
        
    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
        
        for rewrite_cycle in range(3):
            if rewrite_cycle > 0:
                try:
                    new_core = self.director.rewrite_failed_prompt(current_prompt_core, rewrite_cycle)
                    if new_core: current_prompt_core = new_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("..", ".")
            
            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); continue
                    
                    task_id = req.json().get("id")
                    if not task_id: continue
                    
                    log_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中...")
                    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_data = status_resp.json()
                            status = status_data.get("status")
                            if status == "completed":
                                video_url = status_data.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": break 
                            time.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)
        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:
        log_queue.put(f"❌ [Group {group_id}] 渲染失败: {e}")
        return False

def 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.5 纯净版生产线 (SRT Export)...")
    
    try:
        ac = AudioFileClip(audio_path)
        total_audio = ac.duration
        ac.close()
    except: return False

    # 1. 字幕数据处理 (用于导出 SRT)
    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'], log_queue)
        log_queue.put(f"📝 正在生成外挂字幕文件: {os.path.basename(srt_path)}")
        generate_srt_file(final_subtitle_data, srt_path)
    else:
        log_queue.put("⚠️ 无字幕数据,跳过 SRT 生成")

    # 2. 时长对齐计算
    if whisper_result and 'segments' in whisper_result:
        segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio, log_queue)
    else:
        segment_durations = estimate_durations_fallback(text_segments, total_audio)

    video_files = sorted(video_files)
    total_items = min(len(video_files), len(segment_durations))
    
    # 3. 原子化循环处理 (纯视频拉伸)
    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 = {}
        for cfg in group_configs:
            f = renderer.submit(
                render_atomic_group_final,
                cfg['id'], cfg['vid'], cfg['dur'], cfg['start'], 
                log_queue, cfg['out']
            )
            future_map[f] = cfg['id']
            
        for f in as_completed(future_map):
            if f.result(): completed_count += 1

    # 4. 物理拼接
    log_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:
        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)
        
        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)
        
        # 5. 打包 Zip (MP4 + SRT)
        log_queue.put("📦 正在打包成品 (视频 + SRT)...")
        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:
        log_queue.put(f"❌ 拼接失败: {e}")
        return False

def 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

def process_pipeline(full_text, audio_file, gen_system_prompt):
    if not full_text.strip(): yield "❌ 文案不能为空", None; return
    if not audio_file: yield "❌ 请上传音频文件", None; return
    
    timestamp_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:]), None
    
    yield update_ui("🚀 系统启动 (V8.5 Pure + SRT)...")
    
    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)
    
    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 = []
    for i in range(0, total_videos, VIDEOS_PER_BATCH):
        llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH])
    
    video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)
    video_futures = []
    
    yield update_ui(f"🧠 Prompt 生成与视频渲染并发中...")
    
    with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor:
        llm_future_map = {}
        for b_idx, batch in enumerate(llm_batches):
            f = llm_executor.submit(director.generate_batch_prompts, batch, gen_system_prompt)
            llm_future_map[f] = b_idx
            
        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:
                        vf = video_executor.submit(cameraman.worker_task, p_text, gid, log_queue, current_run_dir)
                        video_futures.append((gid, vf))
                yield update_ui(f"⚡ Batch {b_idx+1} Prompt OK")
            except: pass

    yield update_ui("⏳ 等待所有视频素材就绪...")
    
    video_paths = [None] * total_videos
    last_log_time = 0
    while True:
        has_new_log = False
        while not log_queue.empty():
            msg = log_queue.get()
            logs.append(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")
            has_new_log = True
        done_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: break
        time.sleep(0.5)
        
    for idx, f in video_futures:
        try: video_paths[idx] = f.result()
        except: pass
    
    valid_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 = None
    
    if len(valid_videos) > 0:
        # 最终输出改为 Zip 文件
        output_zip = os.path.join(current_run_dir, "Project_Package.zip")
        
        success = False
        with 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 = False
                while not log_queue.empty():
                    yield update_ui(log_queue.get())
                    flushed = True
                if 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("🎉🎉🎉 打包成功!请下载 ZIP 文件 (含视频和SRT)"), output_zip
        else:
            yield update_ui("⚠️ 合成部分失败,提供原始素材包"), create_zip_package(valid_videos, current_run_dir)
    else:
        yield update_ui("❌ 无视频生成"), None

# ================= UI =================

with gr.Blocks(title="Veo V8.5 Pure & SRT") as demo:
    gr.Markdown("## 🎬 Veo 全自动音画工厂 (V8.5 纯净版 + SRT)")
    gr.Markdown("🌟 **特性**:导出无字幕纯净视频 + 配套繁体SRT字幕文件 + 打包下载")
    
    with gr.Row():
        with gr.Column():
            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)
    
    btn.click(process_pipeline, [in_text, in_audio, system_p], [out_log, out_file])

if __name__ == "__main__":
    demo.queue().launch(server_name="0.0.0.0", inbrowser=True)