Spaces:
Runtime error

File size: 30,715 Bytes
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb52c6
 
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b87371b
 
 
21ade96
 
b87371b
21ade96
 
 
 
 
 
 
 
 
 
 
b87371b
21ade96
 
 
b87371b
 
 
21ade96
 
 
 
 
 
b87371b
 
 
 
21ade96
 
b87371b
 
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe5b91d
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb52c6
21ade96
0cb52c6
 
 
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe5b91d
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb52c6
21ade96
0cb52c6
21ade96
 
 
 
0cb52c6
 
21ade96
 
 
 
0cb52c6
21ade96
 
 
 
 
0cb52c6
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb52c6
21ade96
0cb52c6
21ade96
 
 
 
 
 
 
 
0cb52c6
21ade96
 
 
0cb52c6
 
 
 
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb52c6
21ade96
 
 
 
0cb52c6
21ade96
 
 
 
 
398813a
 
b87371b
 
 
 
 
 
 
 
 
 
 
 
21ade96
 
398813a
 
21ade96
398813a
 
21ade96
 
 
b87371b
398813a
 
 
21ade96
 
398813a
21ade96
b87371b
 
 
21ade96
398813a
21ade96
 
b87371b
398813a
 
 
21ade96
 
 
 
398813a
b87371b
 
 
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
b87371b
21ade96
 
 
398813a
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b87371b
21ade96
 
 
398813a
21ade96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b87371b
 
 
 
 
 
 
 
 
 
 
 
 
 
21ade96
 
398813a
 
21ade96
 
 
398813a
 
 
 
 
 
 
 
 
 
 
 
 
21ade96
 
 
 
 
 
398813a
21ade96
 
 
 
 
 
 
 
 
398813a
21ade96
398813a
b87371b
 
21ade96
 
 
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
import sys
import subprocess
import os
import shutil
import time
import json
import requests
import zipfile
import re
import threading
import glob
import traceback
import random
import math
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed

# ==========================================
# 0. 环境依赖自动检测与安装
# ==========================================
def ensure_dependencies():
    """启动前自检必要的Python库"""
    required_packages = ["gradio", "requests"]
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"📦 检测到缺失依赖: {', '.join(missing_packages)},正在自动修复...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install"] + missing_packages)
            print("✅ 依赖安装成功!环境已就绪。")
        except subprocess.CalledProcessError as e:
            print(f"❌ 依赖安装失败。请手动在终端运行: pip install {' '.join(missing_packages)}")
            print(f"错误详情: {e}")
    else:
        print("✅ 环境检查通过。")

ensure_dependencies()

import gradio as gr
import requests

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

# 1. 核心鉴权配置
API_KEY = "sk-vhrneE8MG8c3ADoIR8r3cI5QFoJpe8wVfN25u0hkYVqbQeIA"
BASE_URL = "https://yunwu.ai" 

# 2. 模型参数配置
TEXT_MODEL = "claude-opus-4-5-20251101-thinking"

# 3. 并发控制
MAX_CONCURRENT_TOPICS = 200 

# 4. 文件存储路径配置
if os.path.exists("/data"):
    ROOT_BASE = "/data"
else:
    ROOT_BASE = os.getcwd()

TASKS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_tasks_v14_final") 
CORPUS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_corpus_lib")        
PERSONAS_FILE = os.path.join(ROOT_BASE, "personas_config.json")        

os.makedirs(TASKS_ROOT_DIR, exist_ok=True)
os.makedirs(CORPUS_ROOT_DIR, exist_ok=True)

# ================= 1. 角色/提示词管理器 =================

