Spaces:
Sleeping

File size: 37,174 Bytes
ea829c2
 
4ff7ac7
ea829c2
4ff7ac7
 
 
 
ea829c2
f8942fc
 
 
640f1c4
8e6ef06
4ff7ac7
 
ea829c2
 
abdd826
ea829c2
640f1c4
abdd826
 
 
 
640f1c4
 
 
 
 
 
 
 
 
 
 
 
abdd826
640f1c4
 
 
 
8e6ef06
640f1c4
 
ea829c2
abdd826
640f1c4
ea829c2
abdd826
ea829c2
640f1c4
4ff7ac7
 
 
640f1c4
 
abdd826
 
 
 
640f1c4
 
 
 
 
abdd826
640f1c4
 
8e6ef06
640f1c4
 
 
 
 
abdd826
 
 
640f1c4
abdd826
640f1c4
 
 
abdd826
640f1c4
abdd826
f315035
abdd826
 
f315035
abdd826
640f1c4
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15b354a
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640f1c4
abdd826
640f1c4
abdd826
 
640f1c4
abdd826
 
ea829c2
640f1c4
abdd826
 
 
 
 
 
640f1c4
abdd826
 
640f1c4
abdd826
 
ea829c2
640f1c4
abdd826
 
640f1c4
 
abdd826
640f1c4
 
abdd826
 
 
640f1c4
abdd826
640f1c4
abdd826
640f1c4
 
abdd826
 
 
 
 
 
 
640f1c4
8e6ef06
abdd826
640f1c4
 
abdd826
8e6ef06
abdd826
 
8e6ef06
 
 
abdd826
 
8e6ef06
abdd826
 
8e6ef06
640f1c4
8e6ef06
abdd826
8e6ef06
abdd826
8e6ef06
abdd826
 
 
8e6ef06
640f1c4
 
abdd826
 
 
 
 
 
 
 
640f1c4
abdd826
 
640f1c4
abdd826
640f1c4
 
 
abdd826
 
 
ea829c2
640f1c4
 
abdd826
ea829c2
8e6ef06
 
abdd826
8e6ef06
abdd826
 
 
 
8e6ef06
abdd826
8e6ef06
 
abdd826
8e6ef06
 
abdd826
 
 
 
640f1c4
abdd826
 
 
 
 
640f1c4
ea829c2
abdd826
 
 
b9b258b
8e6ef06
abdd826
640f1c4
 
8e6ef06
abdd826
 
8e6ef06
 
abdd826
 
8e6ef06
 
abdd826
 
8e6ef06
abdd826
 
 
 
 
640f1c4
abdd826
8e6ef06
ea829c2
abdd826
 
ea09d82
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ff7ac7
abdd826
f8942fc
 
abdd826
 
 
 
f8942fc
 
 
 
abdd826
 
8e6ef06
abdd826
8e6ef06
 
abdd826
 
8e6ef06
 
 
 
abdd826
8e6ef06
 
 
 
 
 
f8942fc
8e6ef06
abdd826
8e6ef06
abdd826
 
 
 
 
 
f8942fc
abdd826
 
f8942fc
 
8e6ef06
abdd826
8e6ef06
 
abdd826
 
8e6ef06
f8942fc
abdd826
 
 
 
 
 
 
8e6ef06
 
abdd826
 
 
 
 
 
 
 
 
 
 
 
f8942fc
 
abdd826
f8942fc
640f1c4
f8942fc
 
 
8e6ef06
abdd826
8e6ef06
 
 
 
 
 
f8942fc
 
 
abdd826
f8942fc
640f1c4
abdd826
 
 
 
640f1c4
abdd826
 
 
 
640f1c4
abdd826
 
640f1c4
abdd826
 
 
 
 
640f1c4
abdd826
 
640f1c4
 
abdd826
 
 
 
 
 
 
640f1c4
ea09d82
abdd826
ea09d82
8e6ef06
640f1c4
abdd826
 
 
640f1c4
abdd826
 
 
 
 
 
 
 
 
 
ea09d82
abdd826
 
 
 
 
 
640f1c4
abdd826
8e6ef06
abdd826
 
8e6ef06
abdd826
b23cc85
abdd826
b23cc85
abdd826
 
 
 
b23cc85
8e6ef06
abdd826
 
8e6ef06
abdd826
 
 
 
 
 
 
 
8e6ef06
abdd826
 
8e6ef06
abdd826
 
 
 
 
 
 
 
 
8e6ef06
 
640f1c4
abdd826
 
 
ea09d82
abdd826
 
ea09d82
abdd826
640f1c4
abdd826
 
