Update app.py
Browse files219 unmodified lines22022122222322422522622722822923023123223323423582 unmodified lines31831932032132232332411 unmodified lines3363373383393403413423436 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713728 unmodified lines3813823833843853863873883893903913923933943953963973983994004014024034044054064075 unmodified lines41341441541641741841910 unmodified lines43043143243343443543643743843944044144244344444544644730 unmodified lines47847948048148248348448548648748825 unmodified lines51451551651751851952052152223 unmodified lines54654754854955055155255355413 unmodified lines5685695705715725735742 unmodified lines577578579580581582583584585586219 unmodified linesreturn context, " + ".join(log_names)# ================= 3. 任务与日志系统 =================class TaskManager:def __init__(self, root_dir=TASKS_ROOT_DIR):self.root_dir = root_diros.makedirs(self.root_dir, exist_ok=True)def create_task(self, task_name_prefix="task"):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)82 unmodified linestime.sleep(3)return "Error: LLM调用失败"# ================= 5. TTS清洗与处理逻辑 =================def clean_text_for_tts(text):"""TTS专用清洗逻辑"""11 unmodified linesdef process_single_topic(idx, topic, persona_name, ref_context, ref_log_name, task_dir, generator, logger_func):"""【完全纯净的注入逻辑】不再包含任何硬编码的内容指令,一切以用户的 Persona 配置为准。"""logger_func(f"🚀 [No.{idx+1}] 启动: {topic if topic else '无主题模式 (依赖素材)'}")logger_func(f"📚 注入素材: {ref_log_name}")6 unmodified lines# 2. 自动组装 Promptfinal_user_prompt = user_tpl# 注意:这里删除了所有的 "length_instruction" (强制注水指令)# 现在完全依赖 user_template 中的定义# 替换变量 {topic}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:# 如果用户没给主题,只给个标记,具体怎么处理由 Prompt 决定if "{topic}" in final_user_prompt:final_user_prompt = final_user_prompt.replace("{topic}", "(未指定,请根据参考资料自拟)")else:final_user_prompt += "\n\n=== 核心任务主题 ===\n(用户未指定主题,请根据参考资料自拟)"# 替换变量 {references}if "{references}" in final_user_prompt:final_user_prompt = final_user_prompt.replace("{references}", ref_context)else:8 unmodified lineslogger_func(f"❌ 生成失败: {raw_text}")return None# 4. 清洗cleaned_text = clean_text_for_tts(raw_text)# 5. 保存filename_topic = re.sub(r'[\\/*?:"<>|]', "", topic)[:20] if topic else f"Untitled_{datetime.now().strftime('%H%M%S')}"res_dir = os.path.join(task_dir, "results")os.makedirs(res_dir, exist_ok=True)tts_path = os.path.join(res_dir, f"{idx+1}_{filename_topic}_{persona_name}.txt")with open(tts_path, "w", encoding="utf-8") as f:f.write(cleaned_text)# 保存调试用的 Prompt,方便你检查真正发给 AI 的是什么debug_path = os.path.join(res_dir, f"{idx+1}_debug_prompt.log")with open(debug_path, "w", encoding="utf-8") as f:f.write(f"--- SYSTEM ---\n{sys_prompt}\n\n--- USER ---\n{final_user_prompt}")logger_func(f"✅ 完成!({len(cleaned_text)}字)")return tts_pathdef worker(task_id, topics, persona_name, selected_refs):"""后台工作线程"""task_dir = os.path.join(task_manager.root_dir, task_id)def log(m): task_manager.log(task_id, m)5 unmodified lines# 统一读取用户选中的素材ref_context, ref_log_name = build_references_from_selection(selected_refs)all_files = []with ThreadPoolExecutor(max_workers=MAX_CONCURRENT_TOPICS) as executor:futures = []for idx, topic in enumerate(topics):10 unmodified linesfor f in as_completed(futures):try:res = f.result()if res: all_files.append(res)except Exception as e:log(f"Error: {e}")traceback.print_exc()if all_files:zip_path = os.path.join(task_dir, f"Batch_{len(all_files)}_Files.zip")with zipfile.ZipFile(zip_path, 'w') as z:for f in all_files: z.write(f, os.path.basename(f))task_manager.update_status(task_id, "completed", zip_path)log("🎉 任务结束,ZIP打包完成。")else:task_manager.update_status(task_id, "failed")log("❌ 未生成有效文件。")30 unmodified linesreturn "❌ 既无主题也无素材,无法生成", Nonetopics = topic_text.split('\n')if not topic_text.strip(): topics = [""]tid, _ = task_manager.create_task()threading.Thread(target=worker, args=(tid, topics, persona_name, selected_refs)).start()return f"任务已启动: {tid}", tid# --- UI Helper (角色管理) ---25 unmodified lines# --- 界面布局 ---with gr.Blocks(title="AI 灵活内容工厂 (V10 Pure)") as demo:gr.Markdown("## 🧞♂️ AI 灵活内容工厂 (纯净指令版)")gr.Markdown("支持:**智能/全量素材选择** | **角色自动保存** | **Token上限32k**")state_all_files = gr.State([])23 unmodified linesgr.Markdown("""**模式 A:有明确主题**1. 输入主题 -> 点击分析 -> 勾选素材 -> 生成。**模式 B:无主题(让AI发挥)**1. **留空**主题 -> 点击分析(列出全部) -> 勾选素材 -> 生成。""")# --- Tab 2: 角色管理 (UI 修改核心区域) ---13 unmodified lines# 这里的文案只是说明,不影响代码逻辑gr.Markdown("""#### 1. System Prompt (系统提示词 / 人设)* 示例:你是倪海厦在YouTube平台的数字人分身,你精通中医、易经、五行八卦、黄历等等,你生平写了很多关于中医和风水的著作,你现在给45-70岁的老年朋友上课。""")p_sys_input = gr.Textbox(label="System Prompt 输入区", lines=3)2 unmodified linesgr.Markdown("""#### 2. User Template (用户指令模板 / 写作指令)* 告诉AI具体怎么写,系统会自动将 **{topic}** 和 **{references}** 拼接到最后。* 示例:1、请写一篇9000-10000字的长文,引用参考资料中的案例。2、全文使用第一人称,环境是在给观众录制YouTube视频3、仔细拆解提供的参考爆款文案,整理爆款文案的爆点,写作逻辑,为什么可以吸引观众,然后学习复刻骨架,写出新的爆款文案4、....""")p_user_input = gr.Textbox(label="User Template 输入区", lines=12, placeholder="在这里输入你的核心写作指令...")219 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524682 unmodified lines32933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835911 unmodified lines3713723733743753763773786 unmodified lines3853863873883893903913923933943953963973983994004018 unmodified lines4104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584595 unmodified lines46546646746846947047147247310 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751830 unmodified lines54955055155255355455555655755855956056156256325 unmodified lines58959059159259359459559659723 unmodified lines62162262362462562662762862963063113 unmodified lines6456466476486496506512 unmodified lines654655656657658659660219 unmodified linesreturn context, " + ".join(log_names)# ================= 3. 任务与日志系统 (增强命名功能) =================class TaskManager:def __init__(self, root_dir=TASKS_ROOT_DIR):self.root_dir = root_diros.makedirs(self.root_dir, exist_ok=True)def create_task(self, task_name_prefix="task", custom_label=None):"""创建任务。如果提供了 custom_label (手动输入的主题),则文件名包含该主题。"""timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')# 处理文件名安全性if custom_label:safe_label = re.sub(r'[\\/*?:"<>|]', "", custom_label)[:15] # 截取前15字避免过长task_id = f"{timestamp}_{safe_label}"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)82 unmodified linestime.sleep(3)return "Error: LLM调用失败"# ================= 5. TTS清洗与元数据提取处理逻辑 =================def extract_meta_data(text):"""从文本中提取标题和视频描述。返回: (合并后的元数据文本, 提取到的标题字符串)"""meta_content = []extracted_title = None# 提取标题 (匹配 "标题:" 或 "Title:")t_match = re.search(r'(?:标题|Title)[::]\s*(.*)', text)if t_match:extracted_title = t_match.group(1).strip()meta_content.append(f"【标题】\n{extracted_title}")# 提取视频描述 (匹配 "视频描述:" 或 "Video Description:",直到双换行或结束)d_match = re.search(r'(?:视频描述|Video Description)[::]\s*([\s\S]*?)(?=\n\n\n|===|$)', text)if d_match:meta_content.append(f"\n【视频描述】\n{d_match.group(1).strip()}")if not meta_content:return None, Nonereturn "\n\n".join(meta_content), extracted_titledef clean_text_for_tts(text):"""TTS专用清洗逻辑"""11 unmodified linesdef process_single_topic(idx, topic, persona_name, ref_context, ref_log_name, task_dir, generator, logger_func):"""【处理单条主题】新增:自动分离元数据和正文,自动推断标题。"""logger_func(f"🚀 [No.{idx+1}] 启动: {topic if topic else '无主题模式 (依赖素材)'}")logger_func(f"📚 注入素材: {ref_log_name}")6 unmodified lines# 2. 自动组装 Promptfinal_user_prompt = user_tplif 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:8 unmodified lineslogger_func(f"❌ 生成失败: {raw_text}")return None# 4. 提取元数据 (标题/描述) & 清洗正文meta_text, auto_inferred_title = extract_meta_data(raw_text)cleaned_text = clean_text_for_tts(raw_text)# 5. 确定文件名 (优先使用提取的标题,没有则用主题,还没有则用时间戳)# 如果topic为空,尝试使用AI生成的标题if not topic and auto_inferred_title:base_filename = auto_inferred_titleelif topic:base_filename = topicelse:base_filename = f"Untitled_{datetime.now().strftime('%H%M%S')}"safe_filename = re.sub(r'[\\/*?:"<>|]', "", base_filename)[:30] # 截取前30个字符res_dir = os.path.join(task_dir, "results")os.makedirs(res_dir, exist_ok=True)generated_files = []# 保存正文 (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_text)generated_files.append(tts_path)# 保存元数据 (如果存在)if meta_text:meta_path = os.path.join(res_dir, f"{idx+1}_{safe_filename}_Meta.txt")with open(meta_path, "w", encoding="utf-8") as f:f.write(meta_text)generated_files.append(meta_path)# 保存调试用的 Promptdebug_path = os.path.join(res_dir, f"{idx+1}_debug_prompt.log")with open(debug_path, "w", encoding="utf-8") as f:f.write(f"--- SYSTEM ---\n{sys_prompt}\n\n--- USER ---\n{final_user_prompt}")logger_func(f"✅ 完成!({len(cleaned_text)}字)")# 返回:文件列表 和 自动推断的标题(用于ZIP命名)return generated_files, auto_inferred_titledef worker(task_id, topics, persona_name, selected_refs, manual_topic_name=None):"""后台工作线程"""task_dir = os.path.join(task_manager.root_dir, task_id)def log(m): task_manager.log(task_id, m)5 unmodified lines# 统一读取用户选中的素材ref_context, ref_log_name = build_references_from_selection(selected_refs)all_files_to_zip = []first_auto_title = None # 用于自动模式下命名ZIPwith ThreadPoolExecutor(max_workers=MAX_CONCURRENT_TOPICS) as executor:futures = []for idx, topic in enumerate(topics):10 unmodified linesfor 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_titleexcept Exception as e:log(f"Error: {e}")traceback.print_exc()if all_files_to_zip:# === ZIP 动态命名逻辑 ===if manual_topic_name:# 如果用户手动输入了主题,ZIP名字就是主题safe_zip_name = re.sub(r'[\\/*?:"<>|]', "", manual_topic_name)[:30]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))task_manager.update_status(task_id, "completed", zip_path)log(f"🎉 任务结束,ZIP已打包: {zip_filename}")else:task_manager.update_status(task_id, "failed")log("❌ 未生成有效文件。")30 unmodified linesreturn "❌ 既无主题也无素材,无法生成", Nonetopics = topic_text.split('\n')# 获取第一个有效主题用于命名任务文件夹和ZIPmanual_topic_name = topics[0].strip() if topic_text.strip() else Noneif 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, selected_refs, manual_topic_name)).start()return f"任务已启动: {tid}", tid# --- UI Helper (角色管理) ---25 unmodified lines# --- 界面布局 ---with gr.Blocks(title="AI 灵活内容工厂 (V10 Pro)") as demo:gr.Markdown("## 🧞♂️ AI 灵活内容工厂 (纯净指令版 + 智能命名)")gr.Markdown("支持:**自动提取标题描述分离文件** | **ZIP智能命名** | **Token上限32k**")state_all_files = gr.State([])23 unmodified linesgr.Markdown("""**模式 A:有明确主题**1. 输入主题 -> 点击分析 -> 勾选素材 -> 生成。* 结果:ZIP包会以该主题命名。**模式 B:无主题(让AI发挥)**1. **留空**主题 -> 点击分析(列出全部) -> 勾选素材 -> 生成。* 结果:AI会自动根据生成内容的标题来命名 ZIP 包。""")# --- Tab 2: 角色管理 (UI 修改核心区域) ---13 unmodified lines# 这里的文案只是说明,不影响代码逻辑gr.Markdown("""#### 1. System Prompt (系统提示词 / 人设)* 示例:你是一个拥有20年经验的中医专家。""")p_sys_input = gr.Textbox(label="System Prompt 输入区", lines=3)2 unmodified linesgr.Markdown("""#### 2. User Template (用户指令模板 / 写作指令)* 告诉AI具体怎么写,系统会自动将 **{topic}** 和 **{references}** 拼接到最后。* 示例:请写一篇3000字的长文,引用参考资料中的案例。""")p_user_input = gr.Textbox(label="User Template 输入区", lines=12, placeholder="在这里输入你的核心写作指令...")
app.py+111-37