class PersonaManager:
    def __init__(self, filepath=PERSONAS_FILE):
        self.filepath = filepath
        self.default_personas = {
            "01_默认角色_示例": {
                "system": "你是一个专业的文章撰写助手。",
                "user_template": "【任务】:请根据参考资料总结核心内容。\n【主题】:{topic}"
            }
        }
        # 启动时确保文件存在
        if not os.path.exists(self.filepath):
            self.save_personas(self.default_personas)

    def load_personas(self):
        """强制从硬盘读取,不使用内存缓存"""
        if not os.path.exists(self.filepath):
            return self.default_personas
        try:
            with open(self.filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
                return data if data else self.default_personas
        except Exception as e:
            print(f"⚠️ 配置文件读取失败: {e},使用默认值")
            return self.default_personas

    def save_personas(self, new_data):
        """保存并强制刷入磁盘"""
        try:
            with open(self.filepath, 'w', encoding='utf-8') as f:
                json.dump(new_data, f, indent=4, ensure_ascii=False)
                f.flush()
                os.fsync(f.fileno()) # 物理写入
            time.sleep(0.05) # 微小延迟确保系统文件锁释放
            return True
        except Exception as e:
            print(f"❌ 保存失败: {e}")
            return False

    def get_persona(self, name):
        data = self.load_personas()
        if name not in data and data:
            return list(data.values())[0]
        return data.get(name)

    def get_all_names(self):
        data = self.load_personas()
        return list(data.keys())

persona_manager = PersonaManager()

# ================= 2. 素材库管理 & 推荐算法 =================

def save_to_corpus(files):
    if not files: return list_corpus_files(), "⚠️ 未检测到文件,请重新上传"
    saved_count = 0
    error_count = 0
    for file in files:
        try:
            filename = os.path.basename(file.name)
            if not filename.lower().endswith('.txt'):
                error_count += 1
                continue
            dest_path = os.path.join(CORPUS_ROOT_DIR, filename)
            shutil.copy(file.name, dest_path)
            saved_count += 1
        except Exception as e:
            error_count += 1
    msg = f"✅ 成功入库: {saved_count} 篇"
    if error_count > 0: msg += f" (跳过 {error_count} 个非txt文件)"
    return list_corpus_files(), msg

def list_corpus_files():
    if not os.path.exists(CORPUS_ROOT_DIR): return []
    files = glob.glob(os.path.join(CORPUS_ROOT_DIR, "*.txt"))
    files.sort(key=os.path.getmtime, reverse=True)
    return files

def clear_corpus():
    try:
        shutil.rmtree(CORPUS_ROOT_DIR)
        os.makedirs(CORPUS_ROOT_DIR, exist_ok=True)
        return [], "🗑️ 素材库已全部清空"
    except Exception as e:
        return [], f"❌ 清空失败: {str(e)}"

# --- 核心算法:Jaccard 相似度匹配 ---
def jaccard_similarity(str1, str2):
    if not str1 or not str2: return 0
    set1 = set(str1)
    set2 = set(str2)
    intersection = len(set1.intersection(set2))
    union = len(set1.union(set2))
    return intersection / union if union > 0 else 0

def recommend_files(target_topic, top_k=6):
    files = list_corpus_files()
    if not files: return []
    
    all_filenames = [os.path.basename(f) for f in files]
    
    if not target_topic or not target_topic.strip():
        return all_filenames
    
    scored_files = []
    for f_path in files:
        try:
            f_name = os.path.basename(f_path)
            with open(f_path, 'r', encoding='utf-8') as f:
                content_preview = f.read(1000) 
            score_name = jaccard_similarity(target_topic, f_name)
            score_content = jaccard_similarity(target_topic, content_preview)
            final_score = (score_name * 0.7) + (score_content * 0.3)
            scored_files.append((final_score, f_name))
        except: continue
        
    scored_files.sort(key=lambda x: x[0], reverse=True)
    return [item[1] for item in scored_files[:top_k]]

def build_references_from_selection(selected_filenames):
    if not selected_filenames:
        return "", "未选择任何参考素材"
    
    context = ""
    log_names = []
    
    for idx, fname in enumerate(selected_filenames):
        f_path = os.path.join(CORPUS_ROOT_DIR, fname)
        if os.path.exists(f_path):
            try:
                log_names.append(fname)
                with open(f_path, 'r', encoding='utf-8') as f:
                    content = f.read(40000) # 限制单篇长度
                    context += f"=== 参考资料_{idx+1} ({fname}) ===\n{content}\n\n"
            except: pass
            
    return context, " + ".join(log_names)

# ================= 3. 任务与日志系统 =================

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, task_name_prefix="task", custom_label=None):
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        
        # 任务文件夹命名逻辑 - 【修复】如果输入了主题,直接作为ID前缀
        if custom_label:
            safe_label = re.sub(r'[\\/*?:"<>|]', "", custom_label)[:30] 
            # 将自定义标签放在前面,方便查找
            task_id = f"{safe_label}_{timestamp}"
        else:
            task_id = f"{task_name_prefix}_{timestamp}"
            
        task_dir = os.path.join(self.root_dir, task_id)
        os.makedirs(task_dir, exist_ok=True)
        self.update_status(task_id, "initializing", progress=0)
        return task_id, task_dir

    def log(self, task_id, message):
        timestamp = datetime.now().strftime('%H:%M:%S')
        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(f"[{timestamp}] {message}\n")
        except: pass

    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(), "result": result_path, "progress": progress }
        try:
            with open(status_path, "w", encoding="utf-8") as f: json.dump(data, f)
        except: pass

    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:
            if os.path.exists(os.path.join(task_dir, "log.txt")):
                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:
            if os.path.exists(os.path.join(task_dir, "status.json")):
                with open(os.path.join(task_dir, "status.json"), "r", encoding="utf-8") as f: status_data = json.load(f)
        except: pass
        return { "id": task_id, "log": log_content, "status": status_data.get("status"), "result": status_data.get("result") }

    def list_tasks(self):
        if not os.path.exists(self.root_dir): return []
        tasks = [d for d in os.listdir(self.root_dir) if os.path.isdir(os.path.join(self.root_dir, 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()

# ================= 4. LLM 通信 =================

class TextGenerator:
    def __init__(self, api_key=API_KEY):
        self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" }
        self.base_url = BASE_URL.rstrip('/')
        if not self.base_url.endswith('/v1'): self.base_url += '/v1'

    def call_llm(self, system_prompt, user_prompt, temperature=0.7):
        url = f"{self.base_url}/chat/completions"
        payload = {
            "model": TEXT_MODEL,
            "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ],
            "stream": False, 
            "temperature": temperature, 
            "max_tokens": 64000 
        }
        
        max_retries = 4
        for attempt in range(max_retries):
            try:
                # 超时时间调整为 500s 
                resp = requests.post(url, headers=self.headers, json=payload, timeout=500)
                
                if resp.status_code == 200:
                    data = resp.json()
                    if "choices" in data and len(data["choices"]) > 0:
                        return data["choices"][0]["message"]["content"]
                    else: return f"Error: 数据结构异常: {data}"
                else:
                    print(f"⚠️ API Warning: {resp.status_code} - {resp.text}")
                    time.sleep(3 + attempt * 2)
            except Exception as e:
                print(f"Network Error: {e}")
                time.sleep(3)
        return "Error: LLM调用失败"

# ================= 5. TTS清洗与分段处理逻辑 =================

def clean_text_for_tts(text):
    if not text: return ""
    text = re.sub(r"[\*\#\-\>\[\]\=\`\~]", "", text)
    text = re.sub(r"(.*?)", "", text)
    text = re.sub(r"\(.*?\)", "", text)
    text = re.sub(r"【.*?】", "", text)
    text = re.sub(r"\[.*?\]", "", text)
    text = re.sub(r"第[一二三四五六七八九十0-9]+[章节部分].*?\n", "", text)
    text = text.replace(",", ",").replace("?", "?").replace("!", "!").replace(";", ";").replace(":", ":")
    lines = [line.strip() for line in text.split('\n') if line.strip()]
    return "\n".join(lines)

def process_single_topic(idx, topic, persona_name, custom_sys, custom_user, ref_context, ref_log_name, task_dir, generator, logger_func):
    logger_func(f"🚀 [No.{idx+1}] 启动: {topic if topic else '无主题模式'}")
    
    sys_prompt = ""
    user_tpl = ""
    
    if custom_sys and custom_sys.strip():
        sys_prompt = custom_sys
    else:
        persona = persona_manager.get_persona(persona_name)
        sys_prompt = persona.get("system", "")
        
    if custom_user and custom_user.strip():
        user_tpl = custom_user
    else:
        persona = persona_manager.get_persona(persona_name)
        user_tpl = persona.get("user_template", "")

    SEGMENT_BORDER = "==========SEGMENT_BORDER=========="
    
    mandatory_instruction = f"""
    
    【⚠️ 核心输出格式要求 - 必须严格遵守 ⚠️】
    你必须输出三部分内容,并使用特定分隔符分开。
    
    第一部分:【标题】
    (如果有提供主题,请使用主题;如果没有,请仿照参考素材风格自拟爆款标题)
    
    {SEGMENT_BORDER}
    
    第二部分:【YouTube视频描述】
    1. 必须详细,符合YouTube SEO,包含关键词,激发点击欲望。
    2. ❌ 严禁包含时间轴(如 00:00 开头),因为语速未知。
    3. ✅ 必须包含 Hashtags(以#开头,例如 #芒格 #投资),放在描述最后。
    
    {SEGMENT_BORDER}
    
    第三部分:【口播正文】
    1. ⚠️ 字数生死状:必须极度详尽,目标 **9000字至10000字**。不到9000字视为任务失败!
    2. 扩写策略:请把每一个观点都当成一篇小论文来写,大量引用案例、数据、细节描写、反复论证。不要概括,要展开!
    3. 格式:只输出正文内容,不要包含 Markdown 标题符号(如 # ##),方便TTS。
    """
    
    final_user_prompt = user_tpl + mandatory_instruction
    
    if topic:
        if "{topic}" in final_user_prompt:
            final_user_prompt = final_user_prompt.replace("{topic}", topic)
        else:
            final_user_prompt += f"\n\n=== 核心任务主题 ===\n{topic}"
    else:
        if "{topic}" in final_user_prompt:
             final_user_prompt = final_user_prompt.replace("{topic}", "(未指定,请自拟)")
        else:
             final_user_prompt += "\n\n=== 核心任务主题 ===\n(用户未指定主题,请自拟)"

    if "{references}" in final_user_prompt:
        final_user_prompt = final_user_prompt.replace("{references}", ref_context)
    else:
        if ref_context:
            final_user_prompt += f"\n\n=== 必读参考资料 ===\n{ref_context}"
    
    logger_func(f"✍️ AI正在创作 (目标: 1万字, 请耐心等待3-5分钟)...")
    raw_text = generator.call_llm(sys_prompt, final_user_prompt)
    
    if "Error" in raw_text:
        logger_func(f"❌ 生成失败: {raw_text}")
        return None, None
    
    parts = raw_text.split(SEGMENT_BORDER)
    title_part = "未提取到标题"
    desc_part = "未提取到描述"
    body_part = raw_text 
    
    if len(parts) >= 3:
        title_part = parts[0].strip().replace("第一部分:", "").replace("【标题】", "").strip()
        desc_part = parts[1].strip().replace("第二部分:", "").replace("【YouTube视频描述】", "").strip()
        body_part = parts[2].strip().replace("第三部分:", "").replace("【口播正文】", "").strip()
    else:
        logger_func("⚠️ 警告:AI未严格遵守分割符,正在尝试降级处理...")
    
    cleaned_tts_body = clean_text_for_tts(body_part)
    
    if topic:
        base_filename = topic
    else:
        base_filename = title_part.split('\n')[0][:20] if len(title_part) > 1 else f"Untitled_{datetime.now().strftime('%H%M%S')}"

    safe_filename = re.sub(r'[\\/*?:"<>|]', "", base_filename)[:30]
    res_dir = os.path.join(task_dir, "results")
    os.makedirs(res_dir, exist_ok=True)
    
    generated_files = []
    
    # 【修复】文件1:标题+视频详情 (Meta)
    meta_content = f"【标题】\n{title_part}\n\n【YouTube视频描述】\n{desc_part}"
    meta_path = os.path.join(res_dir, f"{idx+1}_{safe_filename}_标题与详情.txt")
    with open(meta_path, "w", encoding="utf-8") as f:
        f.write(meta_content)
    generated_files.append(meta_path)
    
    # 【修复】文件2:正文 (TTS)
    tts_path = os.path.join(res_dir, f"{idx+1}_{safe_filename}_正文(TTS).txt")
    with open(tts_path, "w", encoding="utf-8") as f:
        f.write(cleaned_tts_body)
    generated_files.append(tts_path)
    
    # Debug文件(可选)
    debug_path = os.path.join(res_dir, f"{idx+1}_debug.log")
    with open(debug_path, "w", encoding="utf-8") as f:
        f.write(f"PROMPT:\n{final_user_prompt}")
        
    logger_func(f"✅ 完成!正文约 {len(cleaned_tts_body)} 字")
    # 返回生成的文件列表和自动提取的标题
    return generated_files, title_part.split('\n')[0]

def worker(task_id, topics, persona_name, custom_sys, custom_user, selected_refs, manual_topic_name):
    """后台工作线程"""
    task_dir = os.path.join(task_manager.root_dir, task_id)
    def log(m): task_manager.log(task_id, m)
    
    try:
        task_manager.update_status(task_id, "running")
        gen = TextGenerator()
        
        ref_context, ref_log_name = build_references_from_selection(selected_refs)
        
        all_files_to_zip = []
        first_auto_title = None 
        
        with ThreadPoolExecutor(max_workers=MAX_CONCURRENT_TOPICS) as executor:
            futures = []
            for idx, topic in enumerate(topics):
                if not topic.strip() and not selected_refs: continue 
                
                futures.append(
                    executor.submit(
                        process_single_topic, 
                        idx, topic.strip(), 
                        persona_name, custom_sys, custom_user,
                        ref_context, ref_log_name, 
                        task_dir, gen, log
                    )
                )
            
            for f in as_completed(futures):
                try:
                    res_files, auto_title = f.result()
                    if res_files: 
                        all_files_to_zip.extend(res_files)
                        if not first_auto_title and auto_title:
                            first_auto_title = auto_title
                except Exception as e:
                    log(f"Error: {e}")
                    traceback.print_exc()
        
        if all_files_to_zip:
            # 【修复】Zip文件命名逻辑:优先使用手动输入的主题
            if manual_topic_name:
                safe_zip_name = re.sub(r'[\\/*?:"<>|]', "", manual_topic_name)[:50]
                zip_filename = f"{safe_zip_name}.zip"
            elif first_auto_title:
                safe_zip_name = re.sub(r'[\\/*?:"<>|]', "", first_auto_title)[:30]
                zip_filename = f"{safe_zip_name}.zip"
            else:
                zip_filename = f"Batch_{len(all_files_to_zip)}_Files.zip"
                
            zip_path = os.path.join(task_dir, zip_filename)
            
            with zipfile.ZipFile(zip_path, 'w') as z:
                for f in all_files_to_zip: z.write(f, os.path.basename(f))
            
            # 【修复】确保传给前端的是绝对路径,解决下载失败问题
            abs_zip_path = os.path.abspath(zip_path)
            
            task_manager.update_status(task_id, "completed", abs_zip_path)
            log(f"🎉 任务结束,ZIP已打包: {zip_filename}")
        else:
            task_manager.update_status(task_id, "failed")
            log("❌ 未生成有效文件。")
            
    except Exception as e:
        log(f"Fatal Error: {e}")
        task_manager.update_status(task_id, "error")

# ================= 7. UI 交互逻辑 =================

def analyze_matches(topic_text):
    first_topic = topic_text.split('\n')[0].strip()
    rec_files = recommend_files(first_topic, top_k=6)
    
    if not rec_files:
        return gr.CheckboxGroup(choices=[], value=[]), "⚠️ 库中无文件", []
    
    if not first_topic:
        msg = f"✅ 无主题模式:已列出库中全部 {len(rec_files)} 篇素材"
    else:
        msg = f"✅ 智能匹配:已推荐 {len(rec_files)} 篇最相关素材"
        
    return gr.CheckboxGroup(choices=rec_files, value=rec_files), msg, rec_files

def toggle_select_all(current_selected, all_available):
    if not all_available: return []
    if len(current_selected) == len(all_available): return []
    return all_available

def start_execution(topic_text, persona_name, p_sys, p_user, selected_refs):
    if not topic_text.strip() and not selected_refs:
        return "❌ 既无主题也无素材,无法生成", None
        
    topics = topic_text.split('\n')
    # 【修复】确保明确提取第一个主题作为任务名
    manual_topic_name = topics[0].strip() if topic_text.strip() else None
    
    if not topic_text.strip(): topics = [""]
    
    # 传递 manual_topic_name 给 create_task
    tid, _ = task_manager.create_task(custom_label=manual_topic_name)
    
    threading.Thread(target=worker, args=(tid, topics, persona_name, p_sys, p_user, selected_refs, manual_topic_name)).start()
    return f"任务已启动: {tid}", tid

# --- UI Helper (核心修复部分) ---

def global_refresh_dropdowns(target_value=None):
    """
    通用刷新函数:强制从硬盘读取最新列表,并生成两个gr.update对象。
    """
    all_names = persona_manager.get_all_names()
    
    # 确定选中的值:如果指定值在列表里,就选它;否则选第一个;如果列表为空,则None
    final_val = target_value if (target_value and target_value in all_names) else (all_names[0] if all_names else None)
    
    # 返回两个更新指令,分别对应 Tab1 和 Tab2 的下拉框
    # 注意:使用 gr.update(choices=..., value=...) 是解决不同步的终极方案
    return gr.update(choices=all_names, value=final_val), gr.update(choices=all_names, value=final_val)

def on_select_persona_config(name):
    if not name:
        return "", ""
    p = persona_manager.get_persona(name)
    if not p:
        return "", ""
    return p.get("system"), p.get("user_template")

def save_new_persona(name, sys, user):
    """保存角色并原子化更新两个下拉框"""
    if not name: 
        return "❌ 名字不能为空", gr.update(), gr.update()
    
    current = persona_manager.load_personas()
    current[name] = {"system": sys, "user_template": user}
    
    if persona_manager.save_personas(current):
        # 保存成功后,直接调用通用刷新函数,选中新创建的角色
        u1, u2 = global_refresh_dropdowns(target_value=name)
        return f"✅ 角色 '{name}' 已保存", u1, u2
    else:
        return f"❌ 保存失败", gr.update(), gr.update()

def delete_persona(name):
    """删除角色并原子化更新两个下拉框"""
    if not name: 
        return "❌ 未选择", gr.update(), gr.update()
    
    current = persona_manager.load_personas()
    if name in current:
        del current[name]
        persona_manager.save_personas(current)
    
    # 删除后,刷新列表,默认选中第一个
    u1, u2 = global_refresh_dropdowns(target_value=None)
    return f"🗑️ 已删除", u1, u2

# --- 界面布局 ---

with gr.Blocks(title="AI 灵活内容工厂 (V14 Final)") as demo:
    gr.Markdown("## 🧞‍♂️ AI 灵活内容工厂 (V14 自动刷新修复版)")
    gr.Markdown("支持:**自动刷新监控** | **强制三段式输出** | **9000+字锁定**")
    
    state_all_files = gr.State([])
    
    # 关键:添加自动刷新定时器
    timer = gr.Timer(2)

    with gr.Tabs():
        # --- Tab 1: 创作中心 ---
        with gr.Tab("🚀 1. 创作中心") as tab_create:
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### 配置与启动")
                    # 给组件定义变量名,方便后续更新
                    persona_select = gr.Dropdown(label="加载预设角色 (选填)", choices=persona_manager.get_all_names(), interactive=True)
                    topic_input = gr.Textbox(label="输入主题 (一行一个)", lines=3, placeholder="留空则自动拟题...")
                    
                with gr.Column(scale=1):
                    gr.Markdown("### 素材选择")
                    with gr.Row():
                        analyze_btn = gr.Button("🔍 分析素材", variant="secondary")
                        select_all_btn = gr.Button("✅ 全选/反选", variant="secondary")
                    analyze_status = gr.Label(show_label=False)
                    ref_checkboxes = gr.CheckboxGroup(label="参考文案列表", choices=[], interactive=True)
            
            gr.Markdown("---")
            start_btn = gr.Button("🔥 立即执行 (自动分离文案与描述)", variant="primary")
            start_msg = gr.Label(show_label=False)

        # --- Tab 2: 角色配置 ---
        with gr.Tab("🎭 2. 角色配置") as tab_config:
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### 角色管理")
                    # 这里定义变量名
                    p_config_select = gr.Dropdown(label="选择角色编辑", choices=persona_manager.get_all_names(), interactive=True)
                    p_name_input = gr.Textbox(label="新建/重命名", placeholder="角色名")
                    p_save_btn = gr.Button("💾 保存/新建", variant="primary")
                    p_del_btn = gr.Button("🗑️ 删除", variant="stop")
                    p_status = gr.Label(show_label=False)
                
                with gr.Column(scale=2):
                    gr.Markdown("### 提示词编辑 (所见即所得)")
                    p_sys_input = gr.Textbox(label="System Prompt", lines=3)
                    p_user_input = gr.Textbox(label="User Template", lines=10)
                    gr.Markdown("✅ **点击[保存]后永久生效,点击[立即执行]直接使用当前文本。**")

        # --- Tab 3: 素材库 ---
        with gr.Tab("📚 3. 素材库"):
            with gr.Row():
                with gr.Column():
                    files = gr.File(label="上传素材 (txt)", file_count="multiple")
                    upload_btn = gr.Button("☁️ 确认入库")
                    upload_res = gr.Label()
                with gr.Column():
                    corpus_display = gr.File(label="库中文件", interactive=False)
                    clear_btn = gr.Button("🗑️ 清空")

        # --- Tab 4: 监控 ---
        with gr.Tab("📺 4. 监控"):
            refresh_task = gr.Button("🔄 刷新")
            task_dd = gr.Dropdown(label="任务记录")
            log_box = gr.Textbox(label="日志", lines=20)
            result_dl = gr.File(label="下载Zip")

    # --- 事件绑定 ---
    
    start_btn.click(
        start_execution, 
        [topic_input, persona_select, p_sys_input, p_user_input, ref_checkboxes], 
        [start_msg, gr.State()]
    ).then(
        lambda: gr.Dropdown(choices=task_manager.list_tasks(), value=task_manager.list_tasks()[0] if task_manager.list_tasks() else None), 
        outputs=task_dd
    )
    
    # ================= 核心修复逻辑:Tab 切换自动刷新 =================
    # 原理:只要用户点击 Tab 1 或 Tab 2,就强制刷新该页面下的下拉框
    # 这确保了即使按钮更新失败,切换一下页面也能立刻修复
    
    def tab_refresh_handler():
        u1, u2 = global_refresh_dropdowns()
        return u1 # 返回给当前Tab的组件
    
    # 绑定 Tab 选中事件 (Gradio 4.x+)
    tab_create.select(fn=lambda: global_refresh_dropdowns()[0], inputs=None, outputs=persona_select)
    tab_config.select(fn=lambda: global_refresh_dropdowns()[1], inputs=None, outputs=p_config_select)

    # =============================================================
    
    # 角色配置联动
    persona_select.select(on_select_persona_config, persona_select, [p_sys_input, p_user_input])
    
    # 关键逻辑:选择角色配置时,自动填充名字输入框
    p_config_select.select(on_select_persona_config, p_config_select, [p_sys_input, p_user_input])
    p_config_select.select(lambda x: x, p_config_select, p_name_input)
    
    # 核心修复:保存按钮同时更新两个下拉框,并设置Value,防止报错
    p_save_btn.click(
        save_new_persona, 
        inputs=[p_name_input, p_sys_input, p_user_input], 
        outputs=[p_status, persona_select, p_config_select] # 同时指向 Tab1 和 Tab2 的下拉框
    )
    
    # 核心修复:删除按钮同时更新两个下拉框
    p_del_btn.click(
        delete_persona, 
        inputs=p_config_select, 
        outputs=[p_status, persona_select, p_config_select]
    )
    
    analyze_btn.click(analyze_matches, topic_input, [ref_checkboxes, analyze_status, state_all_files])
    select_all_btn.click(toggle_select_all, inputs=[ref_checkboxes, state_all_files], outputs=ref_checkboxes)
    upload_btn.click(save_to_corpus, files, [corpus_display, upload_res])
    clear_btn.click(clear_corpus, outputs=[corpus_display, upload_res])
    
    # 自动刷新逻辑
    timer.tick(
        lambda tid: (task_manager.get_task_info(tid)["log"], task_manager.get_task_info(tid)["result"]) if tid else ("", None), 
        inputs=task_dd, 
        outputs=[log_box, result_dl]
    )
    
    refresh_task.click(lambda: gr.Dropdown(choices=task_manager.list_tasks(), value=task_manager.list_tasks()[0] if task_manager.list_tasks() else None), outputs=task_dd)
    task_dd.change(lambda tid: (task_manager.get_task_info(tid)["log"], task_manager.get_task_info(tid)["result"]) if tid else ("", None), task_dd, [log_box, result_dl])
    
    # 初始加载
    demo.load(list_corpus_files, outputs=corpus_display)
    # 初始化时确保两个下拉框都有值
    demo.load(lambda: global_refresh_dropdowns()[0], outputs=persona_select)
    demo.load(lambda: global_refresh_dropdowns()[1], outputs=p_config_select)

if __name__ == "__main__":
    demo.queue().launch()