640f1c4
abdd826
 
 
b9b258b
abdd826
 
 
 
 
15b354a
abdd826
 
 
 
 
 
640f1c4
abdd826
 
 
 
 
 
 
8e6ef06
abdd826
 
 
8e6ef06
abdd826
 
8e6ef06
abdd826
 
 
 
 
 
640f1c4
abdd826
 
 
 
 
 
 
 
 
 
 
 
b23cc85
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b23cc85
abdd826
 
 
 
 
 
 
 
640f1c4
 
 
b23cc85
abdd826
 
 
 
 
b23cc85
 
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b23cc85
abdd826
640f1c4
abdd826
 
 
 
640f1c4
abdd826
 
640f1c4
 
abdd826
640f1c4
ea09d82
abdd826
 
 
 
 
 
 
ea09d82
abdd826
 
b23cc85
640f1c4
 
 
abdd826
 
ea09d82
abdd826
ea09d82
 
abdd826
 
f8942fc
abdd826
 
f8942fc
abdd826
640f1c4
8e6ef06
abdd826
 
 
 
 
 
 
 
 
b23cc85
abdd826
 
f8942fc
abdd826
f8942fc
ea09d82
ea829c2
abdd826
f8942fc
4ff7ac7
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f315035
abdd826
640f1c4
8e6ef06
abdd826
 
 
 
c506d87
f8942fc
abdd826
 
f8942fc
abdd826
 
 
 
 
 
 
 
640f1c4
abdd826
 
640f1c4
 
abdd826
 
 
 
 
 
 
 
 
640f1c4
abdd826
 
 
 
 
 
 
 
ea09d82
abdd826
 
 
 
 
640f1c4
abdd826
 
 
640f1c4
abdd826
 
 
 
 
 
 
f8942fc
abdd826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ff7ac7
 
abdd826
640f1c4
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
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:
            # 使用 sys.executable 确保安装到当前 Python 环境
            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"

# ⚠️ 根据你的文档,接口表现为 OpenAI 格式
# 如果你的服务商地址是 https://yunwu.ai/v1/chat/completions,这里填 https://yunwu.ai
BASE_URL = "https://yunwu.ai"

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

# 3. 并发控制
# 建议保持低并发以保证质量
MAX_CONCURRENT_TOPICS = 2 

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

TASKS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_tasks_heavy_v5") # 任务存储
CORPUS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_corpus_lib")      # 素材库
PROMPTS_FILE = os.path.join(ROOT_BASE, "prompts.json")                # 提示词持久化文件

# 启动时自动创建必要目录
os.makedirs(TASKS_ROOT_DIR, exist_ok=True)
os.makedirs(CORPUS_ROOT_DIR, exist_ok=True)

# ================= 1. 提示词管理器 (Prompt Manager) =================

