Spaces:
Sleeping
Sleeping
Update app.py
Browse files19 unmodified lines2021222324252627282930313 unmodified lines35363738394041424344454611 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912015 unmodified lines1361371381391401411421431441451461471481491501513 unmodified lines1551561571581591601614 unmodified lines16616716816917017117217317417517617717817918018118218318418518627 unmodified lines2142152162172182192202212222232242252263 unmodified lines23023123223323423523623 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128221 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573581 unmodified line36036136236336436536636736836937037137237337437537637737817 unmodified lines3963973983994004014024034044054064074084094104111 unmodified line4134144154164174184194204214224234244254264274284294304314324334344355 unmodified lines4414424434444454464474484494504514524534544554564574584594604614624634644654664674684693 unmodified lines4734744754764774784794 unmodified lines4844854864874884894901 unmodified line4924934944954964974989 unmodified lines5085095105115125135145155165175185195205215225235249 unmodified lines5345355365375385395405415425435445455465475485495505515525535545555565575581 unmodified line56056156256356456556617 unmodified lines5845855865875885895905915925935945955965972 unmodified lines6006016026036046056064 unmodified lines61161261361461561661711 unmodified lines6296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736741 unmodified line67667767867968068168217 unmodified lines7007017027037047057067077087097107117121 unmodified line7147157167177187197209 unmodified lines7307317327337347357364 unmodified lines7417427437447457467477487497507517527537547557567577587593 unmodified lines7637647657667677687697707717727737747757767777782 unmodified lines7817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138145 unmodified lines8208218228238248256 unmodified lines8328338348358368378388398408418428438448458468478488498508518528538548558568578588598606 unmodified lines86786886987087187287387487587687787887988088188288388488588688788888989089189289389410 unmodified lines90590690790890991091191291391491591691791891992092192292392492592619 unmodified linesfrom datetime import datetime, timezone, timedeltaimport pandas as pdimport numpy as npimport fcntlimport atexit# 然后再引入本地模块from app_config import APP_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTSfrom utils.file_parser import extract_text_from_files, extract_data_from_files, count_words_adaptivefrom utils.docx_builder import text_to_docxfrom core.pipeline_agent import SSciPipelineAgent3 unmodified linesos.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码META_SECTIONS_BLACKLIST = {"abstract", "keyword", "keywords", "摘要", "关键词", "关键字","reference", "references", "reference list", "参考文献","acknowledgment", "acknowledgements", "致谢"}# 🏗️ 架构重构 2:顶层纯函数提取,避免正则灾难性回溯def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):11 unmodified linesglobal_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")if not global_ds_key:try:global_ds_key = st.secrets.get("DEEPSEEK_API_KEY", "")except:passglobal_s2_key = os.environ.get("S2_API_KEY", "")if not global_s2_key:try:global_s2_key = st.secrets.get("S2_API_KEY", "")except:pass# 状态机:断点续传工作区配置WORKSPACE_DIR = ".workspace"CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")TASK_LOCK_FILE = os.path.join(WORKSPACE_DIR, "task.lock")if not os.path.exists(WORKSPACE_DIR):os.makedirs(WORKSPACE_DIR, exist_ok=True)# ------------------------- 混合并发锁(session_state 标志 + 文件锁)-------------------------def acquire_global_lock():"""尝试获取全局任务锁,返回 (是否成功, 锁文件句柄)"""try:lock_fd = open(TASK_LOCK_FILE, 'w')fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)return True, lock_fdexcept (BlockingIOError, IOError):if 'lock_fd' in locals():lock_fd.close()return False, Nonedef release_global_lock(lock_fd):"""释放任务锁并关闭文件"""if lock_fd:try:fcntl.flock(lock_fd, fcntl.LOCK_UN)lock_fd.close()except:pass# 清理锁文件try:if os.path.exists(TASK_LOCK_FILE):os.remove(TASK_LOCK_FILE)except:passdef cleanup_lock_file():"""进程退出时清理锁文件"""try:if os.path.exists(TASK_LOCK_FILE):os.remove(TASK_LOCK_FILE)except:passatexit.register(cleanup_lock_file)# --------------------------------------------------------------------------------# 微信拦截与提示WECHAT_BLOCKER_JS = """<script>15 unmodified linescomponents.html(WECHAT_BLOCKER_JS, height=0, width=0)# ==========================================# 🚨 访问控制 (保持不变)# ==========================================def check_password():expected_password = os.environ.get("APP_PASSWORD", "")if not expected_password:try:expected_password = st.secrets.get("APP_PASSWORD", "")except:passif not expected_password:return True3 unmodified linesif not st.session_state["password_correct"]:st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)st.markdown("<p style='text-align: center;'>本系统为高���力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)pwd = st.text_input("Access Token", type="password", key="pwd_input")if st.button("Unlock"):if pwd == expected_password:4 unmodified linesst.stop()return Truecheck_password()# ==========================================# 1. 鲁棒的蒙特卡洛实证模拟引擎 (保持不变)# ==========================================def generate_psd_corr_matrix(n_constructs, max_corr=0.5):if n_constructs == 1:return np.array([[1.0]])base_corr = np.random.uniform(0.2, max_corr - 0.1)A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))A = (A + A.T) / 2np.fill_diagonal(A, 1.0)min_eig = np.min(np.linalg.eigvals(A))if min_eig < 0:A -= (min_eig - 0.01) * np.eye(n_constructs)d = np.sqrt(np.diag(A))return A / np.outer(d, d)27 unmodified linestarget_std = scale_points / 5.0for idx, c_name in enumerate(construct_names):true_score = latent_scores[:, idx]n_items = np.random.randint(3, 6)loadings = np.random.uniform(0.72, 0.88, n_items)true_loadings[c_name] = loadingsitem_names = []for i, load in enumerate(loadings):error = np.random.normal(0, np.sqrt(1 - load**2), n)item_score = load * true_score + errorraw_scaled = item_score * target_std + target_meanitem_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)col_name = f"{c_name}_{i+1}"3 unmodified linesdf = pd.DataFrame(data)validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})fl_matrix = mean_scores.corr().astype(object)for i, row in validity_df.iterrows():c_name = row['Construct']sqrt_ave = np.sqrt(row['AVE'])23 unmodified linesreturn df, simulated_md_prompt, status_msg# ==========================================# 2. UI 界面布局与初始化 (保持不变)# ==========================================if "is_running" not in st.session_state:st.session_state.is_running = Falseif "start_pipeline" not in st.session_state:st.session_state.start_pipeline = Falseif "resume_pipeline" not in st.session_state:st.session_state.resume_pipeline = Falseif "zip_buffer" not in st.session_state:st.session_state.zip_buffer = Noneif "run_mode" not in st.session_state:st.session_state.run_mode = "wizard"# 并发控制相关if "global_task_running" not in st.session_state:st.session_state.global_task_running = Falseif "lock_fd" not in st.session_state:st.session_state.lock_fd = Nonelang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]21 unmodified lineswith tab_wizard:st.markdown("### 🛠️ 人在环路:研究材料配置")prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",options=["工商管理实证研究 (AMJ Style)", "通用学术规范 (Generic Style)"],index=0, disabled=st.session_state.is_running)uploaded_papers_wiz = st.file_uploader("2. 上传核心参考论文 (可选,支持 PDF/DOCX,建议1-5篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, disabled=st.session_state.is_running)uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):if st.session_state.global_task_running:st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")else:acquired, lock_fd = acquire_global_lock()if not acquired:st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")else:st.session_state.global_task_running = Truest.session_state.lock_fd = lock_fdst.session_state.run_mode = "wizard"st.session_state.start_pipeline = Truest.rerun()with tab_clone:st.markdown("### 🧬 高级克隆:骨架与风格复刻")context_differences = st.text_area("1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",max_chars=2000,disabled=st.session_state.is_running)if "extracted_sections" not in st.session_state:st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]if "last_uploaded_clone_ref" not in st.session_state:st.session_state.last_uploaded_clone_ref = Noneuploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)if uploaded_reference_clone and global_ds_key:if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)ref_text_raw = extract_text_from_files([uploaded_reference_clone])dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)st.session_state.extracted_sections = dynamic_sectionsst.session_state.last_uploaded_clone_ref = uploaded_reference_clone.namest.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)uploaded_core_papers_clone = st.file_uploader("4. 上传核心理论参考论文 (可选,用于提升理论深度,建议1-5篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, key="clone_core_papers", disabled=st.session_state.is_running)if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):1 unmodified linest.error("🚨 启动克隆模式必须填写研究背景与核心差异!")elif not uploaded_reference_clone:st.error("🚨 启动克隆模式必须上传范例论文!")else:if st.session_state.global_task_running:st.error("⚠️ 系统正忙:当前有其他研究��正在独占系统生成论文。请稍后重试。")else:acquired, lock_fd = acquire_global_lock()if not acquired:st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")else:st.session_state.global_task_running = Truest.session_state.lock_fd = lock_fdst.session_state.run_mode = "clone"st.session_state.start_pipeline = Truest.rerun()progress_bar = st.empty()monitor_ui = st.empty()17 unmodified linesFLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}# ==========================================# 3. 后台流水线执行 (混合锁控制 + 字数统计修正 + 优雅降级)# ==========================================if st.session_state.start_pipeline or st.session_state.resume_pipeline:if not global_ds_key:st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")st.stop()# 验证锁状态if not st.session_state.global_task_running or st.session_state.lock_fd is None:st.error("⚠️ 任务锁异常丢失,请刷新页面后重试。")st.session_state.start_pipeline = Falsest.session_state.resume_pipeline = Falsest.stop()1 unmodified linest.session_state.is_running = Trueis_resume = st.session_state.resume_pipelineagent = SSciPipelineAgent(global_ds_key, global_s2_key)# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_defaulttry:if is_resume:pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:state = json.load(f)topic = state["topic"]keywords = state["keywords"]target_lang = state["target_lang"]words = state["words"]user_data_md = state["user_data_md"]user_lit_context = state["user_lit_context"]agent.load_state(state["agent_state"])adaptive_structure = state["adaptive_structure"]completed_sections = state["completed_sections"]5 unmodified linescontext_tail = state["context_tail"]st.session_state.run_mode = state.get("run_mode", "wizard")APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")else:pb = progress_bar.progress(1, text="⏳ 流水线启动...")user_lit_context = ""user_data_md = ""if st.session_state.run_mode == "wizard":if uploaded_papers_wiz:if len(uploaded_papers_wiz) > 5:st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")uploaded_papers_wiz = uploaded_papers_wiz[:5]user_lit_context = extract_text_from_files(uploaded_papers_wiz)if uploaded_data_wiz:user_data_md = extract_data_from_files(uploaded_data_wiz)elif st.session_state.run_mode == "clone":if uploaded_reference_clone:reference_paper_text = extract_text_from_files([uploaded_reference_clone])if uploaded_data_clone:user_data_md = extract_data_from_files(uploaded_data_clone)if uploaded_core_papers_clone:if len(uploaded_core_papers_clone) > 5:st.warning("⚠��� 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")3 unmodified linesif not user_data_md:with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()user_data_md = sim_md_promptst.info(sim_msg)state = {4 unmodified lines}pb.progress(5, text="🕵️ 引擎配置与范式路由...")if st.session_state.run_mode == "wizard":if "AMJ" in prompt_style_ui:APP_CONFIG.update(AMJ_PROMPTS)1 unmodified lineelse:APP_CONFIG.update(GENERIC_PROMPTS)st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTSclone_metadata = {}9 unmodified linesrender_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)if len(agent.citation_map) < 50:st.warning(f"⚠️ 仅检索到 {len(agent.citation_map)} 篇文献,低于推荐的 50 篇。")col_cont, col_stop = st.columns(2)with col_cont:if not st.button("▶️ 继续生成(文献可能不足)"):st.stop()with col_stop:if st.button("⏹️ 终止任务"):st.stop()# 用户点击继续后,代码继续执行else:st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")9 unmodified linespb.progress(12, text="🧠 文献综合...")synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)state["synthesis_result"] = synthesis_resultpb.progress(14, text="⚓ 生成锚点...")abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)agent.global_memory["abstract_anchor"] = abstract_anchoragent.global_memory["conclusion_anchor"] = conclusion_anchorpb.progress(15, text="📝 大纲设计...")plan = agent.generate_outline(topic, keywords, synthesis_result)en_topic = str(plan.get("en_topic", topic))en_keywords_raw = plan.get("en_keywords", keywords)if isinstance(en_keywords_raw, list):en_keywords_raw = "; ".join([str(k) for k in en_keywords_raw])else:en_keywords_raw = str(en_keywords_raw)# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成structure = plan.get("structure", [])clean_structure = [sec for sec in structureif sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST]structure = clean_structure1 unmodified line# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()en_abstract_clean = clean_markdown_headings(en_abstract_raw)trans_abstract_raw = agent.call_deepseek(f"Translate the following abstract into {target_lang}. Output ONLY translated text without prefix.", abstract_anchor, max_tokens=1500)trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)17 unmodified linesadaptive_structure.append({"section": sec_name, "display_name": f"{sec_name} (Part {i+1}/{num_chunks})", "target_words": int(target_sec_words/num_chunks), "is_first": i==0, "is_method_or_result": is_method_or_result})else:adaptive_structure.append({"section": sec_name, "display_name": sec_name, "target_words": target_sec_words, "is_first": True, "is_method_or_result": is_method_or_result})state["adaptive_structure"] = adaptive_structurestate["agent_state"] = agent.export_state()state["full_draft_en"] = full_draft_enstate["full_draft_translated"] = full_draft_translatedcompleted_sections = []context_tail = ""with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:json.dump(state, f, ensure_ascii=False)2 unmodified linesst.markdown("---")ui_blocks = []target_flag = FLAG_MAP.get(target_lang, "🌐")for sec in adaptive_structure:display_name = sec["display_name"]st.markdown(f"### ⚙️ {display_name}")4 unmodified lineswith col_trans:st.markdown(f"#### {target_flag} 翻译初稿")trans_ph = st.empty()if display_name in completed_sections:en_ph.success("✅ 已从快照安全恢复并拼接")trans_ph.success("✅ 已从快照安全恢复并拼接")11 unmodified linesallocation_map = {}current_cite_idx = 0for idx, vc in enumerate(valid_chunks):if idx == len(valid_chunks) - 1:allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx:]else:num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]current_cite_idx += num_citesfor i, block in enumerate(ui_blocks):if generation_aborted:breaksec = block["sec"]en_ph = block["en_ph"]trans_ph = block["trans_ph"]sec_title = sec["section"]display_name = sec["display_name"]if display_name in completed_sections:remaining_sections -= 1continueremaining_sections -= 1adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)if is_quarantined:quarantine_rule = "【CRITICAL】: NO IN-TEXT CITATIONS ALLOWED IN THIS SECTION."else:assigned_keys = allocation_map.get(display_name, [])assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容heading_instruction = f"Write the content for the section '{sec_title}'. DO NOT output the main heading '# {sec_title}' itself, start directly with the content or subheadings."memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""1 unmodified lineupper_bound = int(adjusted_target * 1.1)lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)adaptive_heading_rule = ""if adjusted_target > 800:adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."17 unmodified linesfor target_key in clone_metadata.keys():target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))if "result" in target_words:target_words.add("analysis")if "result" in sec_words:sec_words.add("analysis")if target_words & sec_words:is_clone_target = Trueactive_clone_key = target_keybreak1 unmodified lineif is_clone_target:meta = clone_metadata[active_clone_key]sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."base_user = f"""[CLONE MODE ACTIVATED - TARGET: {sec_title}]Mimic the academic tone, structural flow, and sentence patterns of this reference template:9 unmodified linesYour previous section ended with: "...{context_tail}..."Write a natural, smooth transitional opening sentence to bridge this."""if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]You are writing an empirical section. YOU ARE ABSOLUTELY FORBIDDEN from using any exact numbers (R-square, p-values, sample sizes, beta coefficients) found in the <REFERENCE_TEMPLATE_SNIPPET>.4 unmodified linesextra_directives = []lower_sec = sec_title.lower()golden_meta = agent.global_memory.get("core_golden_metadata", [])targeted_directives = APP_CONFIG.get("targeted_directives", {})if golden_meta:if any(kw in lower_sec for kw in ["introduction", "background"]):extra_directives.append(targeted_directives.get("introduction", "【TARGETED DIRECTIVE: INTRODUCTION】"))elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):extra_directives.append(targeted_directives.get("literature", "【TARGETED DIRECTIVE: LITERATURE & HYPOTHESES】"))elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):extra_directives.append(targeted_directives.get("methodology", "【TARGETED DIRECTIVE: METHODOLOGY】"))elif any(kw in lower_sec for kw in ["result", "analysis"]):extra_directives.append(targeted_directives.get("results", "【TARGETED DIRECTIVE: RESULTS - ZERO HALLUCINATION】"))elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):extra_directives.append(targeted_directives.get("discussion", "【TARGETED DIRECTIVE: DISCUSSION & CONCLUSION】"))else:extra_directives.append(APP_CONFIG["deep_refinement_directive"])else:3 unmodified linesif any(kw in lower_sec for kw in ["theory", "theoretical", "hypothesis", "introduction"]):extra_directives.append(APP_CONFIG["deep_synthesis_directive"])extra_directives.append(APP_CONFIG["hypothesis_development_directive"])if "discussion" in lower_sec:extra_directives.append(APP_CONFIG["discussion_depth_directive"])if "conclusion" in lower_sec:extra_directives.append(APP_CONFIG["conclusion_anchor_directive"])theory_injection = "\n\n".join(extra_directives)sys_prompt_m3 = APP_CONFIG["sys_academic_writer"] + "\n" + APP_CONFIG["deep_refinement_directive"]wiz_data_injection = f"\n<USER_ACTUAL_DATA>\n{user_data_md}\n</USER_ACTUAL_DATA>\n" if user_data_md and sec["is_method_or_result"] else ""base_user = f"""Generate a polished section '{display_name}'.{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}2 unmodified linestotal_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)if total_tokens > 60000:base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")try:en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Pythonen_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()# 统一由 Python 在第一部分拼接大标题if sec["is_first"]:en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)en_ph.markdown(en_resolved)full_draft_en += en_resolved + "\n\n"agent._extract_memory_from_text(en_draft_clean, sec_title)words_tail = en_draft_clean.split()context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_clean# 使用自适应字数统计actual_words = count_words_adaptive(en_draft_clean, lang_hint)accumulated_deviation += (actual_words - adjusted_target)st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")current_step += 1pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")except Exception as e:5 unmodified linesrender_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")trans_ph.empty()try:trans_chunk_raw = trans_ph.write_stream(agent.stream_deepseek(f"Translate into {target_lang}. Preserve formatting and [CITE-XX] tags.", f"TEXT:\n{en_draft_clean}", max_tokens=6000, model_name="deepseek-chat"))trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)6 unmodified linesst.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")generation_aborted = Truebreakstate["completed_sections"].append(display_name)state["full_draft_en"] = full_draft_enstate["full_draft_translated"] = full_draft_translatedstate["context_tail"] = context_tailstate["agent_state"] = agent.export_state()with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:json.dump(state, f, ensure_ascii=False)if not generation_aborted and full_draft_en.strip():pb.progress(96, text="📦 打包DOCX...")# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])total_words_en = count_words_adaptive(full_draft_en, "en")target_words = int(words)lower_limit = int(target_words * 0.95)upper_limit = int(target_words * 1.05)st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")if total_words_en > upper_limit:st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)6 unmodified linesif compressed_trans:trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)if trans_match:full_draft_translated = full_draft_translated.replace(trans_match.group(1), compressed_trans.strip())else:full_draft_translated += "\n\n" + compressed_trans.strip()total_words_en = count_words_adaptive(full_draft_en, "en")st.success(f"✅ 精简完成,现总字数: {total_words_en}")elif total_words_en < lower_limit:st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")expanded_en = agent.call_deepseek("Continue the conclusion by adding 100-200 words of academically substantive content (future research/limitations).", full_draft_en[-min(2000, len(full_draft_en)):], max_tokens=800)if expanded_en:full_draft_en += "\n\n" + expanded_en.strip()expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)if expanded_trans:full_draft_translated += "\n\n" + expanded_trans.strip()total_words_en = count_words_adaptive(full_draft_en, "en")st.success(f"✅ 扩展完成,现总字数: {total_words_en}")if len(agent.used_citations) < 50:unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]for tag in unused[:50 - len(agent.used_citations)]:agent.used_citations.add(tag)used_tags = sorted(list(agent.used_citations))raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]unique_refs = sorted(list(set(raw_refs)))10 unmodified lineszip_buffer.seek(0)st.session_state.zip_buffer = zip_buffer.getvalue()st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"if os.path.exists(CHECKPOINT_FILE):os.remove(CHECKPOINT_FILE)pb.progress(100, text="✅ 完成")render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")except Exception as e:st.error(f"🚨 启动/恢复异常: {e}")finally:# 释放文件锁lock_fd = st.session_state.get("lock_fd", None)if lock_fd:release_global_lock(lock_fd)st.session_state.lock_fd = Nonest.session_state.global_task_running = Falsest.session_state.is_running = Falsest.session_state.start_pipeline = Falsest.session_state.resume_pipeline = False19 unmodified lines20212223242526272829303 unmodified lines34353637383940414243444546474811 unmodified lines606162636465666768697071727374757677787915 unmodified lines95969798991001011021031041051061071083 unmodified lines1121131141151161171184 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815927 unmodified lines1871881891901911921931941951961971981993 unmodified lines20320420520620720820923 unmodified lines23323423523623723823924024124224324424521 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153161 unmodified line31831932032132232332432532632732832933017 unmodified lines3483493503513523533543553563573583593603613621 unmodified line3643653663673683693703713723733743753763773783793803813823833843853865 unmodified lines3923933943953963973983994004014024034044054064074084094104114124134144154164173 unmodified lines4214224234244254264274 unmodified lines4324334344354364374381 unmodified line4404414424434444454469 unmodified lines4564574584594604614624634644659 unmodified lines4754764774784794804814824834844854864874884894904914924934944954964971 unmodified line49950050150250350450517 unmodified lines5235245255265275285295305315325335345355362 unmodified lines5395405415425435445454 unmodified lines55055155255355455555611 unmodified lines5685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066071 unmodified line60961061161261361461517 unmodified lines6336346356366376386396406416426431 unmodified line6456466476486496506519 unmodified lines6616626636646656666674 unmodified lines6726736746756766776786796806816826836846856866876886893 unmodified lines6936946956966976986997007017027037047057062 unmodified lines7097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407415 unmodified lines7477487497507517527536 unmodified lines7607617627637647657667677687697707717727737747757767777787797807817827837847857867876 unmodified lines79479579679779879980080180280380480580680780880981081181281381481581681710 unmodified lines82882983083183283383483583683783883984084184284384484519 unmodified linesfrom datetime import datetime, timezone, timedeltaimport pandas as pdimport numpy as npimport threading# 🚨 核心修复:修正幽灵导入,统一从 config.py 读取from config import APP_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTSfrom utils.file_parser import extract_text_from_files, extract_data_from_filesfrom utils.docx_builder import text_to_docxfrom core.pipeline_agent import SSciPipelineAgent3 unmodified linesos.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码 (统一从 APP_CONFIG 读取)# 提供默认备用集以防 config.py 暂未更新default_meta_sections = {"abstract", "keyword", "keywords", "摘要", "关键词", "关键字","reference", "references", "reference list", "参考文献","acknowledgment", "acknowledgements", "致谢","аннотация", "ключевые слова", "түйіндеме", "кілт сөздер"}META_SECTIONS_BLACKLIST = set(APP_CONFIG.get("blacklists", {}).get("meta_sections", default_meta_sections))# 🏗️ 架构重构 2:顶层纯函数提取,避免正则灾难性回溯def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):11 unmodified linesglobal_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")if not global_ds_key:try: global_ds_key = st.secrets.get("DEEPSEEK_API_KEY", "")except: passglobal_s2_key = os.environ.get("S2_API_KEY", "")if not global_s2_key:try: global_s2_key = st.secrets.get("S2_API_KEY", "")except: pass# 状态机:断点续传工作区配置 (消除硬编码)WORKSPACE_DIR = APP_CONFIG.get("workspace_dir", ".workspace")CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")if not os.path.exists(WORKSPACE_DIR):os.makedirs(WORKSPACE_DIR, exist_ok=True)# 微信拦截与提示WECHAT_BLOCKER_JS = """<script>15 unmodified linescomponents.html(WECHAT_BLOCKER_JS, height=0, width=0)# ==========================================# 🚨 访问控制与全局并发锁 (Global Mutex)# ==========================================def check_password():expected_password = os.environ.get("APP_PASSWORD", "")if not expected_password:try: expected_password = st.secrets.get("APP_PASSWORD", "")except: passif not expected_password:return True3 unmodified linesif not st.session_state["password_correct"]:st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)st.markdown("<p style='text-align: center;'>本系统为高���力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)pwd = st.text_input("Access Token", type="password", key="pwd_input")if st.button("Unlock"):if pwd == expected_password:4 unmodified linesst.stop()return True@st.cache_resourcedef get_global_lock():return threading.Lock()check_password()global_lock = get_global_lock()# 🚨 核心修复:防死锁强制释放机制with st.sidebar:st.markdown("### 🛠️ 系统维护")if st.button("🚨 强制释放全局并发锁", help="当系统遭遇意外死锁时,点击此按钮强制重置状态。"):if global_lock.locked():global_lock.release()st.session_state.is_running = Falsest.session_state.start_pipeline = Falsest.session_state.resume_pipeline = Falsest.success("✅ 全局锁已强制释放!您可以重新开始生成了。")time.sleep(1)st.rerun()# ==========================================# 1. 鲁棒的蒙特卡洛实证模拟引擎# ==========================================def generate_psd_corr_matrix(n_constructs, max_corr=0.5):if n_constructs == 1: return np.array([[1.0]])base_corr = np.random.uniform(0.2, max_corr - 0.1)A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))A = (A + A.T) / 2np.fill_diagonal(A, 1.0)min_eig = np.min(np.linalg.eigvals(A))if min_eig < 0: A -= (min_eig - 0.01) * np.eye(n_constructs)d = np.sqrt(np.diag(A))return A / np.outer(d, d)27 unmodified linestarget_std = scale_points / 5.0for idx, c_name in enumerate(construct_names):true_score = latent_scores[:, idx]n_items = np.random.randint(3, 6)loadings = np.random.uniform(0.72, 0.88, n_items)true_loadings[c_name] = loadingsitem_names = []for i, load in enumerate(loadings):error = np.random.normal(0, np.sqrt(1 - load**2), n)item_score = load * true_score + errorraw_scaled = item_score * target_std + target_meanitem_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)col_name = f"{c_name}_{i+1}"3 unmodified linesdf = pd.DataFrame(data)validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})fl_matrix = mean_scores.corr().astype(object)for i, row in validity_df.iterrows():c_name = row['Construct']sqrt_ave = np.sqrt(row['AVE'])23 unmodified linesreturn df, simulated_md_prompt, status_msg# ==========================================# 2. UI 界面布局与初始化# ==========================================if "is_running" not in st.session_state: st.session_state.is_running = Falseif "start_pipeline" not in st.session_state: st.session_state.start_pipeline = Falseif "resume_pipeline" not in st.session_state: st.session_state.resume_pipeline = Falseif "zip_buffer" not in st.session_state: st.session_state.zip_buffer = Noneif "run_mode" not in st.session_state: st.session_state.run_mode = "wizard"lang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]21 unmodified lineswith tab_wizard:st.markdown("### 🛠️ 人在环路:研究材料配置")prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",options=["工商管理实证研究 (AMJ Style)", "通用学术规范 (Generic Style)"],index=0, disabled=st.session_state.is_running)uploaded_papers_wiz = st.file_uploader("2. 上传核心参考论文 (可选,支持 PDF/DOCX,建议1-5篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, disabled=st.session_state.is_running)uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):if not global_lock.acquire(blocking=False):st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。为了保证系统稳定,请大约 5-10 分钟后再试。")else:global_lock.release()st.session_state.run_mode = "wizard"st.session_state.start_pipeline = Truest.rerun()with tab_clone:st.markdown("### 🧬 高级克隆:骨架与风格复刻")context_differences = st.text_area("1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",max_chars=2000,disabled=st.session_state.is_running)if "extracted_sections" not in st.session_state:st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]if "last_uploaded_clone_ref" not in st.session_state:st.session_state.last_uploaded_clone_ref = Noneuploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)if uploaded_reference_clone and global_ds_key:if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)ref_text_raw = extract_text_from_files([uploaded_reference_clone])dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)st.session_state.extracted_sections = dynamic_sectionsst.session_state.last_uploaded_clone_ref = uploaded_reference_clone.namest.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)uploaded_core_papers_clone = st.file_uploader("4. 上传核心理论参考论文 (可选,用于提升理论深度,建议1-5篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, key="clone_core_papers", disabled=st.session_state.is_running)if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):1 unmodified linest.error("🚨 启动克隆模式必须填写研究背景与核心差异!")elif not uploaded_reference_clone:st.error("🚨 启动克隆模式必须上传范例论文!")elif not global_lock.acquire(blocking=False):st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请大约 5-10 分钟后再试。")else:global_lock.release()st.session_state.run_mode = "clone"st.session_state.start_pipeline = Truest.rerun()progress_bar = st.empty()monitor_ui = st.empty()17 unmodified linesFLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}# ==========================================# 3. 后台流水线执行# ==========================================if st.session_state.start_pipeline or st.session_state.resume_pipeline:if not global_ds_key:st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")st.stop()if not global_lock.acquire(blocking=False):st.warning("⚠️ 糟糕!在您点击的一瞬间,系统刚好被抢占了。请稍后重试。")st.session_state.start_pipeline = Falsest.session_state.resume_pipeline = Falsest.stop()1 unmodified linest.session_state.is_running = Trueis_resume = st.session_state.resume_pipelineagent = SSciPipelineAgent(global_ds_key, global_s2_key)# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_defaulttry:if is_resume:pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:state = json.load(f)topic = state["topic"]keywords = state["keywords"]target_lang = state["target_lang"]words = state["words"]user_data_md = state["user_data_md"]user_lit_context = state["user_lit_context"]agent.load_state(state["agent_state"])adaptive_structure = state["adaptive_structure"]completed_sections = state["completed_sections"]5 unmodified linescontext_tail = state["context_tail"]st.session_state.run_mode = state.get("run_mode", "wizard")APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")else:pb = progress_bar.progress(1, text="⏳ 流水线启动...")user_lit_context = ""user_data_md = ""if st.session_state.run_mode == "wizard":if uploaded_papers_wiz:if len(uploaded_papers_wiz) > 5:st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")uploaded_papers_wiz = uploaded_papers_wiz[:5]user_lit_context = extract_text_from_files(uploaded_papers_wiz)if uploaded_data_wiz: user_data_md = extract_data_from_files(uploaded_data_wiz)elif st.session_state.run_mode == "clone":if uploaded_reference_clone: reference_paper_text = extract_text_from_files([uploaded_reference_clone])if uploaded_data_clone: user_data_md = extract_data_from_files(uploaded_data_clone)if uploaded_core_papers_clone:if len(uploaded_core_papers_clone) > 5:st.warning("⚠��� 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")3 unmodified linesif not user_data_md:with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()user_data_md = sim_md_promptst.info(sim_msg)state = {4 unmodified lines}pb.progress(5, text="🕵️ 引擎配置与范式路由...")if st.session_state.run_mode == "wizard":if "AMJ" in prompt_style_ui:APP_CONFIG.update(AMJ_PROMPTS)1 unmodified lineelse:APP_CONFIG.update(GENERIC_PROMPTS)st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTSclone_metadata = {}9 unmodified linesrender_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)if len(agent.citation_map) < 50:st.error(f"🚨 终止生成:系统已触发最大轮次的【主题自动泛化与补充策略】,最终仅整合到 {len(agent.citation_map)} 篇有效文献,未达到 50 篇最低要求。")st.stop()else:st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")9 unmodified linespb.progress(12, text="🧠 文献综合...")synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)state["synthesis_result"] = synthesis_resultpb.progress(14, text="⚓ 生成锚点...")abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)agent.global_memory["abstract_anchor"] = abstract_anchoragent.global_memory["conclusion_anchor"] = conclusion_anchorpb.progress(15, text="📝 大纲设计...")plan = agent.generate_outline(topic, keywords, synthesis_result)en_topic = str(plan.get("en_topic", topic))en_keywords_raw = plan.get("en_keywords", keywords)if isinstance(en_keywords_raw, list): en_keywords_raw = "; ".join([str(k) for k in en_keywords_raw])else: en_keywords_raw = str(en_keywords_raw)# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成structure = plan.get("structure", [])clean_structure = [sec for sec in structureif sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST]structure = clean_structure1 unmodified line# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()en_abstract_clean = clean_markdown_headings(en_abstract_raw)trans_abstract_raw = agent.call_deepseek(f"Translate the following abstract into {target_lang}. Output ONLY translated text without prefix.", abstract_anchor, max_tokens=1500)trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)17 unmodified linesadaptive_structure.append({"section": sec_name, "display_name": f"{sec_name} (Part {i+1}/{num_chunks})", "target_words": int(target_sec_words/num_chunks), "is_first": i==0, "is_method_or_result": is_method_or_result})else:adaptive_structure.append({"section": sec_name, "display_name": sec_name, "target_words": target_sec_words, "is_first": True, "is_method_or_result": is_method_or_result})state["adaptive_structure"] = adaptive_structurestate["agent_state"] = agent.export_state()state["full_draft_en"] = full_draft_enstate["full_draft_translated"] = full_draft_translatedcompleted_sections = []context_tail = ""with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:json.dump(state, f, ensure_ascii=False)2 unmodified linesst.markdown("---")ui_blocks = []target_flag = FLAG_MAP.get(target_lang, "🌐")for sec in adaptive_structure:display_name = sec["display_name"]st.markdown(f"### ⚙️ {display_name}")4 unmodified lineswith col_trans:st.markdown(f"#### {target_flag} 翻译初稿")trans_ph = st.empty()if display_name in completed_sections:en_ph.success("✅ 已从快照安全恢复并拼接")trans_ph.success("✅ 已从快照安全恢复并拼接")11 unmodified linesallocation_map = {}current_cite_idx = 0for idx, vc in enumerate(valid_chunks):if idx == len(valid_chunks) - 1: allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx:]else:num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]current_cite_idx += num_citesfor i, block in enumerate(ui_blocks):if generation_aborted: breaksec = block["sec"]; en_ph = block["en_ph"]; trans_ph = block["trans_ph"]sec_title = sec["section"]; display_name = sec["display_name"]if display_name in completed_sections:remaining_sections -= 1continueremaining_sections -= 1adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)if is_quarantined: quarantine_rule = "【CRITICAL】: NO IN-TEXT CITATIONS ALLOWED IN THIS SECTION."else:assigned_keys = allocation_map.get(display_name, [])assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容heading_instruction = f"Write the content for the section '{sec_title}'. DO NOT output the main heading '# {sec_title}' itself, start directly with the content or subheadings."memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""1 unmodified lineupper_bound = int(adjusted_target * 1.1)lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)adaptive_heading_rule = ""if adjusted_target > 800:adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."17 unmodified linesfor target_key in clone_metadata.keys():target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))if "result" in target_words: target_words.add("analysis")if "result" in sec_words: sec_words.add("analysis")if target_words & sec_words:is_clone_target = Trueactive_clone_key = target_keybreak1 unmodified lineif is_clone_target:meta = clone_metadata[active_clone_key]sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."base_user = f"""[CLONE MODE ACTIVATED - TARGET: {sec_title}]Mimic the academic tone, structural flow, and sentence patterns of this reference template:9 unmodified linesYour previous section ended with: "...{context_tail}..."Write a natural, smooth transitional opening sentence to bridge this."""if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]You are writing an empirical section. YOU ARE ABSOLUTELY FORBIDDEN from using any exact numbers (R-square, p-values, sample sizes, beta coefficients) found in the <REFERENCE_TEMPLATE_SNIPPET>.4 unmodified linesextra_directives = []lower_sec = sec_title.lower()golden_meta = agent.global_memory.get("core_golden_metadata", [])if golden_meta:if any(kw in lower_sec for kw in ["introduction", "background"]):extra_directives.append("【TARGETED DIRECTIVE: INTRODUCTION】\n你必须审视 [TARGETED INJECTION] 中列出的核心文献的局限性与未来展望 (Future Gaps)。禁止泛泛而谈研究背景。你必须将本研究定位为对这些明确 Gaps 的直接回应,建立极强的学术对话感。")elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):extra_directives.append("【TARGETED DIRECTIVE: LITERATURE & HYPOTHESES】\n严禁简单罗列前人观点或凭空捏造机制。你必须明确使用 [TARGETED INJECTION] 中提供的理论视角 (Theoretical Lens) 作为推导的底层逻辑。你的论证过程必须引用这些核心文献已验证的因果路径,说明新假设是如何在它们的肩膀上向前推演的。")elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):extra_directives.append("【TARGETED DIRECTIVE: METHODOLOGY】\n在撰写测量工具 (Measures) 时,你必须明确声明我们的问卷题项改编自 [TARGETED INJECTION] 中记录的核心文献,以此证明量表具有极高的历史信度与效度。将注入�� Items 自然融入行文中。")elif any(kw in lower_sec for kw in ["result", "analysis"]):extra_directives.append("【TARGETED DIRECTIVE: RESULTS - ZERO HALLUCINATION】\n【绝对数据忠诚指令】你现在是一个没有感情的统计报告员。1. 必须逐字逐句将 <USER_ACTUAL_DATA> 翻译为规范的学术段落。2. 绝对禁止生成任何表格中不存在的 P值、T值或 R²。3. 必须逐一核对 【ESTABLISHED HYPOTHESES】,并在段末明确写出判定 (如 'H1 is supported')。禁止在此进行理论探讨。")elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):extra_directives.append("【TARGETED DIRECTIVE: DISCUSSION & CONCLUSION】\n【理论回声与升华指令】本章是全篇灵魂。1. 不要简单重复结果,必须将本研究成立的假设与 [TARGETED INJECTION] 中核心文献的发现进行结构化对比,指出是印证了前人还是得出了矛盾/新边界。2. 基于对比提供高度可操作的管理启示。3. 诚实反思局限并提供具体研究方向。")else:extra_directives.append(APP_CONFIG["deep_refinement_directive"])else:3 unmodified linesif any(kw in lower_sec for kw in ["theory", "theoretical", "hypothesis", "introduction"]):extra_directives.append(APP_CONFIG["deep_synthesis_directive"])extra_directives.append(APP_CONFIG["hypothesis_development_directive"])if "discussion" in lower_sec: extra_directives.append(APP_CONFIG["discussion_depth_directive"])if "conclusion" in lower_sec: extra_directives.append(APP_CONFIG["conclusion_anchor_directive"])theory_injection = "\n\n".join(extra_directives)sys_prompt_m3 = APP_CONFIG["sys_academic_writer"] + "\n" + APP_CONFIG["deep_refinement_directive"]wiz_data_injection = f"\n<USER_ACTUAL_DATA>\n{user_data_md}\n</USER_ACTUAL_DATA>\n" if user_data_md and sec["is_method_or_result"] else ""base_user = f"""Generate a polished section '{display_name}'.{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}2 unmodified linestotal_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)if total_tokens > 60000:base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")try:en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Pythonen_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()# 统一由 Python 在第一部分拼接大标题if sec["is_first"]:en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)en_ph.markdown(en_resolved)full_draft_en += en_resolved + "\n\n"agent._extract_memory_from_text(en_draft_clean, sec_title)words_tail = en_draft_clean.split()context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_cleanactual_words = len(en_draft_clean.split())accumulated_deviation += (actual_words - adjusted_target)st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")current_step += 1pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")except Exception as e:5 unmodified linesrender_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")trans_ph.empty()try:# 此时的 en_draft_clean 已经包含了 Python 安全注入的 `# 标题`,翻译节点会原封不动地将其平滑译出trans_chunk_raw = trans_ph.write_stream(agent.stream_deepseek(f"Translate into {target_lang}. Preserve formatting and [CITE-XX] tags.", f"TEXT:\n{en_draft_clean}", max_tokens=6000, model_name="deepseek-chat"))trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)6 unmodified linesst.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")generation_aborted = Truebreakstate["completed_sections"].append(display_name)state["full_draft_en"] = full_draft_enstate["full_draft_translated"] = full_draft_translatedstate["context_tail"] = context_tailstate["agent_state"] = agent.export_state()with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:json.dump(state, f, ensure_ascii=False)if not generation_aborted and full_draft_en.strip():pb.progress(96, text="📦 打包DOCX...")# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])total_words_en = len(full_draft_en.split())target_words = int(words)lower_limit = int(target_words * 0.95); upper_limit = int(target_words * 1.05)st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")if total_words_en > upper_limit:st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)6 unmodified linesif compressed_trans:trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)if trans_match: full_draft_translated = full_draft_translated.replace(trans_match.group(1), compressed_trans.strip())else: full_draft_translated += "\n\n" + compressed_trans.strip()total_words_en = len(full_draft_en.split())st.success(f"✅ 精简完成,现总字数: {total_words_en}")elif total_words_en < lower_limit:st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")expanded_en = agent.call_deepseek("Continue the conclusion by adding 100-200 words of academically substantive content (future research/limitations).", full_draft_en[-min(2000, len(full_draft_en)):], max_tokens=800)if expanded_en:full_draft_en += "\n\n" + expanded_en.strip()expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)if expanded_trans: full_draft_translated += "\n\n" + expanded_trans.strip()total_words_en = len(full_draft_en.split())st.success(f"✅ 扩展完成,现总字数: {total_words_en}")if len(agent.used_citations) < 50:unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]for tag in unused[:50 - len(agent.used_citations)]: agent.used_citations.add(tag)used_tags = sorted(list(agent.used_citations))raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]unique_refs = sorted(list(set(raw_refs)))10 unmodified lineszip_buffer.seek(0)st.session_state.zip_buffer = zip_buffer.getvalue()st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"if os.path.exists(CHECKPOINT_FILE):os.remove(CHECKPOINT_FILE)pb.progress(100, text="✅ 完成")render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")except Exception as e:st.error(f"🚨 启动/恢复异常: {e}")finally:if global_lock.locked():global_lock.release()st.session_state.is_running = Falsest.session_state.start_pipeline = Falsest.session_state.resume_pipeline = False
app.py+172-253