Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,12 +20,12 @@ import json
|
|
| 20 |
from datetime import datetime, timezone, timedelta
|
| 21 |
import pandas as pd
|
| 22 |
import numpy as np
|
| 23 |
-
import fcntl
|
| 24 |
-
import atexit
|
| 25 |
|
| 26 |
# 然后再引入本地模块
|
| 27 |
from app_config import APP_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTS
|
| 28 |
-
from utils.file_parser import extract_text_from_files, extract_data_from_files
|
| 29 |
from utils.docx_builder import text_to_docx
|
| 30 |
from core.pipeline_agent import SSciPipelineAgent
|
| 31 |
|
|
@@ -37,8 +37,8 @@ os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
|
|
| 37 |
|
| 38 |
# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码
|
| 39 |
META_SECTIONS_BLACKLIST = {
|
| 40 |
-
"abstract", "keyword", "keywords", "摘要", "关键词", "关键字",
|
| 41 |
-
"reference", "references", "reference list", "参考文献",
|
| 42 |
"acknowledgment", "acknowledgements", "致谢"
|
| 43 |
}
|
| 44 |
|
|
@@ -58,13 +58,17 @@ def clean_markdown_headings(text):
|
|
| 58 |
|
| 59 |
global_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 60 |
if not global_ds_key:
|
| 61 |
-
try:
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
|
| 64 |
global_s2_key = os.environ.get("S2_API_KEY", "")
|
| 65 |
if not global_s2_key:
|
| 66 |
-
try:
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# 状态机:断点续传工作区配置
|
| 70 |
WORKSPACE_DIR = ".workspace"
|
|
@@ -73,8 +77,8 @@ TASK_LOCK_FILE = os.path.join(WORKSPACE_DIR, "task.lock")
|
|
| 73 |
if not os.path.exists(WORKSPACE_DIR):
|
| 74 |
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 75 |
|
| 76 |
-
# -------------------------
|
| 77 |
-
def
|
| 78 |
"""尝试获取全局任务锁,返回 (是否成功, 锁文件句柄)"""
|
| 79 |
try:
|
| 80 |
lock_fd = open(TASK_LOCK_FILE, 'w')
|
|
@@ -85,7 +89,7 @@ def acquire_task_lock():
|
|
| 85 |
lock_fd.close()
|
| 86 |
return False, None
|
| 87 |
|
| 88 |
-
def
|
| 89 |
"""释放任务锁并关闭文件"""
|
| 90 |
if lock_fd:
|
| 91 |
try:
|
|
@@ -137,9 +141,11 @@ components.html(WECHAT_BLOCKER_JS, height=0, width=0)
|
|
| 137 |
def check_password():
|
| 138 |
expected_password = os.environ.get("APP_PASSWORD", "")
|
| 139 |
if not expected_password:
|
| 140 |
-
try:
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
if not expected_password:
|
| 144 |
return True
|
| 145 |
|
|
@@ -149,7 +155,7 @@ def check_password():
|
|
| 149 |
if not st.session_state["password_correct"]:
|
| 150 |
st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)
|
| 151 |
st.markdown("<p style='text-align: center;'>本系统为高算力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)
|
| 152 |
-
|
| 153 |
pwd = st.text_input("Access Token", type="password", key="pwd_input")
|
| 154 |
if st.button("Unlock"):
|
| 155 |
if pwd == expected_password:
|
|
@@ -166,13 +172,15 @@ check_password()
|
|
| 166 |
# 1. 鲁棒的蒙特卡洛实证模拟引擎 (保持不变)
|
| 167 |
# ==========================================
|
| 168 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 169 |
-
if n_constructs == 1:
|
| 170 |
-
|
|
|
|
| 171 |
A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))
|
| 172 |
A = (A + A.T) / 2
|
| 173 |
np.fill_diagonal(A, 1.0)
|
| 174 |
min_eig = np.min(np.linalg.eigvals(A))
|
| 175 |
-
if min_eig < 0:
|
|
|
|
| 176 |
d = np.sqrt(np.diag(A))
|
| 177 |
return A / np.outer(d, d)
|
| 178 |
|
|
@@ -206,13 +214,13 @@ def generate_empirical_data_robust(construct_names=None, n=300, scale_points=7):
|
|
| 206 |
target_std = scale_points / 5.0
|
| 207 |
for idx, c_name in enumerate(construct_names):
|
| 208 |
true_score = latent_scores[:, idx]
|
| 209 |
-
n_items = np.random.randint(3, 6)
|
| 210 |
loadings = np.random.uniform(0.72, 0.88, n_items)
|
| 211 |
true_loadings[c_name] = loadings
|
| 212 |
item_names = []
|
| 213 |
for i, load in enumerate(loadings):
|
| 214 |
error = np.random.normal(0, np.sqrt(1 - load**2), n)
|
| 215 |
-
item_score = load * true_score + error
|
| 216 |
raw_scaled = item_score * target_std + target_mean
|
| 217 |
item_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)
|
| 218 |
col_name = f"{c_name}_{i+1}"
|
|
@@ -222,7 +230,7 @@ def generate_empirical_data_robust(construct_names=None, n=300, scale_points=7):
|
|
| 222 |
df = pd.DataFrame(data)
|
| 223 |
validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)
|
| 224 |
mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})
|
| 225 |
-
fl_matrix = mean_scores.corr().astype(object)
|
| 226 |
for i, row in validity_df.iterrows():
|
| 227 |
c_name = row['Construct']
|
| 228 |
sqrt_ave = np.sqrt(row['AVE'])
|
|
@@ -254,13 +262,21 @@ def resolve_empirical_data(extracted_vars=None):
|
|
| 254 |
# ==========================================
|
| 255 |
# 2. UI 界面布局与初始化 (保持不变)
|
| 256 |
# ==========================================
|
| 257 |
-
if "is_running" not in st.session_state:
|
| 258 |
-
|
| 259 |
-
if "
|
| 260 |
-
|
| 261 |
-
if "
|
| 262 |
-
|
| 263 |
-
if "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
lang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")
|
| 266 |
ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]
|
|
@@ -288,51 +304,55 @@ tab_wizard, tab_clone = st.tabs(["✨ 智能向导模式 (Smart Wizard)", "🧬
|
|
| 288 |
|
| 289 |
with tab_wizard:
|
| 290 |
st.markdown("### 🛠️ 人在环路:研究材料配置")
|
| 291 |
-
prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",
|
| 292 |
-
options=["工商管理实证研究 (AMJ Style)", "通用学术规范 (Generic Style)"],
|
| 293 |
index=0, disabled=st.session_state.is_running)
|
| 294 |
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)
|
| 295 |
uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)
|
| 296 |
-
|
| 297 |
if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):
|
| 298 |
-
|
| 299 |
-
if not acquired:
|
| 300 |
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 301 |
else:
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
with tab_clone:
|
| 308 |
st.markdown("### 🧬 高级克隆:骨架与风格复刻")
|
| 309 |
context_differences = st.text_area(
|
| 310 |
-
"1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",
|
| 311 |
-
placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",
|
| 312 |
max_chars=2000,
|
| 313 |
disabled=st.session_state.is_running
|
| 314 |
)
|
| 315 |
-
|
| 316 |
if "extracted_sections" not in st.session_state:
|
| 317 |
st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]
|
| 318 |
if "last_uploaded_clone_ref" not in st.session_state:
|
| 319 |
st.session_state.last_uploaded_clone_ref = None
|
| 320 |
|
| 321 |
uploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)
|
| 322 |
-
|
| 323 |
if uploaded_reference_clone and global_ds_key:
|
| 324 |
if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:
|
| 325 |
with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):
|
| 326 |
temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 327 |
ref_text_raw = extract_text_from_files([uploaded_reference_clone])
|
| 328 |
dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)
|
| 329 |
-
|
| 330 |
st.session_state.extracted_sections = dynamic_sections
|
| 331 |
st.session_state.last_uploaded_clone_ref = uploaded_reference_clone.name
|
| 332 |
st.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")
|
| 333 |
-
|
| 334 |
uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)
|
| 335 |
-
|
| 336 |
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)
|
| 337 |
|
| 338 |
if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):
|
|
@@ -341,14 +361,18 @@ with tab_clone:
|
|
| 341 |
elif not uploaded_reference_clone:
|
| 342 |
st.error("🚨 启动克隆模式必须上传范例论文!")
|
| 343 |
else:
|
| 344 |
-
|
| 345 |
-
if not acquired:
|
| 346 |
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 347 |
else:
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
progress_bar = st.empty()
|
| 354 |
monitor_ui = st.empty()
|
|
@@ -372,54 +396,40 @@ def render_monitor(agent, phase, current_sec="", details=""):
|
|
| 372 |
FLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}
|
| 373 |
|
| 374 |
# ==========================================
|
| 375 |
-
# 3. 后台流水线执行 (
|
| 376 |
# ==========================================
|
| 377 |
if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
| 378 |
if not global_ds_key:
|
| 379 |
st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")
|
| 380 |
st.stop()
|
| 381 |
-
|
| 382 |
-
#
|
| 383 |
-
|
| 384 |
-
if not lock_fd:
|
| 385 |
-
st.error("⚠️ 任务锁丢失,请刷新页面后重试。")
|
| 386 |
-
st.session_state.start_pipeline = False
|
| 387 |
-
st.session_state.resume_pipeline = False
|
| 388 |
-
st.stop()
|
| 389 |
-
|
| 390 |
-
# 二次验证锁是否仍被本进程持有
|
| 391 |
-
try:
|
| 392 |
-
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 393 |
-
# 若能再次获取,说明原锁已失效,立即释放并报错
|
| 394 |
-
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
| 395 |
st.error("⚠️ 任务锁异常丢失,请刷新页面后重试。")
|
| 396 |
st.session_state.start_pipeline = False
|
| 397 |
st.session_state.resume_pipeline = False
|
| 398 |
st.stop()
|
| 399 |
-
except BlockingIOError:
|
| 400 |
-
# 正常:锁仍被本进程持有
|
| 401 |
-
pass
|
| 402 |
|
| 403 |
st.session_state.is_running = True
|
| 404 |
is_resume = st.session_state.resume_pipeline
|
| 405 |
agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 406 |
-
|
| 407 |
# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取
|
| 408 |
SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_default
|
| 409 |
-
|
| 410 |
try:
|
| 411 |
if is_resume:
|
| 412 |
pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")
|
| 413 |
with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:
|
| 414 |
state = json.load(f)
|
| 415 |
-
|
| 416 |
topic = state["topic"]
|
| 417 |
keywords = state["keywords"]
|
| 418 |
target_lang = state["target_lang"]
|
| 419 |
words = state["words"]
|
| 420 |
user_data_md = state["user_data_md"]
|
| 421 |
user_lit_context = state["user_lit_context"]
|
| 422 |
-
|
| 423 |
agent.load_state(state["agent_state"])
|
| 424 |
adaptive_structure = state["adaptive_structure"]
|
| 425 |
completed_sections = state["completed_sections"]
|
|
@@ -431,26 +441,29 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 431 |
context_tail = state["context_tail"]
|
| 432 |
st.session_state.run_mode = state.get("run_mode", "wizard")
|
| 433 |
APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))
|
| 434 |
-
|
| 435 |
st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")
|
| 436 |
-
|
| 437 |
else:
|
| 438 |
pb = progress_bar.progress(1, text="⏳ 流水线启动...")
|
| 439 |
-
|
| 440 |
user_lit_context = ""
|
| 441 |
user_data_md = ""
|
| 442 |
-
|
| 443 |
if st.session_state.run_mode == "wizard":
|
| 444 |
if uploaded_papers_wiz:
|
| 445 |
if len(uploaded_papers_wiz) > 5:
|
| 446 |
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
| 447 |
uploaded_papers_wiz = uploaded_papers_wiz[:5]
|
| 448 |
user_lit_context = extract_text_from_files(uploaded_papers_wiz)
|
| 449 |
-
if uploaded_data_wiz:
|
| 450 |
-
|
|
|
|
| 451 |
elif st.session_state.run_mode == "clone":
|
| 452 |
-
if uploaded_reference_clone:
|
| 453 |
-
|
|
|
|
|
|
|
| 454 |
if uploaded_core_papers_clone:
|
| 455 |
if len(uploaded_core_papers_clone) > 5:
|
| 456 |
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
|
@@ -460,7 +473,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 460 |
if not user_data_md:
|
| 461 |
with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):
|
| 462 |
sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()
|
| 463 |
-
user_data_md = sim_md_prompt
|
| 464 |
st.info(sim_msg)
|
| 465 |
|
| 466 |
state = {
|
|
@@ -471,7 +484,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 471 |
}
|
| 472 |
|
| 473 |
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 474 |
-
|
| 475 |
if st.session_state.run_mode == "wizard":
|
| 476 |
if "AMJ" in prompt_style_ui:
|
| 477 |
APP_CONFIG.update(AMJ_PROMPTS)
|
|
@@ -479,7 +492,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 479 |
else:
|
| 480 |
APP_CONFIG.update(GENERIC_PROMPTS)
|
| 481 |
st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")
|
| 482 |
-
|
| 483 |
state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTS
|
| 484 |
|
| 485 |
clone_metadata = {}
|
|
@@ -495,10 +508,17 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 495 |
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")
|
| 496 |
|
| 497 |
refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)
|
| 498 |
-
|
| 499 |
if len(agent.citation_map) < 50:
|
| 500 |
-
st.
|
| 501 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
else:
|
| 503 |
st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 504 |
|
|
@@ -514,23 +534,25 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 514 |
pb.progress(12, text="🧠 文献综合...")
|
| 515 |
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 516 |
state["synthesis_result"] = synthesis_result
|
| 517 |
-
|
| 518 |
pb.progress(14, text="⚓ 生成锚点...")
|
| 519 |
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 520 |
agent.global_memory["abstract_anchor"] = abstract_anchor
|
| 521 |
agent.global_memory["conclusion_anchor"] = conclusion_anchor
|
| 522 |
-
|
| 523 |
pb.progress(15, text="📝 大纲设计...")
|
| 524 |
plan = agent.generate_outline(topic, keywords, synthesis_result)
|
| 525 |
en_topic = str(plan.get("en_topic", topic))
|
| 526 |
en_keywords_raw = plan.get("en_keywords", keywords)
|
| 527 |
-
if isinstance(en_keywords_raw, list):
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
| 530 |
# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成
|
| 531 |
structure = plan.get("structure", [])
|
| 532 |
clean_structure = [
|
| 533 |
-
sec for sec in structure
|
| 534 |
if sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST
|
| 535 |
]
|
| 536 |
structure = clean_structure
|
|
@@ -538,7 +560,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 538 |
# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树
|
| 539 |
en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()
|
| 540 |
en_abstract_clean = clean_markdown_headings(en_abstract_raw)
|
| 541 |
-
|
| 542 |
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)
|
| 543 |
trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()
|
| 544 |
trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)
|
|
@@ -562,14 +584,14 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 562 |
adaptive_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})
|
| 563 |
else:
|
| 564 |
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})
|
| 565 |
-
|
| 566 |
state["adaptive_structure"] = adaptive_structure
|
| 567 |
state["agent_state"] = agent.export_state()
|
| 568 |
state["full_draft_en"] = full_draft_en
|
| 569 |
state["full_draft_translated"] = full_draft_translated
|
| 570 |
completed_sections = []
|
| 571 |
context_tail = ""
|
| 572 |
-
|
| 573 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 574 |
json.dump(state, f, ensure_ascii=False)
|
| 575 |
|
|
@@ -578,7 +600,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 578 |
st.markdown("---")
|
| 579 |
ui_blocks = []
|
| 580 |
target_flag = FLAG_MAP.get(target_lang, "🌐")
|
| 581 |
-
|
| 582 |
for sec in adaptive_structure:
|
| 583 |
display_name = sec["display_name"]
|
| 584 |
st.markdown(f"### ⚙️ {display_name}")
|
|
@@ -589,7 +611,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 589 |
with col_trans:
|
| 590 |
st.markdown(f"#### {target_flag} 翻译初稿")
|
| 591 |
trans_ph = st.empty()
|
| 592 |
-
|
| 593 |
if display_name in completed_sections:
|
| 594 |
en_ph.success("✅ 已从快照安全恢复并拼接")
|
| 595 |
trans_ph.success("✅ 已从快照安全恢复并拼接")
|
|
@@ -607,40 +629,46 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 607 |
allocation_map = {}
|
| 608 |
current_cite_idx = 0
|
| 609 |
for idx, vc in enumerate(valid_chunks):
|
| 610 |
-
if idx == len(valid_chunks) - 1:
|
|
|
|
| 611 |
else:
|
| 612 |
num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))
|
| 613 |
allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]
|
| 614 |
current_cite_idx += num_cites
|
| 615 |
|
| 616 |
for i, block in enumerate(ui_blocks):
|
| 617 |
-
if generation_aborted:
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
if display_name in completed_sections:
|
| 622 |
remaining_sections -= 1
|
| 623 |
-
continue
|
| 624 |
-
|
| 625 |
remaining_sections -= 1
|
| 626 |
adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
|
| 627 |
-
|
| 628 |
# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩
|
| 629 |
max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)
|
| 630 |
adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))
|
| 631 |
-
|
| 632 |
quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]
|
| 633 |
is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)
|
| 634 |
-
|
| 635 |
-
if is_quarantined:
|
|
|
|
| 636 |
else:
|
| 637 |
assigned_keys = allocation_map.get(display_name, [])
|
| 638 |
assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"
|
| 639 |
quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""
|
| 640 |
-
|
| 641 |
# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容
|
| 642 |
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."
|
| 643 |
-
|
| 644 |
memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)
|
| 645 |
memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""
|
| 646 |
|
|
@@ -648,7 +676,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 648 |
upper_bound = int(adjusted_target * 1.1)
|
| 649 |
lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")
|
| 650 |
num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)
|
| 651 |
-
|
| 652 |
adaptive_heading_rule = ""
|
| 653 |
if adjusted_target > 800:
|
| 654 |
adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."
|
|
@@ -672,11 +700,13 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 672 |
for target_key in clone_metadata.keys():
|
| 673 |
target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))
|
| 674 |
sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))
|
| 675 |
-
|
| 676 |
-
if "result" in target_words:
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
|
|
|
|
|
|
| 680 |
is_clone_target = True
|
| 681 |
active_clone_key = target_key
|
| 682 |
break
|
|
@@ -684,7 +714,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 684 |
if is_clone_target:
|
| 685 |
meta = clone_metadata[active_clone_key]
|
| 686 |
sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."
|
| 687 |
-
|
| 688 |
base_user = f"""
|
| 689 |
[CLONE MODE ACTIVATED - TARGET: {sec_title}]
|
| 690 |
Mimic the academic tone, structural flow, and sentence patterns of this reference template:
|
|
@@ -700,7 +730,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 700 |
Your previous section ended with: "...{context_tail}..."
|
| 701 |
Write a natural, smooth transitional opening sentence to bridge this.
|
| 702 |
"""
|
| 703 |
-
|
| 704 |
if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():
|
| 705 |
base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]
|
| 706 |
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>.
|
|
@@ -711,18 +741,19 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 711 |
extra_directives = []
|
| 712 |
lower_sec = sec_title.lower()
|
| 713 |
golden_meta = agent.global_memory.get("core_golden_metadata", [])
|
|
|
|
| 714 |
|
| 715 |
if golden_meta:
|
| 716 |
if any(kw in lower_sec for kw in ["introduction", "background"]):
|
| 717 |
-
extra_directives.append("【TARGETED DIRECTIVE: INTRODUCTION】
|
| 718 |
elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
|
| 719 |
-
extra_directives.append("【TARGETED DIRECTIVE: LITERATURE & HYPOTHESES】
|
| 720 |
elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
|
| 721 |
-
extra_directives.append("【TARGETED DIRECTIVE: METHODOLOGY】
|
| 722 |
elif any(kw in lower_sec for kw in ["result", "analysis"]):
|
| 723 |
-
extra_directives.append("【TARGETED DIRECTIVE: RESULTS - ZERO HALLUCINATION】
|
| 724 |
elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):
|
| 725 |
-
extra_directives.append("【TARGETED DIRECTIVE: DISCUSSION & CONCLUSION】
|
| 726 |
else:
|
| 727 |
extra_directives.append(APP_CONFIG["deep_refinement_directive"])
|
| 728 |
else:
|
|
@@ -732,14 +763,16 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 732 |
if any(kw in lower_sec for kw in ["theory", "theoretical", "hypothesis", "introduction"]):
|
| 733 |
extra_directives.append(APP_CONFIG["deep_synthesis_directive"])
|
| 734 |
extra_directives.append(APP_CONFIG["hypothesis_development_directive"])
|
| 735 |
-
if "discussion" in lower_sec:
|
| 736 |
-
|
| 737 |
-
|
|
|
|
|
|
|
| 738 |
theory_injection = "\n\n".join(extra_directives)
|
| 739 |
sys_prompt_m3 = APP_CONFIG["sys_academic_writer"] + "\n" + APP_CONFIG["deep_refinement_directive"]
|
| 740 |
-
|
| 741 |
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 ""
|
| 742 |
-
|
| 743 |
base_user = f"""Generate a polished section '{display_name}'.
|
| 744 |
{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}
|
| 745 |
Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}
|
|
@@ -748,33 +781,34 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 748 |
total_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)
|
| 749 |
if total_tokens > 60000:
|
| 750 |
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
| 751 |
-
|
| 752 |
engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")
|
| 753 |
render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")
|
| 754 |
en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")
|
| 755 |
-
|
| 756 |
try:
|
| 757 |
en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))
|
| 758 |
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()
|
| 759 |
-
|
| 760 |
# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Python
|
| 761 |
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 762 |
-
|
| 763 |
# 统一由 Python 在第一部分拼接大标题
|
| 764 |
if sec["is_first"]:
|
| 765 |
en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"
|
| 766 |
-
|
| 767 |
en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
|
| 768 |
en_ph.markdown(en_resolved)
|
| 769 |
full_draft_en += en_resolved + "\n\n"
|
| 770 |
agent._extract_memory_from_text(en_draft_clean, sec_title)
|
| 771 |
words_tail = en_draft_clean.split()
|
| 772 |
context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_clean
|
| 773 |
-
|
| 774 |
-
|
|
|
|
| 775 |
accumulated_deviation += (actual_words - adjusted_target)
|
| 776 |
st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")
|
| 777 |
-
|
| 778 |
current_step += 1
|
| 779 |
pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")
|
| 780 |
except Exception as e:
|
|
@@ -786,7 +820,6 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 786 |
render_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")
|
| 787 |
trans_ph.empty()
|
| 788 |
try:
|
| 789 |
-
# 此时的 en_draft_clean 已经包含了 Python 安全注入的 `# 标题`,翻译节点会原封不动地将其平滑译出
|
| 790 |
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"))
|
| 791 |
trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()
|
| 792 |
trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)
|
|
@@ -799,28 +832,29 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 799 |
st.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")
|
| 800 |
generation_aborted = True
|
| 801 |
break
|
| 802 |
-
|
| 803 |
state["completed_sections"].append(display_name)
|
| 804 |
state["full_draft_en"] = full_draft_en
|
| 805 |
state["full_draft_translated"] = full_draft_translated
|
| 806 |
state["context_tail"] = context_tail
|
| 807 |
state["agent_state"] = agent.export_state()
|
| 808 |
-
|
| 809 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 810 |
json.dump(state, f, ensure_ascii=False)
|
| 811 |
|
| 812 |
if not generation_aborted and full_draft_en.strip():
|
| 813 |
pb.progress(96, text="📦 打包DOCX...")
|
| 814 |
-
|
| 815 |
# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死
|
| 816 |
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 817 |
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 818 |
-
|
| 819 |
-
total_words_en =
|
| 820 |
target_words = int(words)
|
| 821 |
-
lower_limit = int(target_words * 0.95)
|
|
|
|
| 822 |
st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")
|
| 823 |
-
|
| 824 |
if total_words_en > upper_limit:
|
| 825 |
st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")
|
| 826 |
conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)
|
|
@@ -833,9 +867,11 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 833 |
if compressed_trans:
|
| 834 |
trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")
|
| 835 |
trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)
|
| 836 |
-
if trans_match:
|
| 837 |
-
|
| 838 |
-
|
|
|
|
|
|
|
| 839 |
st.success(f"✅ 精简完成,现总字数: {total_words_en}")
|
| 840 |
elif total_words_en < lower_limit:
|
| 841 |
st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")
|
|
@@ -843,14 +879,16 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 843 |
if expanded_en:
|
| 844 |
full_draft_en += "\n\n" + expanded_en.strip()
|
| 845 |
expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)
|
| 846 |
-
if expanded_trans:
|
| 847 |
-
|
|
|
|
| 848 |
st.success(f"✅ 扩展完成,现总字数: {total_words_en}")
|
| 849 |
-
|
| 850 |
-
if len(agent.used_citations) < 50:
|
| 851 |
unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]
|
| 852 |
-
for tag in unused[:50 - len(agent.used_citations)]:
|
| 853 |
-
|
|
|
|
| 854 |
used_tags = sorted(list(agent.used_citations))
|
| 855 |
raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]
|
| 856 |
unique_refs = sorted(list(set(raw_refs)))
|
|
@@ -867,21 +905,22 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 867 |
zip_buffer.seek(0)
|
| 868 |
st.session_state.zip_buffer = zip_buffer.getvalue()
|
| 869 |
st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"
|
| 870 |
-
|
| 871 |
if os.path.exists(CHECKPOINT_FILE):
|
| 872 |
os.remove(CHECKPOINT_FILE)
|
| 873 |
-
|
| 874 |
pb.progress(100, text="✅ 完成")
|
| 875 |
render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")
|
| 876 |
-
|
| 877 |
-
except Exception as e:
|
| 878 |
st.error(f"🚨 启动/恢复异常: {e}")
|
| 879 |
finally:
|
| 880 |
# 释放文件锁
|
| 881 |
-
lock_fd = st.session_state.get("
|
| 882 |
if lock_fd:
|
| 883 |
-
|
| 884 |
-
st.session_state.
|
|
|
|
| 885 |
st.session_state.is_running = False
|
| 886 |
st.session_state.start_pipeline = False
|
| 887 |
st.session_state.resume_pipeline = False
|
|
|
|
| 20 |
from datetime import datetime, timezone, timedelta
|
| 21 |
import pandas as pd
|
| 22 |
import numpy as np
|
| 23 |
+
import fcntl
|
| 24 |
+
import atexit
|
| 25 |
|
| 26 |
# 然后再引入本地模块
|
| 27 |
from app_config import APP_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTS
|
| 28 |
+
from utils.file_parser import extract_text_from_files, extract_data_from_files, count_words_adaptive
|
| 29 |
from utils.docx_builder import text_to_docx
|
| 30 |
from core.pipeline_agent import SSciPipelineAgent
|
| 31 |
|
|
|
|
| 37 |
|
| 38 |
# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码
|
| 39 |
META_SECTIONS_BLACKLIST = {
|
| 40 |
+
"abstract", "keyword", "keywords", "摘要", "关键词", "关键字",
|
| 41 |
+
"reference", "references", "reference list", "参考文献",
|
| 42 |
"acknowledgment", "acknowledgements", "致谢"
|
| 43 |
}
|
| 44 |
|
|
|
|
| 58 |
|
| 59 |
global_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 60 |
if not global_ds_key:
|
| 61 |
+
try:
|
| 62 |
+
global_ds_key = st.secrets.get("DEEPSEEK_API_KEY", "")
|
| 63 |
+
except:
|
| 64 |
+
pass
|
| 65 |
|
| 66 |
global_s2_key = os.environ.get("S2_API_KEY", "")
|
| 67 |
if not global_s2_key:
|
| 68 |
+
try:
|
| 69 |
+
global_s2_key = st.secrets.get("S2_API_KEY", "")
|
| 70 |
+
except:
|
| 71 |
+
pass
|
| 72 |
|
| 73 |
# 状态机:断点续传工作区配置
|
| 74 |
WORKSPACE_DIR = ".workspace"
|
|
|
|
| 77 |
if not os.path.exists(WORKSPACE_DIR):
|
| 78 |
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 79 |
|
| 80 |
+
# ------------------------- 混合并发锁(session_state 标志 + 文件锁)-------------------------
|
| 81 |
+
def acquire_global_lock():
|
| 82 |
"""尝试获取全局任务锁,返回 (是否成功, 锁文件句柄)"""
|
| 83 |
try:
|
| 84 |
lock_fd = open(TASK_LOCK_FILE, 'w')
|
|
|
|
| 89 |
lock_fd.close()
|
| 90 |
return False, None
|
| 91 |
|
| 92 |
+
def release_global_lock(lock_fd):
|
| 93 |
"""释放任务锁并关闭文件"""
|
| 94 |
if lock_fd:
|
| 95 |
try:
|
|
|
|
| 141 |
def check_password():
|
| 142 |
expected_password = os.environ.get("APP_PASSWORD", "")
|
| 143 |
if not expected_password:
|
| 144 |
+
try:
|
| 145 |
+
expected_password = st.secrets.get("APP_PASSWORD", "")
|
| 146 |
+
except:
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
if not expected_password:
|
| 150 |
return True
|
| 151 |
|
|
|
|
| 155 |
if not st.session_state["password_correct"]:
|
| 156 |
st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)
|
| 157 |
st.markdown("<p style='text-align: center;'>本系统为高算力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)
|
| 158 |
+
|
| 159 |
pwd = st.text_input("Access Token", type="password", key="pwd_input")
|
| 160 |
if st.button("Unlock"):
|
| 161 |
if pwd == expected_password:
|
|
|
|
| 172 |
# 1. 鲁棒的蒙特卡洛实证模拟引擎 (保持不变)
|
| 173 |
# ==========================================
|
| 174 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 175 |
+
if n_constructs == 1:
|
| 176 |
+
return np.array([[1.0]])
|
| 177 |
+
base_corr = np.random.uniform(0.2, max_corr - 0.1)
|
| 178 |
A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))
|
| 179 |
A = (A + A.T) / 2
|
| 180 |
np.fill_diagonal(A, 1.0)
|
| 181 |
min_eig = np.min(np.linalg.eigvals(A))
|
| 182 |
+
if min_eig < 0:
|
| 183 |
+
A -= (min_eig - 0.01) * np.eye(n_constructs)
|
| 184 |
d = np.sqrt(np.diag(A))
|
| 185 |
return A / np.outer(d, d)
|
| 186 |
|
|
|
|
| 214 |
target_std = scale_points / 5.0
|
| 215 |
for idx, c_name in enumerate(construct_names):
|
| 216 |
true_score = latent_scores[:, idx]
|
| 217 |
+
n_items = np.random.randint(3, 6)
|
| 218 |
loadings = np.random.uniform(0.72, 0.88, n_items)
|
| 219 |
true_loadings[c_name] = loadings
|
| 220 |
item_names = []
|
| 221 |
for i, load in enumerate(loadings):
|
| 222 |
error = np.random.normal(0, np.sqrt(1 - load**2), n)
|
| 223 |
+
item_score = load * true_score + error
|
| 224 |
raw_scaled = item_score * target_std + target_mean
|
| 225 |
item_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)
|
| 226 |
col_name = f"{c_name}_{i+1}"
|
|
|
|
| 230 |
df = pd.DataFrame(data)
|
| 231 |
validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)
|
| 232 |
mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})
|
| 233 |
+
fl_matrix = mean_scores.corr().astype(object)
|
| 234 |
for i, row in validity_df.iterrows():
|
| 235 |
c_name = row['Construct']
|
| 236 |
sqrt_ave = np.sqrt(row['AVE'])
|
|
|
|
| 262 |
# ==========================================
|
| 263 |
# 2. UI 界面布局与初始化 (保持不变)
|
| 264 |
# ==========================================
|
| 265 |
+
if "is_running" not in st.session_state:
|
| 266 |
+
st.session_state.is_running = False
|
| 267 |
+
if "start_pipeline" not in st.session_state:
|
| 268 |
+
st.session_state.start_pipeline = False
|
| 269 |
+
if "resume_pipeline" not in st.session_state:
|
| 270 |
+
st.session_state.resume_pipeline = False
|
| 271 |
+
if "zip_buffer" not in st.session_state:
|
| 272 |
+
st.session_state.zip_buffer = None
|
| 273 |
+
if "run_mode" not in st.session_state:
|
| 274 |
+
st.session_state.run_mode = "wizard"
|
| 275 |
+
# 并发控制相关
|
| 276 |
+
if "global_task_running" not in st.session_state:
|
| 277 |
+
st.session_state.global_task_running = False
|
| 278 |
+
if "lock_fd" not in st.session_state:
|
| 279 |
+
st.session_state.lock_fd = None
|
| 280 |
|
| 281 |
lang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")
|
| 282 |
ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]
|
|
|
|
| 304 |
|
| 305 |
with tab_wizard:
|
| 306 |
st.markdown("### 🛠️ 人在环路:研究材料配置")
|
| 307 |
+
prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",
|
| 308 |
+
options=["工商管理实证研究 (AMJ Style)", "通用学术规范 (Generic Style)"],
|
| 309 |
index=0, disabled=st.session_state.is_running)
|
| 310 |
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)
|
| 311 |
uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)
|
| 312 |
+
|
| 313 |
if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):
|
| 314 |
+
if st.session_state.global_task_running:
|
|
|
|
| 315 |
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 316 |
else:
|
| 317 |
+
acquired, lock_fd = acquire_global_lock()
|
| 318 |
+
if not acquired:
|
| 319 |
+
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 320 |
+
else:
|
| 321 |
+
st.session_state.global_task_running = True
|
| 322 |
+
st.session_state.lock_fd = lock_fd
|
| 323 |
+
st.session_state.run_mode = "wizard"
|
| 324 |
+
st.session_state.start_pipeline = True
|
| 325 |
+
st.rerun()
|
| 326 |
|
| 327 |
with tab_clone:
|
| 328 |
st.markdown("### 🧬 高级克隆:骨架与风格复刻")
|
| 329 |
context_differences = st.text_area(
|
| 330 |
+
"1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",
|
| 331 |
+
placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",
|
| 332 |
max_chars=2000,
|
| 333 |
disabled=st.session_state.is_running
|
| 334 |
)
|
| 335 |
+
|
| 336 |
if "extracted_sections" not in st.session_state:
|
| 337 |
st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]
|
| 338 |
if "last_uploaded_clone_ref" not in st.session_state:
|
| 339 |
st.session_state.last_uploaded_clone_ref = None
|
| 340 |
|
| 341 |
uploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)
|
| 342 |
+
|
| 343 |
if uploaded_reference_clone and global_ds_key:
|
| 344 |
if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:
|
| 345 |
with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):
|
| 346 |
temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 347 |
ref_text_raw = extract_text_from_files([uploaded_reference_clone])
|
| 348 |
dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)
|
| 349 |
+
|
| 350 |
st.session_state.extracted_sections = dynamic_sections
|
| 351 |
st.session_state.last_uploaded_clone_ref = uploaded_reference_clone.name
|
| 352 |
st.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")
|
| 353 |
+
|
| 354 |
uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)
|
| 355 |
+
|
| 356 |
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)
|
| 357 |
|
| 358 |
if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):
|
|
|
|
| 361 |
elif not uploaded_reference_clone:
|
| 362 |
st.error("🚨 启动克隆模式必须上传范例论文!")
|
| 363 |
else:
|
| 364 |
+
if st.session_state.global_task_running:
|
|
|
|
| 365 |
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 366 |
else:
|
| 367 |
+
acquired, lock_fd = acquire_global_lock()
|
| 368 |
+
if not acquired:
|
| 369 |
+
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请稍后重试。")
|
| 370 |
+
else:
|
| 371 |
+
st.session_state.global_task_running = True
|
| 372 |
+
st.session_state.lock_fd = lock_fd
|
| 373 |
+
st.session_state.run_mode = "clone"
|
| 374 |
+
st.session_state.start_pipeline = True
|
| 375 |
+
st.rerun()
|
| 376 |
|
| 377 |
progress_bar = st.empty()
|
| 378 |
monitor_ui = st.empty()
|
|
|
|
| 396 |
FLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}
|
| 397 |
|
| 398 |
# ==========================================
|
| 399 |
+
# 3. 后台流水线执行 (混合锁控制 + 字数统计修正 + 优雅降级)
|
| 400 |
# ==========================================
|
| 401 |
if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
| 402 |
if not global_ds_key:
|
| 403 |
st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")
|
| 404 |
st.stop()
|
| 405 |
+
|
| 406 |
+
# 验证锁状态
|
| 407 |
+
if not st.session_state.global_task_running or st.session_state.lock_fd is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
st.error("⚠️ 任务锁异常丢失,请刷新页面后重试。")
|
| 409 |
st.session_state.start_pipeline = False
|
| 410 |
st.session_state.resume_pipeline = False
|
| 411 |
st.stop()
|
|
|
|
|
|
|
|
|
|
| 412 |
|
| 413 |
st.session_state.is_running = True
|
| 414 |
is_resume = st.session_state.resume_pipeline
|
| 415 |
agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 416 |
+
|
| 417 |
# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取
|
| 418 |
SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_default
|
| 419 |
+
|
| 420 |
try:
|
| 421 |
if is_resume:
|
| 422 |
pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")
|
| 423 |
with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:
|
| 424 |
state = json.load(f)
|
| 425 |
+
|
| 426 |
topic = state["topic"]
|
| 427 |
keywords = state["keywords"]
|
| 428 |
target_lang = state["target_lang"]
|
| 429 |
words = state["words"]
|
| 430 |
user_data_md = state["user_data_md"]
|
| 431 |
user_lit_context = state["user_lit_context"]
|
| 432 |
+
|
| 433 |
agent.load_state(state["agent_state"])
|
| 434 |
adaptive_structure = state["adaptive_structure"]
|
| 435 |
completed_sections = state["completed_sections"]
|
|
|
|
| 441 |
context_tail = state["context_tail"]
|
| 442 |
st.session_state.run_mode = state.get("run_mode", "wizard")
|
| 443 |
APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))
|
| 444 |
+
|
| 445 |
st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")
|
| 446 |
+
|
| 447 |
else:
|
| 448 |
pb = progress_bar.progress(1, text="⏳ 流水线启动...")
|
| 449 |
+
|
| 450 |
user_lit_context = ""
|
| 451 |
user_data_md = ""
|
| 452 |
+
|
| 453 |
if st.session_state.run_mode == "wizard":
|
| 454 |
if uploaded_papers_wiz:
|
| 455 |
if len(uploaded_papers_wiz) > 5:
|
| 456 |
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
| 457 |
uploaded_papers_wiz = uploaded_papers_wiz[:5]
|
| 458 |
user_lit_context = extract_text_from_files(uploaded_papers_wiz)
|
| 459 |
+
if uploaded_data_wiz:
|
| 460 |
+
user_data_md = extract_data_from_files(uploaded_data_wiz)
|
| 461 |
+
|
| 462 |
elif st.session_state.run_mode == "clone":
|
| 463 |
+
if uploaded_reference_clone:
|
| 464 |
+
reference_paper_text = extract_text_from_files([uploaded_reference_clone])
|
| 465 |
+
if uploaded_data_clone:
|
| 466 |
+
user_data_md = extract_data_from_files(uploaded_data_clone)
|
| 467 |
if uploaded_core_papers_clone:
|
| 468 |
if len(uploaded_core_papers_clone) > 5:
|
| 469 |
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
|
|
|
| 473 |
if not user_data_md:
|
| 474 |
with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):
|
| 475 |
sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()
|
| 476 |
+
user_data_md = sim_md_prompt
|
| 477 |
st.info(sim_msg)
|
| 478 |
|
| 479 |
state = {
|
|
|
|
| 484 |
}
|
| 485 |
|
| 486 |
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 487 |
+
|
| 488 |
if st.session_state.run_mode == "wizard":
|
| 489 |
if "AMJ" in prompt_style_ui:
|
| 490 |
APP_CONFIG.update(AMJ_PROMPTS)
|
|
|
|
| 492 |
else:
|
| 493 |
APP_CONFIG.update(GENERIC_PROMPTS)
|
| 494 |
st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")
|
| 495 |
+
|
| 496 |
state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTS
|
| 497 |
|
| 498 |
clone_metadata = {}
|
|
|
|
| 508 |
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")
|
| 509 |
|
| 510 |
refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)
|
| 511 |
+
|
| 512 |
if len(agent.citation_map) < 50:
|
| 513 |
+
st.warning(f"⚠️ 仅检索到 {len(agent.citation_map)} 篇文献,低于推荐的 50 篇。")
|
| 514 |
+
col_cont, col_stop = st.columns(2)
|
| 515 |
+
with col_cont:
|
| 516 |
+
if not st.button("▶️ 继续生成(文献可能不足)"):
|
| 517 |
+
st.stop()
|
| 518 |
+
with col_stop:
|
| 519 |
+
if st.button("⏹️ 终止任务"):
|
| 520 |
+
st.stop()
|
| 521 |
+
# 用户点击继续后,代码继续执行
|
| 522 |
else:
|
| 523 |
st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 524 |
|
|
|
|
| 534 |
pb.progress(12, text="🧠 文献综合...")
|
| 535 |
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 536 |
state["synthesis_result"] = synthesis_result
|
| 537 |
+
|
| 538 |
pb.progress(14, text="⚓ 生成锚点...")
|
| 539 |
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 540 |
agent.global_memory["abstract_anchor"] = abstract_anchor
|
| 541 |
agent.global_memory["conclusion_anchor"] = conclusion_anchor
|
| 542 |
+
|
| 543 |
pb.progress(15, text="📝 大纲设计...")
|
| 544 |
plan = agent.generate_outline(topic, keywords, synthesis_result)
|
| 545 |
en_topic = str(plan.get("en_topic", topic))
|
| 546 |
en_keywords_raw = plan.get("en_keywords", keywords)
|
| 547 |
+
if isinstance(en_keywords_raw, list):
|
| 548 |
+
en_keywords_raw = "; ".join([str(k) for k in en_keywords_raw])
|
| 549 |
+
else:
|
| 550 |
+
en_keywords_raw = str(en_keywords_raw)
|
| 551 |
+
|
| 552 |
# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成
|
| 553 |
structure = plan.get("structure", [])
|
| 554 |
clean_structure = [
|
| 555 |
+
sec for sec in structure
|
| 556 |
if sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST
|
| 557 |
]
|
| 558 |
structure = clean_structure
|
|
|
|
| 560 |
# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树
|
| 561 |
en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()
|
| 562 |
en_abstract_clean = clean_markdown_headings(en_abstract_raw)
|
| 563 |
+
|
| 564 |
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)
|
| 565 |
trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()
|
| 566 |
trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)
|
|
|
|
| 584 |
adaptive_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})
|
| 585 |
else:
|
| 586 |
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})
|
| 587 |
+
|
| 588 |
state["adaptive_structure"] = adaptive_structure
|
| 589 |
state["agent_state"] = agent.export_state()
|
| 590 |
state["full_draft_en"] = full_draft_en
|
| 591 |
state["full_draft_translated"] = full_draft_translated
|
| 592 |
completed_sections = []
|
| 593 |
context_tail = ""
|
| 594 |
+
|
| 595 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 596 |
json.dump(state, f, ensure_ascii=False)
|
| 597 |
|
|
|
|
| 600 |
st.markdown("---")
|
| 601 |
ui_blocks = []
|
| 602 |
target_flag = FLAG_MAP.get(target_lang, "🌐")
|
| 603 |
+
|
| 604 |
for sec in adaptive_structure:
|
| 605 |
display_name = sec["display_name"]
|
| 606 |
st.markdown(f"### ⚙️ {display_name}")
|
|
|
|
| 611 |
with col_trans:
|
| 612 |
st.markdown(f"#### {target_flag} 翻译初稿")
|
| 613 |
trans_ph = st.empty()
|
| 614 |
+
|
| 615 |
if display_name in completed_sections:
|
| 616 |
en_ph.success("✅ 已从快照安全恢复并拼接")
|
| 617 |
trans_ph.success("✅ 已从快照安全恢复并拼接")
|
|
|
|
| 629 |
allocation_map = {}
|
| 630 |
current_cite_idx = 0
|
| 631 |
for idx, vc in enumerate(valid_chunks):
|
| 632 |
+
if idx == len(valid_chunks) - 1:
|
| 633 |
+
allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx:]
|
| 634 |
else:
|
| 635 |
num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))
|
| 636 |
allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]
|
| 637 |
current_cite_idx += num_cites
|
| 638 |
|
| 639 |
for i, block in enumerate(ui_blocks):
|
| 640 |
+
if generation_aborted:
|
| 641 |
+
break
|
| 642 |
+
sec = block["sec"]
|
| 643 |
+
en_ph = block["en_ph"]
|
| 644 |
+
trans_ph = block["trans_ph"]
|
| 645 |
+
sec_title = sec["section"]
|
| 646 |
+
display_name = sec["display_name"]
|
| 647 |
+
|
| 648 |
if display_name in completed_sections:
|
| 649 |
remaining_sections -= 1
|
| 650 |
+
continue
|
| 651 |
+
|
| 652 |
remaining_sections -= 1
|
| 653 |
adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
|
| 654 |
+
|
| 655 |
# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩
|
| 656 |
max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)
|
| 657 |
adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))
|
| 658 |
+
|
| 659 |
quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]
|
| 660 |
is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)
|
| 661 |
+
|
| 662 |
+
if is_quarantined:
|
| 663 |
+
quarantine_rule = "【CRITICAL】: NO IN-TEXT CITATIONS ALLOWED IN THIS SECTION."
|
| 664 |
else:
|
| 665 |
assigned_keys = allocation_map.get(display_name, [])
|
| 666 |
assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"
|
| 667 |
quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""
|
| 668 |
+
|
| 669 |
# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容
|
| 670 |
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."
|
| 671 |
+
|
| 672 |
memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)
|
| 673 |
memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""
|
| 674 |
|
|
|
|
| 676 |
upper_bound = int(adjusted_target * 1.1)
|
| 677 |
lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")
|
| 678 |
num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)
|
| 679 |
+
|
| 680 |
adaptive_heading_rule = ""
|
| 681 |
if adjusted_target > 800:
|
| 682 |
adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."
|
|
|
|
| 700 |
for target_key in clone_metadata.keys():
|
| 701 |
target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))
|
| 702 |
sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))
|
| 703 |
+
|
| 704 |
+
if "result" in target_words:
|
| 705 |
+
target_words.add("analysis")
|
| 706 |
+
if "result" in sec_words:
|
| 707 |
+
sec_words.add("analysis")
|
| 708 |
+
|
| 709 |
+
if target_words & sec_words:
|
| 710 |
is_clone_target = True
|
| 711 |
active_clone_key = target_key
|
| 712 |
break
|
|
|
|
| 714 |
if is_clone_target:
|
| 715 |
meta = clone_metadata[active_clone_key]
|
| 716 |
sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."
|
| 717 |
+
|
| 718 |
base_user = f"""
|
| 719 |
[CLONE MODE ACTIVATED - TARGET: {sec_title}]
|
| 720 |
Mimic the academic tone, structural flow, and sentence patterns of this reference template:
|
|
|
|
| 730 |
Your previous section ended with: "...{context_tail}..."
|
| 731 |
Write a natural, smooth transitional opening sentence to bridge this.
|
| 732 |
"""
|
| 733 |
+
|
| 734 |
if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():
|
| 735 |
base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]
|
| 736 |
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>.
|
|
|
|
| 741 |
extra_directives = []
|
| 742 |
lower_sec = sec_title.lower()
|
| 743 |
golden_meta = agent.global_memory.get("core_golden_metadata", [])
|
| 744 |
+
targeted_directives = APP_CONFIG.get("targeted_directives", {})
|
| 745 |
|
| 746 |
if golden_meta:
|
| 747 |
if any(kw in lower_sec for kw in ["introduction", "background"]):
|
| 748 |
+
extra_directives.append(targeted_directives.get("introduction", "【TARGETED DIRECTIVE: INTRODUCTION】"))
|
| 749 |
elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
|
| 750 |
+
extra_directives.append(targeted_directives.get("literature", "【TARGETED DIRECTIVE: LITERATURE & HYPOTHESES】"))
|
| 751 |
elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
|
| 752 |
+
extra_directives.append(targeted_directives.get("methodology", "【TARGETED DIRECTIVE: METHODOLOGY】"))
|
| 753 |
elif any(kw in lower_sec for kw in ["result", "analysis"]):
|
| 754 |
+
extra_directives.append(targeted_directives.get("results", "【TARGETED DIRECTIVE: RESULTS - ZERO HALLUCINATION】"))
|
| 755 |
elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):
|
| 756 |
+
extra_directives.append(targeted_directives.get("discussion", "【TARGETED DIRECTIVE: DISCUSSION & CONCLUSION】"))
|
| 757 |
else:
|
| 758 |
extra_directives.append(APP_CONFIG["deep_refinement_directive"])
|
| 759 |
else:
|
|
|
|
| 763 |
if any(kw in lower_sec for kw in ["theory", "theoretical", "hypothesis", "introduction"]):
|
| 764 |
extra_directives.append(APP_CONFIG["deep_synthesis_directive"])
|
| 765 |
extra_directives.append(APP_CONFIG["hypothesis_development_directive"])
|
| 766 |
+
if "discussion" in lower_sec:
|
| 767 |
+
extra_directives.append(APP_CONFIG["discussion_depth_directive"])
|
| 768 |
+
if "conclusion" in lower_sec:
|
| 769 |
+
extra_directives.append(APP_CONFIG["conclusion_anchor_directive"])
|
| 770 |
+
|
| 771 |
theory_injection = "\n\n".join(extra_directives)
|
| 772 |
sys_prompt_m3 = APP_CONFIG["sys_academic_writer"] + "\n" + APP_CONFIG["deep_refinement_directive"]
|
| 773 |
+
|
| 774 |
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 ""
|
| 775 |
+
|
| 776 |
base_user = f"""Generate a polished section '{display_name}'.
|
| 777 |
{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}
|
| 778 |
Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}
|
|
|
|
| 781 |
total_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)
|
| 782 |
if total_tokens > 60000:
|
| 783 |
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
| 784 |
+
|
| 785 |
engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")
|
| 786 |
render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")
|
| 787 |
en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")
|
| 788 |
+
|
| 789 |
try:
|
| 790 |
en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))
|
| 791 |
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()
|
| 792 |
+
|
| 793 |
# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Python
|
| 794 |
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 795 |
+
|
| 796 |
# 统一由 Python 在第一部分拼接大标题
|
| 797 |
if sec["is_first"]:
|
| 798 |
en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"
|
| 799 |
+
|
| 800 |
en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
|
| 801 |
en_ph.markdown(en_resolved)
|
| 802 |
full_draft_en += en_resolved + "\n\n"
|
| 803 |
agent._extract_memory_from_text(en_draft_clean, sec_title)
|
| 804 |
words_tail = en_draft_clean.split()
|
| 805 |
context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_clean
|
| 806 |
+
|
| 807 |
+
# 使用自适应字数统计
|
| 808 |
+
actual_words = count_words_adaptive(en_draft_clean, lang_hint)
|
| 809 |
accumulated_deviation += (actual_words - adjusted_target)
|
| 810 |
st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")
|
| 811 |
+
|
| 812 |
current_step += 1
|
| 813 |
pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")
|
| 814 |
except Exception as e:
|
|
|
|
| 820 |
render_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")
|
| 821 |
trans_ph.empty()
|
| 822 |
try:
|
|
|
|
| 823 |
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"))
|
| 824 |
trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()
|
| 825 |
trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)
|
|
|
|
| 832 |
st.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")
|
| 833 |
generation_aborted = True
|
| 834 |
break
|
| 835 |
+
|
| 836 |
state["completed_sections"].append(display_name)
|
| 837 |
state["full_draft_en"] = full_draft_en
|
| 838 |
state["full_draft_translated"] = full_draft_translated
|
| 839 |
state["context_tail"] = context_tail
|
| 840 |
state["agent_state"] = agent.export_state()
|
| 841 |
+
|
| 842 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 843 |
json.dump(state, f, ensure_ascii=False)
|
| 844 |
|
| 845 |
if not generation_aborted and full_draft_en.strip():
|
| 846 |
pb.progress(96, text="📦 打包DOCX...")
|
| 847 |
+
|
| 848 |
# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死
|
| 849 |
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 850 |
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 851 |
+
|
| 852 |
+
total_words_en = count_words_adaptive(full_draft_en, "en")
|
| 853 |
target_words = int(words)
|
| 854 |
+
lower_limit = int(target_words * 0.95)
|
| 855 |
+
upper_limit = int(target_words * 1.05)
|
| 856 |
st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")
|
| 857 |
+
|
| 858 |
if total_words_en > upper_limit:
|
| 859 |
st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")
|
| 860 |
conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)
|
|
|
|
| 867 |
if compressed_trans:
|
| 868 |
trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")
|
| 869 |
trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)
|
| 870 |
+
if trans_match:
|
| 871 |
+
full_draft_translated = full_draft_translated.replace(trans_match.group(1), compressed_trans.strip())
|
| 872 |
+
else:
|
| 873 |
+
full_draft_translated += "\n\n" + compressed_trans.strip()
|
| 874 |
+
total_words_en = count_words_adaptive(full_draft_en, "en")
|
| 875 |
st.success(f"✅ 精简完成,现总字数: {total_words_en}")
|
| 876 |
elif total_words_en < lower_limit:
|
| 877 |
st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")
|
|
|
|
| 879 |
if expanded_en:
|
| 880 |
full_draft_en += "\n\n" + expanded_en.strip()
|
| 881 |
expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)
|
| 882 |
+
if expanded_trans:
|
| 883 |
+
full_draft_translated += "\n\n" + expanded_trans.strip()
|
| 884 |
+
total_words_en = count_words_adaptive(full_draft_en, "en")
|
| 885 |
st.success(f"✅ 扩展完成,现总字数: {total_words_en}")
|
| 886 |
+
|
| 887 |
+
if len(agent.used_citations) < 50:
|
| 888 |
unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]
|
| 889 |
+
for tag in unused[:50 - len(agent.used_citations)]:
|
| 890 |
+
agent.used_citations.add(tag)
|
| 891 |
+
|
| 892 |
used_tags = sorted(list(agent.used_citations))
|
| 893 |
raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]
|
| 894 |
unique_refs = sorted(list(set(raw_refs)))
|
|
|
|
| 905 |
zip_buffer.seek(0)
|
| 906 |
st.session_state.zip_buffer = zip_buffer.getvalue()
|
| 907 |
st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"
|
| 908 |
+
|
| 909 |
if os.path.exists(CHECKPOINT_FILE):
|
| 910 |
os.remove(CHECKPOINT_FILE)
|
| 911 |
+
|
| 912 |
pb.progress(100, text="✅ 完成")
|
| 913 |
render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")
|
| 914 |
+
|
| 915 |
+
except Exception as e:
|
| 916 |
st.error(f"🚨 启动/恢复异常: {e}")
|
| 917 |
finally:
|
| 918 |
# 释放文件锁
|
| 919 |
+
lock_fd = st.session_state.get("lock_fd", None)
|
| 920 |
if lock_fd:
|
| 921 |
+
release_global_lock(lock_fd)
|
| 922 |
+
st.session_state.lock_fd = None
|
| 923 |
+
st.session_state.global_task_running = False
|
| 924 |
st.session_state.is_running = False
|
| 925 |
st.session_state.start_pipeline = False
|
| 926 |
st.session_state.resume_pipeline = False
|