class PromptManager:
    """
    负责提示词的加载、保存和获取。
    实现了将提示词从代码中解耦,并在 UI 中可配置。
    """
    def __init__(self, filepath=PROMPTS_FILE):
        self.filepath = filepath
        self.default_prompts = {
            "logic_sys": """你是一个冷酷的逻辑拆解机器。
你的任务是分析文本的【结构】,而不是【内容】。
不要加入你的任何主观判断。""",
            
            "logic_user_template": """请阅读以下 4 篇参考文案:
{ref_content}

【任务】:
提取这 4 篇文案共有的**底层逻辑骨架 (Skeleton)**。

请回答以下问题来构建骨架:
1. 它们是如何开头的?(例如:是先骂人?还是先讲故事?还是先恐吓?)
2. 它们中间是如何论证的?(例如:第几段开始引用古籍?第几段开始讲物理磁场?)
3. 它们是如何结尾的?(例如:是讲因果?还是卖关子?)

请输出一个【通用爆款逻辑模板】。""",

            "outline_sys": """你是一个严格的执行者。
你需要将新主题填入给定的逻辑模板中。
严禁修改模板的逻辑顺序。""",

            "outline_user_template": """【新主题】:{topic}
【逻辑模板】:
{logic_template}

【强制要求 - 照葫芦画瓢】:
请严格按照模板的节奏,设计一个 **12个章节** 的详细大纲。
不要发挥你的创意,只做**填空题**。""",

            "seg_sys": """你就是**倪海厦**本人的数字分身。
你现在就在镜头前,给这群45-70岁的海外华人讲课、直播。

【🚨 数字人人设高压线 - 违反即死】:
1. **必须用第一人称“我”**。
2. **绝对禁止**出现“倪海厦老师生前”、“倪师曾经说过”这种第三人称描述!
3. **绝对禁止**出现“去世”、“生前”、“纪念”等词汇!因为你现在就活生生地在讲课!
4. **绝对禁止**AI味(如“接下来我们探讨”),要用口语(“听我一句劝”、“诸位老友”)。
5. **不要**添加舞台动作。
6. **不要**试图从你的数据库里补充不相关的信息,只准用原文的逻辑风格。

【🚨 模仿指令 - 照葫芦画瓢】:
请参考以下原文的**讲课/骂人方式、说理逻辑**:
{ref_snippet}

【⚠️ 输出格式核心要求】:
1. **必须保留标点符号!** 请务必使用逗号、句号、问号、感叹号来控制语速和节奏。没有标点TTS无法朗读!
2. **禁止使用Markdown**(如**加粗**、# 标题),只输出纯文本。
3. **禁止包含任何注释**、旁白、或者“以下是生成的文案”之类的废话。
4. 直接开始讲课内容。""",

            "seg_user_template": """当前主题:【{topic}】
当前章节:{chapter_range}

【本段大纲】:
{outline}

【写作指令】:
请将这几章内容扩写。
**字数目标:本段落请写满 2000 字,禁止超过2200字!**

请像参考原文那样,把每一个道理都掰开了、揉碎了讲。
如果原文喜欢引用《黄帝内经》,你也必须引用。

【输出结构】:
第一部分:【TTS纯净逐字稿(带标点)】
@@@分隔符@@@
第二部分:【模仿痕迹说明】""",

            # --- 新增功能:视频描述提示词 ---
            "meta_sys": """你是一个专业的YouTube运营专家。
你需要为刚刚生成的长视频文案写发布信息,目的是吸引点击和符合SEO。""",
            
            "meta_user_template": """【任务】:请根据以下主题和大纲,为这个长视频写一套YouTube发布文案。

【主题】:{topic}
【大纲】:
{outline}

【输出要求】:
1. **标题**:起3个极具吸引力的爆款标题。
2. **描述**:写一段详细的视频描述(Description),包含关键词,激发好奇心。
3. **Hashtags**:提供 10-15 个相关的标签(#)。

【⚠️ 禁止事项】:
- 不要包含时间轴(00:00),因为不知道最终语速。
- 不要包含Markdown标题符号。

请按以下格式输出:
【推荐标题】
...
【视频描述】
...
【标签】
..."""
        }
        self.prompts = self.load_prompts()

    def load_prompts(self):
        """加载提示词,如果文件不存在则使用默认值并创建"""
        if not os.path.exists(self.filepath):
            self.save_prompts(self.default_prompts)
            return self.default_prompts
        try:
            with open(self.filepath, 'r', encoding='utf-8') as f:
                saved = json.load(f)
                # 合并默认值,防止旧文件缺少新key
                for k, v in self.default_prompts.items():
                    if k not in saved:
                        saved[k] = v
                return saved
        except Exception as e:
            print(f"⚠️ 提示词文件读取失败: {e},使用默认值")
            return self.default_prompts

    def save_prompts(self, new_prompts):
        """保存提示词到文件"""
        try:
            with open(self.filepath, 'w', encoding='utf-8') as f:
                json.dump(new_prompts, f, indent=4, ensure_ascii=False)
            self.prompts = new_prompts
            return True
        except Exception as e:
            print(f"❌ 提示词保存失败: {e}")
            return False

    def get(self, key):
        """获取指定 Key 的提示词"""
        return self.prompts.get(key, self.default_prompts.get(key, ""))

prompt_manager = PromptManager()

# ================= 2. 素材库管理 & 智能匹配算法 (完整找回) =================

def save_to_corpus(files):
    """
    将用户上传的文件保存到素材库中。
    会过滤非 txt 文件,并统计成功入库的数量。
    """
    if not files: 
        return list_corpus_files(), "⚠️ 未检测到文件,请重新上传"
    
    saved_count = 0
    error_count = 0
    
    for file in files:
        try:
            # 获取文件名
            filename = os.path.basename(file.name)
            
            # 严格过滤:只允许 .txt
            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:
            print(f"文件保存异常: {str(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():
    """
    列出素材库中所有的 .txt 文件。
    按照修改时间倒序排列,确保最新的素材显示在最前面。
    """
    if not os.path.exists(CORPUS_ROOT_DIR): 
        return []
        
    # 获取所有 txt 文件路径
    files = glob.glob(os.path.join(CORPUS_ROOT_DIR, "*.txt"))
    
    # 按修改时间排序 (reverse=True 表示倒序)
    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):
    """
    计算两个字符串的 Jaccard 相似度系数。
    原理:交集大小 / 并集大小。
    """
    if not str1 or not str2: return 0
    
    set1 = set(str1)
    set2 = set(str2)
    
    intersection = len(set1.intersection(set2))
    union = len(set1.union(set2))
    
    if union == 0:
        return 0
    return intersection / union

