Spaces:
Sleeping
Sleeping
Update app.py
Browse files19 unmodified lines2021222324252627282930315 unmodified lines373839404142434413 unmodified lines585960616263646566676869702 unmodified lines73747576777879804 unmodified lines8586878889909145 unmodified lines1371381391401411421431441453 unmodified lines14915015115215315415510 unmodified lines16616716816917017117217317417517617717827 unmodified lines2062072082092102112122132142152162172183 unmodified lines22222322422522622722825 unmodified lines25425525625725825926026126226326426526621 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373382 unmodified lines34134234334434534634734834935035135235335417 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244255 unmodified lines4314324334344354364374384394404414424434444454464474484494504514524534544554563 unmodified lines4604614624634644654664 unmodified lines4714724734744754764771 unmodified line4794804814824834844859 unmodified lines4954964974984995005015025035049 unmodified lines5145155165175185195205215225235245255265275285295305315325335345355361 unmodified line53853954054154254354417 unmodified lines5625635645655665675685695705715725735745752 unmodified lines5785795805815825835844 unmodified lines58959059159259359459511 unmodified lines6076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456461 unmodified line64864965065165265365417 unmodified lines6726736746756766776786796806816821 unmodified line6846856866876886896909 unmodified lines7007017027037047057064 unmodified lines7117127137147157167177187197207217227237247257267277283 unmodified lines7327337347357367377387397407417427437447452 unmodified lines7487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797805 unmodified lines7867877887897907917926 unmodified lines7998008018028038048058068078088098108118128138148158168178188198208218228238248258266 unmodified lines8338348358368378388398408411 unmodified line84384484584684784884985085185285385485585610 unmodified lines86786886987087187287387487587687787887988088188288388488588688719 unmodified linesfrom datetime import datetime, timezone, timedeltaimport pandas as pdimport numpy as npimport fcntl # 文件锁,用于跨进程互斥import atexit # 注册退出清理函数# 然后再引入本地模块from app_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 SSciPipelineAgent5 unmodified lines# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码META_SECTIONS_BLACKLIST = {"abstract", "keyword", "keywords", "摘要", "关键词", "关键字","reference", "references", "reference list", "参考文献","acknowledgment", "acknowledgements", "致谢"}13 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"2 unmodified linesif not os.path.exists(WORKSPACE_DIR):os.makedirs(WORKSPACE_DIR, exist_ok=True)# ------------------------- 文件锁工具函数 (替换 threading.Lock) -------------------------def acquire_task_lock():"""尝试获取全局任务锁,返回 (是否成功, 锁文件句柄)"""try:lock_fd = open(TASK_LOCK_FILE, 'w')4 unmodified lineslock_fd.close()return False, Nonedef release_task_lock(lock_fd):"""释放任务锁并关闭文件"""if lock_fd:try:45 unmodified linesdef 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:10 unmodified lines# 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'])25 unmodified lines# ==========================================# 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 "task_lock_fd" not in st.session_state: st.session_state.task_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"):acquired, lock_fd = acquire_task_lock()if not acquired:st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")else:st.session_state.task_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"):2 unmodified lineselif not uploaded_reference_clone:st.error("🚨 启动克隆模式必须上传范例论文!")else:acquired, lock_fd = acquire_task_lock()if not acquired:st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")else:st.session_state.task_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()# 检查任务锁是否有效持有lock_fd = st.session_state.get("task_lock_fd", None)if not lock_fd:st.error("⚠️ 任务锁丢失,请刷新页面后重试。")st.session_state.start_pipeline = Falsest.session_state.resume_pipeline = Falsest.stop()# 二次验证锁是否仍被本进程持有try:fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)# 若能再次获取,说明原锁已失效,立即释放并报错fcntl.flock(lock_fd, fcntl.LOCK_UN)st.error("⚠️ 任务锁异常丢失,请刷新页面后重试。")st.session_state.start_pipeline = Falsest.session_state.resume_pipeline = Falsest.stop()except BlockingIOError:# 正常:锁仍被本进程持有passst.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...")1 unmodified lineif 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:# 释放文件锁lock_fd = st.session_state.get("task_lock_fd", None)if lock_fd:release_task_lock(lock_fd)st.session_state.task_lock_fd = Nonest.session_state.is_running = Falsest.session_state.start_pipeline = Falsest.session_state.resume_pipeline = False19 unmodified lines2021222324252627282930315 unmodified lines373839404142434413 unmodified lines58596061626364656667686970717273742 unmodified lines77787980818283844 unmodified lines8990919293949545 unmodified lines1411421431441451461471481491501513 unmodified lines15515615715815916016110 unmodified lines17217317417517617717817918018118218318418518627 unmodified lines2142152162172182192202212222232242252263 unmodified lines23023123223323423523625 unmodified lines26226326426526626726826927027127227327427527627727827928028128221 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573582 unmodified lines36136236336436536636736836937037137237337437537637737817 unmodified lines3963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344355 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 lines8678688698708718728738748758768771 unmodified line87988088188288388488588688788888989089189289389410 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 SSciPipelineAgent5 unmodified lines# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码META_SECTIONS_BLACKLIST = {"abstract", "keyword", "keywords", "摘要", "关键词", "关键字","reference", "references", "reference list", "参考文献","acknowledgment", "acknowledgements", "致谢"}13 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"2 unmodified linesif 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')4 unmodified lineslock_fd.close()return False, Nonedef release_global_lock(lock_fd):"""释放任务锁并关闭文件"""if lock_fd:try:45 unmodified linesdef 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:10 unmodified lines# 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'])25 unmodified lines# ==========================================# 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"):2 unmodified lineselif 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()st.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...")1 unmodified lineif 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 = False
app.py+200-161