Spaces:
Sleeping
Sleeping
Update app.py
Browse files48 unmodified lines495051525354555657585 unmodified lines64656667686970215 unmodified lines28628728828929029129229329429529629729829930011 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383399 unmodified lines34935035135235335435535621 unmodified lines37837938038138238338411 unmodified lines3963973983994004014024034044054064074084094104114124134144154161 unmodified line4184194204214224234244254264274284294304314324334342 unmodified lines43743843944044144244344444544644744844945045145245345445545645745845946046146246337 unmodified lines50150250350450550650780 unmodified lines5885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516 unmodified lines65865966066166266366466566666766866967067167267367467567667748 unmodified lines# 1. 核心鉴权配置API_KEY = "sk-vhrneE8MG8c3ADoIR8r3cI5QFoJpe8wVfN25u0hkYVqbQeIA"BASE_URL = "https://yunwu.ai" # 适配你的 OpenAI 兼容协议接口# 2. 模型参数配置# 使用最强的 Opus 4.5 Thinking 模型以挑战 1万字长文TEXT_MODEL = "claude-opus-4-5-20251101-thinking"# 3. 并发控制5 unmodified lineselse:ROOT_BASE = os.getcwd()TASKS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_tasks_v12_strict")CORPUS_ROOT_DIR = os.path.join(ROOT_BASE, "nihaisha_corpus_lib")PERSONAS_FILE = os.path.join(ROOT_BASE, "personas_config.json")215 unmodified lines"messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ],"stream": False,"temperature": temperature,# Token上限32000,确保万字长文不截断"max_tokens": 32000}max_retries = 4for attempt in range(max_retries):try:# 600秒超时,等待思考resp = requests.post(url, headers=self.headers, json=payload, timeout=600)if resp.status_code == 200:data = resp.json()if "choices" in data and len(data["choices"]) > 0:11 unmodified linesdef clean_text_for_tts(text):if not text: return ""# 移除Markdown符号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):"""【V12 严格分段处理逻辑】强制要求 AI 按照特定分隔符输出三部分。"""logger_func(f"🚀 [No.{idx+1}] 启动: {topic if topic else '无主题模式'}")# 1. 确定 Prompt 来源 (WYSIWYG)sys_prompt = ""user_tpl = ""9 unmodified linespersona = persona_manager.get_persona(persona_name)user_tpl = persona.get("user_template", "")# 2. 注入【强制结构指令】与【极限字数指令】# 使用特殊的分割符来确保代码能精准切割SEGMENT_BORDER = "==========SEGMENT_BORDER=========="mandatory_instruction = f"""21 unmodified linesfinal_user_prompt = user_tpl + mandatory_instruction# 替换变量if topic:if "{topic}" in final_user_prompt:final_user_prompt = final_user_prompt.replace("{topic}", topic)11 unmodified linesif ref_context:final_user_prompt += f"\n\n=== 必读参考资料 ===\n{ref_context}"# 3. 生成logger_func(f"✍️ AI正在创作 (目标: 1万字)...")raw_text = generator.call_llm(sys_prompt, final_user_prompt)if "Error" in raw_text:logger_func(f"❌ 生成失败: {raw_text}")return None, None# 4. 智能切割 (Split)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()1 unmodified linebody_part = parts[2].strip().replace("第三部分:", "").replace("【口播正文】", "").strip()else:logger_func("⚠️ 警告:AI未严格遵守分割符,正在尝试降级处理...")# 降级处理:直接保存全文# 5. 清洗正文 (TTS用)cleaned_tts_body = clean_text_for_tts(body_part)# 6. 文件保存# 确定基础文件名if topic:base_filename = topicelse:# 如果自动拟了标题,尝试用第一行的标题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]2 unmodified linesgenerated_files = []# 文件A: 标题 + 视频描述meta_content = f"【标题】\n{title_part}\n\n【YouTube视频描述】\n{desc_part}"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_content)generated_files.append(meta_path)# 文件B: 正文 (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_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)} 字")# 返回提取的标题用于ZIP命名return generated_files, title_part.split('\n')[0]def worker(task_id, topics, persona_name, custom_sys, custom_user, selected_refs, manual_topic_name):37 unmodified linestraceback.print_exc()if all_files_to_zip:# === ZIP 动态命名逻辑 ===if manual_topic_name:safe_zip_name = re.sub(r'[\\/*?:"<>|]', "", manual_topic_name)[:30]zip_filename = f"{safe_zip_name}.zip"80 unmodified lines# --- 界面布局 ---with gr.Blocks(title="AI 灵活内容工厂 (V12 Strict)") as demo:gr.Markdown("## 🧞♂️ AI 灵活内容工厂 (V12 严格输出版)")gr.Markdown("支持:**强制三段式输出** | **9000-1万字锁定** | **YouTube SEO优化**")state_all_files = gr.State([])with gr.Row():# --- 左侧:配置区 ---with gr.Column(scale=1):gr.Markdown("### 1. 核心配置")gr.Markdown("**加载预设角色 (选填)**")persona_select = gr.Dropdown(label="选择预设加载到下方", choices=persona_manager.get_all_names(), interactive=True)gr.Markdown("---")gr.Markdown("**Prompt 编辑区 (所见即所得)**")p_sys_input = gr.Textbox(label="System Prompt (人设)", lines=3, placeholder="在此输入人设...")p_user_input = gr.Textbox(label="User Template (指令)", lines=10, placeholder="在此输入具体指令...")with gr.Accordion("💾 保存当前配置为新角色 (可选)", open=False):p_name_input = gr.Textbox(label="新角色名称")with gr.Row():p_save_btn = gr.Button("保存新角色")p_del_btn = gr.Button("删除选中角色", variant="stop")p_status = gr.Label(show_label=False)# --- 中间:任务区 ---with gr.Column(scale=1):gr.Markdown("### 2. 任务与素材")topic_input = gr.Textbox(label="输入主题 (可为空)", lines=3, placeholder="输入主题则智能匹配素材;\n留空则显示所有素材,让AI根据素材自拟标题。")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)# --- 右侧:素材库与监控 ---with gr.Column(scale=1):with gr.Tabs():with gr.Tab("📚 素材库"):files = gr.File(label="上传素材 (txt)", file_count="multiple")upload_btn = gr.Button("☁️ 确认入库")upload_res = gr.Label()corpus_display = gr.File(label="库中文件", interactive=False)clear_btn = gr.Button("🗑️ 清空")with gr.Tab("📺 监控"):refresh_task = gr.Button("🔄 刷新")task_dd = gr.Dropdown(label="任务记录")log_box = gr.Textbox(label="日志", lines=15)result_dl = gr.File(label="下载Zip")# --- 事件绑定 ---6 unmodified linesoutputs=task_dd)persona_select.select(on_select_persona_config, persona_select, [p_sys_input, p_user_input])p_save_btn.click(save_new_persona, [p_name_input, p_sys_input, p_user_input], [p_status, persona_select])p_del_btn.click(delete_persona, persona_select, [p_status, persona_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])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(update_persona_dropdown, outputs=persona_select)if __name__ == "__main__":demo.queue().launch()48 unmodified lines4950515253545556575 unmodified lines63646566676869215 unmodified lines28528628728828929029129229329429529629729829911 unmodified lines3113123133143153163173183193203213223233243253263273283299 unmodified lines33934034134234334421 unmodified lines36636736836937037111 unmodified lines3833843853863873883893903913923933943953963973983991 unmodified line4014024034044054064074084094104114122 unmodified lines41541641741841942042142242342442542642742842943043143243343443543637 unmodified lines47447547647747847980 unmodified lines5605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296 unmodified lines63663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167248 unmodified lines# 1. 核心鉴权配置API_KEY = "sk-vhrneE8MG8c3ADoIR8r3cI5QFoJpe8wVfN25u0hkYVqbQeIA"BASE_URL = "https://yunwu.ai"# 2. 模型参数配置TEXT_MODEL = "claude-opus-4-5-20251101-thinking"# 3. 并发控制5 unmodified lineselse: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")215 unmodified lines"messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ],"stream": False,"temperature": temperature,"max_tokens": 32000}max_retries = 4for attempt in range(max_retries):try:# 超时时间调整为 1500s (25分钟)resp = requests.post(url, headers=self.headers, json=payload, timeout=1500)if resp.status_code == 200:data = resp.json()if "choices" in data and len(data["choices"]) > 0:11 unmodified linesdef 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 = ""9 unmodified linespersona = persona_manager.get_persona(persona_name)user_tpl = persona.get("user_template", "")SEGMENT_BORDER = "==========SEGMENT_BORDER=========="mandatory_instruction = f"""21 unmodified linesfinal_user_prompt = user_tpl + mandatory_instructionif topic:if "{topic}" in final_user_prompt:final_user_prompt = final_user_prompt.replace("{topic}", topic)11 unmodified linesif ref_context:final_user_prompt += f"\n\n=== 必读参考资料 ===\n{ref_context}"logger_func(f"✍️ AI正在创作 (目标: 1万字, 请耐心等待15-20分钟)...")raw_text = generator.call_llm(sys_prompt, final_user_prompt)if "Error" in raw_text:logger_func(f"❌ 生成失败: {raw_text}")return None, Noneparts = raw_text.split(SEGMENT_BORDER)title_part = "未提取到标题"desc_part = "未提取到描述"body_part = raw_textif len(parts) >= 3:title_part = parts[0].strip().replace("第一部分:", "").replace("【标题】", "").strip()1 unmodified linebody_part = parts[2].strip().replace("第三部分:", "").replace("【口播正文】", "").strip()else:logger_func("⚠️ 警告:AI未严格遵守分割符,正在尝试降级处理...")cleaned_tts_body = clean_text_for_tts(body_part)if topic:base_filename = topicelse: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]2 unmodified linesgenerated_files = []meta_content = f"【标题】\n{title_part}\n\n【YouTube视频描述】\n{desc_part}"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_content)generated_files.append(meta_path)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_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):37 unmodified linestraceback.print_exc()if all_files_to_zip:if manual_topic_name:safe_zip_name = re.sub(r'[\\/*?:"<>|]', "", manual_topic_name)[:30]zip_filename = f"{safe_zip_name}.zip"80 unmodified lines# --- 界面布局 ---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. 创作中心"):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. 角色配置"):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")# --- 事件绑定 ---6 unmodified linesoutputs=task_dd)# 角色配置联动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)p_save_btn.click(save_new_persona, [p_name_input, p_sys_input, p_user_input], [p_status, p_config_select])p_save_btn.click(update_persona_dropdown, outputs=persona_select)p_del_btn.click(delete_persona, p_config_select, [p_status, p_config_select])p_del_btn.click(update_persona_dropdown, outputs=persona_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])# 【关键修复】自动刷新逻辑# 每2秒从后台读取日志和结果文件路径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(update_persona_dropdown, outputs=persona_select)demo.load(update_persona_dropdown, outputs=p_config_select)if __name__ == "__main__":demo.queue().launch()
app.py+76-81