def get_smart_references(target_topic, top_k=4):
    """
    【智能选材系统 - 完整版】
    从素材库中,根据目标标题,自动计算并挑出最匹配的 top_k 篇文案。
    """
    files = list_corpus_files()
    
    # 如果素材库为空,返回错误
    if not files: 
        return "", "❌ 错误:素材库为空,无法进行智能匹配。"
    
    scored_files = []
    
    for f_path in files:
        try:
            f_name = os.path.basename(f_path)
            
            # 读取前 1000 个字用于快速匹配
            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_path))
        except Exception as e:
            print(f"读取文件 {f_path} 失败: {e}")
            continue
        
    # 按分数从高到低排序
    scored_files.sort(key=lambda x: x[0], reverse=True)
    
    # 截取前 K 个
    selected_files = scored_files[:top_k]
    
    # 构建给 LLM 的上下文
    reference_context = ""
    log_info = []
    
    for idx, (score, f_path) in enumerate(selected_files):
        fname = os.path.basename(f_path)
        log_info.append(f"【{idx+1}】{fname} (匹配度:{score:.2f})")
        
        try:
            # 读取更长的篇幅 (3500字) 以供 AI 深度学习其逻辑
            with open(f_path, 'r', encoding='utf-8') as f:
                full_c = f.read(3500) 
                reference_context += f"=== 核心参照文案_{idx+1} ({fname}) ===\n{full_c}\n\n"
        except: pass
        
    log_str = " | ".join(log_info)
    return reference_context, log_str

# ================= 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="batch"):
        """创建任务目录,返回 TaskID"""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        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):
        """追加日志到 log.txt"""
        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.json"""
        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:
            log_path = os.path.join(task_dir, "log.txt")
            if os.path.exists(log_path):
                with open(log_path, "r", encoding="utf-8") as f:
                    log_content = f.read()
        except: log_content = "日志读取中..."
        
        # 读取状态
        status_data = {}
        try:
            status_path = os.path.join(task_dir, "status.json")
            if os.path.exists(status_path):
                with open(status_path, "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):
        """列出所有任务ID"""
        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 通信模块 (OpenAI 协议兼容修复版) =================

class TextGenerator:
    """
    负责与 LLM API 进行通信的类。
    【重要修复】:完全适配 OpenAI 格式的 Response 文档 (choices -> message -> content)。
    """
    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.85):
        """
        调用 LLM 接口。使用 OpenAI 标准的 Chat Completion 格式。
        """
        # ⚠️ 根据文档,Endpoint 必须是 /chat/completions
        url = f"{self.base_url}/chat/completions"
        
        # ⚠️ 根据文档,System Prompt 必须放在 messages 列表中
        payload = {
            "model": TEXT_MODEL,
            "messages": [
                {"role": "system", "content": system_prompt}, 
                {"role": "user", "content": user_prompt}
            ],
            "stream": False,
            "temperature": temperature,
            "max_tokens": 8192 
        }
        
        # 4次重试机制
        max_retries = 4
        for attempt in range(max_retries):
            try:
                # 增加超时时间到 500秒,因为 Thinking 模型和长文生成很慢
                resp = requests.post(url, headers=self.headers, json=payload, timeout=500)
                
                if resp.status_code == 200:
                    try:
                        data = resp.json()
                        # 【核心修复】:解析 choices[0]['message']['content']
                        if "choices" in data and len(data["choices"]) > 0:
                            content = data["choices"][0]["message"]["content"]
                            return content
                        else:
                            return f"Error: 返回结构异常,未找到 choices: {data}"
                    except KeyError:
                        return f"Error: API返回格式异常: {resp.text}"
                else:
                    print(f"⚠️ API Warning (Attempt {attempt+1}/{max_retries}): Status {resp.status_code} - {resp.text}")
                    time.sleep(3 + attempt * 2) # 失败后等待 3, 5, 7, 9 秒
            
            except requests.exceptions.Timeout:
                print(f"⚠️ Network Timeout (Attempt {attempt+1}/{max_retries})")
                time.sleep(3)
            except Exception as e:
                print(f"⚠️ Network Error (Attempt {attempt+1}/{max_retries}): {e}")
                time.sleep(3)
                
        return "Error: LLM调用失败,请检查网络连接或API Key是否正确。"

# ================= 5. 文本清洗模块 (TTS专用 - 完整版) =================

def clean_text_for_tts(text):
    """
    终极清洗函数。
    目的是生成“只能有汉字和标点”的纯净文本。
    注意:这里保留了标点符号,因为TTS需要标点来断句。
    但移除了所有Markdown和说明性文字。
    """
    if not text: return ""
    
    # 1. 暴力移除 Markdown 符号 (如 **, ##, [], >)
    text = re.sub(r"[\*\#\-\>\[\]\=\`\~]", "", text)
    
    # 2. 暴力移除所有括号及其内部内容 (说明性文字一律删)
    text = re.sub(r"(.*?)", "", text) # 全角
    text = re.sub(r"\(.*?\)", "", text) # 半角
    text = re.sub(r"【.*?】", "", text) # 方头
    text = re.sub(r"\[.*?\]", "", text) # 中括号
    
    # 3. 移除系统分隔符
    text = text.replace("@@@分隔符@@@", "").replace("===", "")
    
    # 4. 移除章节标题 (防止TTS读出来 "第一章:xxx")
    text = re.sub(r"第[一二三四五六七八九十0-9]+[章节部分].*?\n", "", text)
    
    # 5. 标点规范化 (将西文标点统一为中文标点,优化TTS停顿)
    text = text.replace(",", ",")
    text = text.replace("?", "?")
    text = text.replace("!", "!")
    text = text.replace(";", ";")
    text = text.replace(":", ":")
    
    # 6. 移除多余的空行,整理排版
    lines = [line.strip() for line in text.split('\n') if line.strip()]
    return "\n".join(lines)

# ================= 6. 核心业务逻辑:照葫芦画瓢 (数字人修正版) =================

def process_single_topic(topic_idx, topic, task_dir, generator, logger_func):
    """
    单个主题的处理全流程。
    步骤:智能选材 -> 骨架提取 -> 大纲映射 -> 疯狂扩写 -> 完结打包 -> 视频简介生成(新增)
    """
    logger_func(f"📝 [No.{topic_idx+1}] 启动任务: {topic}")
    
    # 获取最新的提示词配置
    prompts = prompt_manager.load_prompts()
    
    # --- 阶段 1: 智能选材 (Smart Select) ---
    # 根据标题相似度,自动挑4篇
    ref_content, selected_info = get_smart_references(topic, top_k=4)
    
    if not ref_content:
        logger_func("❌ [致命错误] 库中无有效素材,无法进行对标写作!")
        return None
        
    logger_func(f"🔍 [No.{topic_idx+1}] 智能锁定 4 篇对标文案:\n{selected_info}")

    # --- 阶段 2: 逆向逻辑提取 (Deconstruction) ---
    logger_func(f"🧠 [No.{topic_idx+1}] 正在逆向拆解原文逻辑骨架...")
    
    # 动态加载提示词
    logic_sys = prompts.get("logic_sys")
    logic_user = prompts.get("logic_user_template").format(ref_content=ref_content)
    
    logic_template = generator.call_llm(logic_sys, logic_user)

    # --- 阶段 3: 同构大纲生成 (Mapping) ---
    logger_func(f"📐 [No.{topic_idx+1}] 正在将新主题映射到旧骨架...")
    
    outline_sys = prompts.get("outline_sys")
    outline_user = prompts.get("outline_user_template").format(topic=topic, logic_template=logic_template)
    
    outline = generator.call_llm(outline_sys, outline_user)
    if "Error" in outline: 
        logger_func("❌ 大纲生成失败,终止任务。")
        return None

    # --- 阶段 4: 分段撰写 (9000字 + 数字人修正版) ---
    
    tasks = [
        ("Part1", "第1-3章"), 
        ("Part2", "第4-6章"), 
        ("Part3", "第7-9章"), 
        ("Part4", "第10-12章")
    ]
    
    parts_content = []       
    parts_logic = []         
    
    for stage_name, chapter_range in tasks:
        logger_func(f"✍️ [No.{topic_idx+1}] 正在深度复刻 {stage_name} (目标: 2000字)...")
        
        seg_sys = prompts.get("seg_sys").format(ref_snippet=ref_content[:3000])
        seg_user = prompts.get("seg_user_template").format(
            topic=topic, 
            chapter_range=chapter_range, 
            outline=outline
        )
        
        # 调用生成
        raw_text = generator.call_llm(seg_sys, seg_user, temperature=0.85)
        
        # ★★★ 长度强制校验 (动态修正) ★★★
        # 如果字数少于 1500,强制重写。这能保证每段至少 1500-2500,总量 6000-10000
        current_len = len(raw_text)
        if "Error" not in raw_text and current_len < 1500: 
             logger_func(f"⚠️ [No.{topic_idx+1}] {stage_name} 字数偏少({current_len}字),正在勒令扩写...")
             raw_text = generator.call_llm(
                 seg_sys, 
                 seg_user + f"\n\n【严重警告】你只写了{current_len}字!太短了!必须深入挖掘,必须达到2000字!请重写!", 
                 temperature=0.95
             )

        # 解析返回结果
        if "@@@分隔符@@@" in raw_text:
            try:
                content, logic = raw_text.split("@@@分隔符@@@", 1)
            except: 
                content, logic = raw_text, "分割异常,全部视为正文"
        else:
            content, logic = raw_text, "未检测到逻辑说明部分"
            
        parts_content.append(content.strip())
        parts_logic.append(f"=== {stage_name} ===\n{logic.strip()}\n")
        
        # 避免并发过快导致 API 429 错误
        time.sleep(2)

    # --- 阶段 5: 合并与打包 ---
    full_content = "\n".join(parts_content)
    full_logic = "\n\n".join(parts_logic)
    
    # 强力清洗 (保留标点,去除其他符号)
    tts_content = clean_text_for_tts(full_content)
    final_count = len(tts_content)
    
    logger_func(f"📊 [No.{topic_idx+1}] 撰写完成!总字数: {final_count}")
    
    # 构造文件名
    safe_topic = re.sub(r'[\\/*?:"<>|]', "", topic)[:20]
    res_dir = os.path.join(task_dir, "results")
    os.makedirs(res_dir, exist_ok=True)
    
    generated_files = []

    # 保存结果 1: TTS专用
    tts_path = os.path.join(res_dir, f"{topic_idx+1}_{safe_topic}_总{final_count}字_TTS.txt")
    with open(tts_path, "w", encoding="utf-8") as f: 
        f.write(tts_content)
    generated_files.append(tts_path)
    
    # 保存结果 2: 逻辑说明
    logic_path = os.path.join(res_dir, f"{topic_idx+1}_{safe_topic}_复刻逻辑.txt")
    with open(logic_path, "w", encoding="utf-8") as f: 
        f.write(full_logic)
    generated_files.append(logic_path)

    # --- 阶段 6: 生成视频简介 (新增功能) ---
    logger_func(f"🎬 [No.{topic_idx+1}] 正在生成 YouTube 视频发布信息...")
    
    meta_sys = prompts.get("meta_sys")
    # 使用大纲和部分正文作为输入,避免 Token 溢出
    meta_user = prompts.get("meta_user_template").format(topic=topic, outline=outline)
    
    meta_text = generator.call_llm(meta_sys, meta_user, temperature=0.7)
    
    # 保存结果 3: 视频简介
    meta_path = os.path.join(res_dir, f"{topic_idx+1}_{safe_topic}_视频简介.txt")
    with open(meta_path, "w", encoding="utf-8") as f:
        f.write(meta_text)
    generated_files.append(meta_path)
    
    return generated_files

def background_worker(task_id, topics):
    """
    后台线程:负责任务的整体调度。
    """
    task_dir = os.path.join(task_manager.root_dir, task_id)
    # 快捷日志 helper
    def log(msg): task_manager.log(task_id, msg)
    
    try:
        log(f"🚀 任务启动: 收到 {len(topics)} 个标题")
        task_manager.update_status(task_id, "running")
        
        # 预检素材库
        if not list_corpus_files():
            log("❌ 错误:素材库为空!请先上传爆款文案。")
            task_manager.update_status(task_id, "failed")
            return

        generator = TextGenerator()
        
        log(f"⚡ 启动线程池 (并发数: {MAX_CONCURRENT_TOPICS})...")
        all_generated_files = [] 
        
        with ThreadPoolExecutor(max_workers=MAX_CONCURRENT_TOPICS) as executor:
            futures = []
            for idx, topic in enumerate(topics):
                if not topic.strip(): continue
                # 提交子任务
                futures.append(
                    executor.submit(process_single_topic, idx, topic, task_dir, generator, log)
                )
            
            # 收集结果
            for future in as_completed(futures):
                try:
                    res = future.result() 
                    if res: all_generated_files.extend(res)
                except Exception as e:
                    log(f"❌ 线程执行异常: {e}")
                    traceback.print_exc()
        
        # 最终打包
        if all_generated_files:
            log("📦 正在打包所有生成结果 (含视频简介)...")
            zip_name = f"DigitalHuman_WithMeta_{len(topics)}Topics.zip"
            zip_path = os.path.join(task_dir, zip_name)
            
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                for f in all_generated_files:
                    zf.write(f, os.path.basename(f))
            
            log(f"🎉 全部完成!请点击下载按钮。")
            task_manager.update_status(task_id, "completed", result_path=zip_path)
        else:
            log("❌ 流程结束,但未生成有效文件。")
            task_manager.update_status(task_id, "failed")
            
    except Exception as e:
        log(f"💥 系统致命错误: {traceback.format_exc()}")
        task_manager.update_status(task_id, "error")

# ================= 7. UI 界面构建 (Gradio) =================

def submit_task(topic_text):
    """前端提交按钮响应"""
    if not topic_text.strip(): return "❌ 未输入标题", None
    if not list_corpus_files(): return "❌ 素材库为空!请先上传。", None
    
    topics = [t.strip() for t in topic_text.split('\n') if t.strip()]
    
    # 创建后台任务
    task_id, task_dir = task_manager.create_task()
    t = threading.Thread(target=background_worker, args=(task_id, topics))
    t.start()
    
    return f"✅ 任务已提交 (ID: {task_id})", 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
    
    status_map = {
        "initializing": "⏳ 初始化...",
        "running": "🏃‍♂️ 正在复刻中 (字数目标2000+)...",
        "completed": "✅ 已完成",
        "failed": "❌ 失败",
        "error": "💥 出错"
    }
    s_text = status_map.get(info['status'], info['status'])
    return info['log'], info['result'], f"状态: {s_text}"

def handle_clear_tasks():
    success, msg = task_manager.clear_all_tasks()
    return msg, gr.Dropdown(choices=[], value=None)

# --- 提示词管理 UI 函数 ---
def load_prompts_to_ui():
    p = prompt_manager.load_prompts()
    return (
        p.get("logic_sys"), p.get("logic_user_template"),
        p.get("outline_sys"), p.get("outline_user_template"),
        p.get("seg_sys"), p.get("seg_user_template"),
        p.get("meta_sys"), p.get("meta_user_template") # 新增
    )

def save_prompts_from_ui(l_sys, l_user, o_sys, o_user, s_sys, s_user, m_sys, m_user):
    new_prompts = {
        "logic_sys": l_sys,
        "logic_user_template": l_user,
        "outline_sys": o_sys,
        "outline_user_template": o_user,
        "seg_sys": s_sys,
        "seg_user_template": s_user,
        "meta_sys": m_sys,         # 新增
        "meta_user_template": m_user # 新增
    }
    if prompt_manager.save_prompts(new_prompts):
        return "✅ 提示词已保存,刷新页面不丢失,新任务即刻生效。"
    else:
        return "❌ 保存失败,请检查日志。"

# --- 界面布局 ---
with gr.Blocks(title="数字人·9000字工厂 (OpenAI Compatible)") as demo:
    gr.Markdown("## ✍️ 数字人·9000字精准复刻工厂 (究极重型版)")
    gr.Markdown("🌟 **核心逻辑**:智能选材 -> 逆向逻辑拆解 -> 骨架映射 -> 2000字基准扩写 -> 纯第一人称数字人 -> **生成视频描述**")
    gr.Markdown("ℹ️ **接口模式**:OpenAI 兼容协议 (适配 Yunwu Claude Opus Thinking)")
    
    with gr.Tabs():
        # --- Tab 1: 素材库 ---
        with gr.Tab("📚 1. 爆款素材库 (常驻)"):
            with gr.Row():
                with gr.Column():
                    upload_files = gr.File(label="上传爆款文案 (建议30+篇, txt格式)", file_count="multiple", file_types=[".txt"])
                    upload_btn = gr.Button("☁️ 确认入库", variant="primary")
                    upload_msg = gr.Textbox(label="状态", lines=1)
                with gr.Column():
                    gr.Markdown("### 🗂️ 库中素材")
                    current_corpus = gr.File(label="当前备选文件", interactive=False, file_count="multiple")
                    clear_corpus_btn = gr.Button("🗑️ 清空素材库", variant="stop")

        # --- Tab 2: 生成 ---
        with gr.Tab("🚀 2. 智能生成"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### 📝 输入新标题")
                    topics_input = gr.Textbox(
                        label="新主题 (一行一个)", 
                        placeholder="2026年为什么不能睡软床?\n中老年人为什么要多吃黑豆?", 
                        lines=10
                    )
                    submit_btn = gr.Button("🔥 启动数字人复刻", variant="primary")
                    submit_msg = gr.Textbox(label="提示", lines=1)
                    new_task_state = gr.State()
                with gr.Column():
                    gr.Markdown("### ℹ️ 运行原理")
                    gr.Markdown("""
                    1. **智能选材**:系统自动从库中挑出 **4篇** 最像的。
                    2. **数字人**:第一人称直播视角,**严禁出现“生前”、“去世”**。
                    3. **精准控幅**:每段目标 2000 字(预留500字溢出空间),总字数控制在 9000-10000 左右。
                    4. **TTS优化**:输出带标点的纯净文本,可直接朗读。
                    5. **视频发布**:自动生成 YouTube 标题、描述和 Hashtags。
                    """)

        # --- Tab 3: 提示词配置 (新增) ---
        with gr.Tab("⚙️ 3. 提示词配置"):
            gr.Markdown("### 🔧 提示词管理 (修改后点击保存,永久生效)")
            save_prompts_btn = gr.Button("💾 保存所有提示词配置", variant="primary")
            save_status = gr.Label("")
            
            with gr.Accordion("阶段一:逻辑拆解 (Logic Extraction)", open=False):
                p_logic_sys = gr.Textbox(label="System Prompt", lines=3)
                p_logic_user = gr.Textbox(label="User Prompt (可用变量: {ref_content})", lines=10)
            
            with gr.Accordion("阶段二:大纲生成 (Outline Mapping)", open=False):
                p_outline_sys = gr.Textbox(label="System Prompt", lines=3)
                p_outline_user = gr.Textbox(label="User Prompt (可用变量: {topic}, {logic_template})", lines=10)
            
            with gr.Accordion("阶段三:正文扩写 (Segment Writing)", open=True):
                p_seg_sys = gr.Textbox(label="System Prompt (可用变量: {ref_snippet})", lines=10)
                p_seg_user = gr.Textbox(label="User Prompt (可用变量: {topic}, {chapter_range}, {outline})", lines=10)

            # --- 新增的 UI 区域 ---
            with gr.Accordion("阶段四:视频描述生成 (Meta Generation)", open=False):
                p_meta_sys = gr.Textbox(label="System Prompt", lines=3)
                p_meta_user = gr.Textbox(label="User Prompt (可用变量: {topic}, {outline})", lines=10)

        # --- Tab 4: 监控 ---
        with gr.Tab("📺 4. 监控与下载"):
            with gr.Row():
                with gr.Column(scale=1):
                    refresh_btn = gr.Button("🔄 刷新列表")
                    task_select = gr.Dropdown(label="任务记录", choices=[], interactive=True)
                    status_label = gr.Label("状态: --")
                    download_btn = gr.File(label="📥 下载ZIP")
                    clear_tasks_btn = gr.Button("🗑️ 清空记录", variant="stop")
                    clear_tasks_msg = gr.Label("")
                with gr.Column(scale=3):
                    log_view = gr.Textbox(label="运行日志", lines=20, max_lines=20)
                    timer = gr.Timer(2)

    # --- 逻辑连接 ---
    # 1. 素材库
    upload_btn.click(save_to_corpus, upload_files, [current_corpus, upload_msg])
    clear_corpus_btn.click(clear_corpus, outputs=[current_corpus, upload_msg])
    
    # 2. 任务提交
    submit_btn.click(submit_task, [topics_input], [submit_msg, new_task_state])
    submit_btn.click(lambda nid: gr.Dropdown(choices=task_manager.list_tasks(), value=nid), new_task_state, task_select)
    
    # 3. 监控刷新
    refresh_btn.click(refresh_task_list, outputs=task_select)
    clear_tasks_btn.click(handle_clear_tasks, outputs=[clear_tasks_msg, task_select])
    timer.tick(get_task_details, inputs=[task_select], outputs=[log_view, download_btn, status_label])
    task_select.change(get_task_details, inputs=[task_select], outputs=[log_view, download_btn, status_label])
    
    # 4. 提示词管理 (已更新包含 Meta 提示词)
    demo.load(load_prompts_to_ui, outputs=[p_logic_sys, p_logic_user, p_outline_sys, p_outline_user, p_seg_sys, p_seg_user, p_meta_sys, p_meta_user])
    save_prompts_btn.click(
        save_prompts_from_ui, 
        inputs=[p_logic_sys, p_logic_user, p_outline_sys, p_outline_user, p_seg_sys, p_seg_user, p_meta_sys, p_meta_user],
        outputs=save_status
    )
    
    # 初始化加载
    demo.load(fn=list_corpus_files, outputs=current_corpus)
    demo.load(refresh_task_list, outputs=task_select)

if __name__ == "__main__":
    # 启动应用
    demo.queue().launch()