Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,12 +20,11 @@ import json
|
|
| 20 |
from datetime import datetime, timezone, timedelta
|
| 21 |
import pandas as pd
|
| 22 |
import numpy as np
|
| 23 |
-
import
|
| 24 |
-
import atexit
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
from
|
| 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 |
|
|
@@ -35,12 +34,15 @@ from core.pipeline_agent import SSciPipelineAgent
|
|
| 35 |
os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"
|
| 36 |
os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
|
| 37 |
|
| 38 |
-
# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
"
|
| 42 |
-
"
|
|
|
|
|
|
|
| 43 |
}
|
|
|
|
| 44 |
|
| 45 |
# 🏗️ 架构重构 2:顶层纯函数提取,避免正则灾难性回溯
|
| 46 |
def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):
|
|
@@ -58,63 +60,20 @@ 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 |
-
except:
|
| 64 |
-
pass
|
| 65 |
|
| 66 |
global_s2_key = os.environ.get("S2_API_KEY", "")
|
| 67 |
if not global_s2_key:
|
| 68 |
-
try:
|
| 69 |
-
|
| 70 |
-
except:
|
| 71 |
-
pass
|
| 72 |
|
| 73 |
-
# 状态机:断点续传工作区配置
|
| 74 |
-
WORKSPACE_DIR = ".workspace"
|
| 75 |
CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")
|
| 76 |
-
TASK_LOCK_FILE = os.path.join(WORKSPACE_DIR, "task.lock")
|
| 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')
|
| 85 |
-
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 86 |
-
return True, lock_fd
|
| 87 |
-
except (BlockingIOError, IOError):
|
| 88 |
-
if 'lock_fd' in locals():
|
| 89 |
-
lock_fd.close()
|
| 90 |
-
return False, None
|
| 91 |
-
|
| 92 |
-
def release_global_lock(lock_fd):
|
| 93 |
-
"""释放任务锁并关闭文件"""
|
| 94 |
-
if lock_fd:
|
| 95 |
-
try:
|
| 96 |
-
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
| 97 |
-
lock_fd.close()
|
| 98 |
-
except:
|
| 99 |
-
pass
|
| 100 |
-
# 清理锁文件
|
| 101 |
-
try:
|
| 102 |
-
if os.path.exists(TASK_LOCK_FILE):
|
| 103 |
-
os.remove(TASK_LOCK_FILE)
|
| 104 |
-
except:
|
| 105 |
-
pass
|
| 106 |
-
|
| 107 |
-
def cleanup_lock_file():
|
| 108 |
-
"""进程退出时清理锁文件"""
|
| 109 |
-
try:
|
| 110 |
-
if os.path.exists(TASK_LOCK_FILE):
|
| 111 |
-
os.remove(TASK_LOCK_FILE)
|
| 112 |
-
except:
|
| 113 |
-
pass
|
| 114 |
-
|
| 115 |
-
atexit.register(cleanup_lock_file)
|
| 116 |
-
# --------------------------------------------------------------------------------
|
| 117 |
-
|
| 118 |
# 微信拦截与提示
|
| 119 |
WECHAT_BLOCKER_JS = """
|
| 120 |
<script>
|
|
@@ -136,16 +95,14 @@ try {
|
|
| 136 |
components.html(WECHAT_BLOCKER_JS, height=0, width=0)
|
| 137 |
|
| 138 |
# ==========================================
|
| 139 |
-
# 🚨 访问控制 (
|
| 140 |
# ==========================================
|
| 141 |
def check_password():
|
| 142 |
expected_password = os.environ.get("APP_PASSWORD", "")
|
| 143 |
if not expected_password:
|
| 144 |
-
try:
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
pass
|
| 148 |
-
|
| 149 |
if not expected_password:
|
| 150 |
return True
|
| 151 |
|
|
@@ -155,7 +112,7 @@ def check_password():
|
|
| 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:
|
|
@@ -166,21 +123,37 @@ def check_password():
|
|
| 166 |
st.stop()
|
| 167 |
return True
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
check_password()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
# ==========================================
|
| 172 |
-
# 1. 鲁棒的蒙特卡洛实证模拟引擎
|
| 173 |
# ==========================================
|
| 174 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 175 |
-
if n_constructs == 1:
|
| 176 |
-
|
| 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,13 +187,13 @@ def generate_empirical_data_robust(construct_names=None, n=300, scale_points=7):
|
|
| 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,7 +203,7 @@ def generate_empirical_data_robust(construct_names=None, n=300, scale_points=7):
|
|
| 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'])
|
|
@@ -260,23 +233,13 @@ def resolve_empirical_data(extracted_vars=None):
|
|
| 260 |
return df, simulated_md_prompt, status_msg
|
| 261 |
|
| 262 |
# ==========================================
|
| 263 |
-
# 2. UI 界面布局与初始化
|
| 264 |
# ==========================================
|
| 265 |
-
if "is_running" not in st.session_state:
|
| 266 |
-
|
| 267 |
-
if "
|
| 268 |
-
|
| 269 |
-
if "
|
| 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,55 +267,50 @@ tab_wizard, tab_clone = st.tabs(["✨ 智能向导模式 (Smart Wizard)", "🧬
|
|
| 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
|
| 315 |
-
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请
|
| 316 |
else:
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 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"):
|
|
@@ -360,19 +318,13 @@ with tab_clone:
|
|
| 360 |
st.error("🚨 启动克隆模式必须填写研究背景与核心差异!")
|
| 361 |
elif not uploaded_reference_clone:
|
| 362 |
st.error("🚨 启动克隆模式必须上传范例论文!")
|
|
|
|
|
|
|
| 363 |
else:
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 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,16 +348,15 @@ def render_monitor(agent, phase, current_sec="", details=""):
|
|
| 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 |
-
|
| 408 |
-
st.error("⚠️ 任务锁异常丢失,请刷新页面后重试。")
|
| 409 |
st.session_state.start_pipeline = False
|
| 410 |
st.session_state.resume_pipeline = False
|
| 411 |
st.stop()
|
|
@@ -413,23 +364,23 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,29 +392,26 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 461 |
-
|
| 462 |
elif st.session_state.run_mode == "clone":
|
| 463 |
-
if uploaded_reference_clone:
|
| 464 |
-
|
| 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,7 +421,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,7 +432,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,7 +440,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,17 +456,10 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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.
|
| 514 |
-
|
| 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,25 +475,23 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 549 |
-
|
| 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,7 +499,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,14 +523,14 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,7 +539,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,7 +550,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,46 +568,40 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 642 |
-
|
| 643 |
-
|
| 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,7 +609,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,13 +633,11 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
if target_words & sec_words:
|
| 710 |
is_clone_target = True
|
| 711 |
active_clone_key = target_key
|
| 712 |
break
|
|
@@ -714,7 +645,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,7 +661,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,19 +672,18 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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(
|
| 749 |
elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
|
| 750 |
-
extra_directives.append(
|
| 751 |
elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
|
| 752 |
-
extra_directives.append(
|
| 753 |
elif any(kw in lower_sec for kw in ["result", "analysis"]):
|
| 754 |
-
extra_directives.append(
|
| 755 |
elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):
|
| 756 |
-
extra_directives.append(
|
| 757 |
else:
|
| 758 |
extra_directives.append(APP_CONFIG["deep_refinement_directive"])
|
| 759 |
else:
|
|
@@ -763,16 +693,14 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 768 |
-
|
| 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,34 +709,33 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,6 +747,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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,29 +760,28 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 =
|
| 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,28 +794,24 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 872 |
-
|
| 873 |
-
|
| 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...")
|
| 878 |
expanded_en = agent.call_deepseek("Continue the conclusion by adding 100-200 words of academically substantive content (future research/limitations).", full_draft_en[-min(2000, len(full_draft_en)):], max_tokens=800)
|
| 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 |
-
|
| 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 |
-
|
| 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,22 +828,18 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 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 |
-
|
| 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
|
|
|
|
| 20 |
from datetime import datetime, timezone, timedelta
|
| 21 |
import pandas as pd
|
| 22 |
import numpy as np
|
| 23 |
+
import threading
|
|
|
|
| 24 |
|
| 25 |
+
# 🚨 核心修复:修正幽灵导入,统一从 config.py 读取
|
| 26 |
+
from config import APP_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTS
|
| 27 |
+
from utils.file_parser import extract_text_from_files, extract_data_from_files
|
| 28 |
from utils.docx_builder import text_to_docx
|
| 29 |
from core.pipeline_agent import SSciPipelineAgent
|
| 30 |
|
|
|
|
| 34 |
os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"
|
| 35 |
os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
|
| 36 |
|
| 37 |
+
# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码 (统一从 APP_CONFIG 读取)
|
| 38 |
+
# 提供默认备用集以防 config.py 暂未更新
|
| 39 |
+
default_meta_sections = {
|
| 40 |
+
"abstract", "keyword", "keywords", "摘要", "关键词", "关键字",
|
| 41 |
+
"reference", "references", "reference list", "参考文献",
|
| 42 |
+
"acknowledgment", "acknowledgements", "致谢",
|
| 43 |
+
"аннотация", "ключевые слова", "түйіндеме", "кілт сөздер"
|
| 44 |
}
|
| 45 |
+
META_SECTIONS_BLACKLIST = set(APP_CONFIG.get("blacklists", {}).get("meta_sections", default_meta_sections))
|
| 46 |
|
| 47 |
# 🏗️ 架构重构 2:顶层纯函数提取,避免正则灾难性回溯
|
| 48 |
def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):
|
|
|
|
| 60 |
|
| 61 |
global_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 62 |
if not global_ds_key:
|
| 63 |
+
try: global_ds_key = st.secrets.get("DEEPSEEK_API_KEY", "")
|
| 64 |
+
except: pass
|
|
|
|
|
|
|
| 65 |
|
| 66 |
global_s2_key = os.environ.get("S2_API_KEY", "")
|
| 67 |
if not global_s2_key:
|
| 68 |
+
try: global_s2_key = st.secrets.get("S2_API_KEY", "")
|
| 69 |
+
except: pass
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
# 状态机:断点续传工作区配置 (消除硬编码)
|
| 72 |
+
WORKSPACE_DIR = APP_CONFIG.get("workspace_dir", ".workspace")
|
| 73 |
CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")
|
|
|
|
| 74 |
if not os.path.exists(WORKSPACE_DIR):
|
| 75 |
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
# 微信拦截与提示
|
| 78 |
WECHAT_BLOCKER_JS = """
|
| 79 |
<script>
|
|
|
|
| 95 |
components.html(WECHAT_BLOCKER_JS, height=0, width=0)
|
| 96 |
|
| 97 |
# ==========================================
|
| 98 |
+
# 🚨 访问控制与全局并发锁 (Global Mutex)
|
| 99 |
# ==========================================
|
| 100 |
def check_password():
|
| 101 |
expected_password = os.environ.get("APP_PASSWORD", "")
|
| 102 |
if not expected_password:
|
| 103 |
+
try: expected_password = st.secrets.get("APP_PASSWORD", "")
|
| 104 |
+
except: pass
|
| 105 |
+
|
|
|
|
|
|
|
| 106 |
if not expected_password:
|
| 107 |
return True
|
| 108 |
|
|
|
|
| 112 |
if not st.session_state["password_correct"]:
|
| 113 |
st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)
|
| 114 |
st.markdown("<p style='text-align: center;'>本系统为高���力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)
|
| 115 |
+
|
| 116 |
pwd = st.text_input("Access Token", type="password", key="pwd_input")
|
| 117 |
if st.button("Unlock"):
|
| 118 |
if pwd == expected_password:
|
|
|
|
| 123 |
st.stop()
|
| 124 |
return True
|
| 125 |
|
| 126 |
+
@st.cache_resource
|
| 127 |
+
def get_global_lock():
|
| 128 |
+
return threading.Lock()
|
| 129 |
+
|
| 130 |
check_password()
|
| 131 |
+
global_lock = get_global_lock()
|
| 132 |
+
|
| 133 |
+
# 🚨 核心修复:防死锁强制释放机制
|
| 134 |
+
with st.sidebar:
|
| 135 |
+
st.markdown("### 🛠️ 系统维护")
|
| 136 |
+
if st.button("🚨 强制释放全局并发锁", help="当系统遭遇意外死锁时,点击此按钮强制重置状态。"):
|
| 137 |
+
if global_lock.locked():
|
| 138 |
+
global_lock.release()
|
| 139 |
+
st.session_state.is_running = False
|
| 140 |
+
st.session_state.start_pipeline = False
|
| 141 |
+
st.session_state.resume_pipeline = False
|
| 142 |
+
st.success("✅ 全局锁已强制释放!您可以重新开始生成了。")
|
| 143 |
+
time.sleep(1)
|
| 144 |
+
st.rerun()
|
| 145 |
|
| 146 |
# ==========================================
|
| 147 |
+
# 1. 鲁棒的蒙特卡洛实证模拟引擎
|
| 148 |
# ==========================================
|
| 149 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 150 |
+
if n_constructs == 1: return np.array([[1.0]])
|
| 151 |
+
base_corr = np.random.uniform(0.2, max_corr - 0.1)
|
|
|
|
| 152 |
A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))
|
| 153 |
A = (A + A.T) / 2
|
| 154 |
np.fill_diagonal(A, 1.0)
|
| 155 |
min_eig = np.min(np.linalg.eigvals(A))
|
| 156 |
+
if min_eig < 0: A -= (min_eig - 0.01) * np.eye(n_constructs)
|
|
|
|
| 157 |
d = np.sqrt(np.diag(A))
|
| 158 |
return A / np.outer(d, d)
|
| 159 |
|
|
|
|
| 187 |
target_std = scale_points / 5.0
|
| 188 |
for idx, c_name in enumerate(construct_names):
|
| 189 |
true_score = latent_scores[:, idx]
|
| 190 |
+
n_items = np.random.randint(3, 6)
|
| 191 |
loadings = np.random.uniform(0.72, 0.88, n_items)
|
| 192 |
true_loadings[c_name] = loadings
|
| 193 |
item_names = []
|
| 194 |
for i, load in enumerate(loadings):
|
| 195 |
error = np.random.normal(0, np.sqrt(1 - load**2), n)
|
| 196 |
+
item_score = load * true_score + error
|
| 197 |
raw_scaled = item_score * target_std + target_mean
|
| 198 |
item_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)
|
| 199 |
col_name = f"{c_name}_{i+1}"
|
|
|
|
| 203 |
df = pd.DataFrame(data)
|
| 204 |
validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)
|
| 205 |
mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})
|
| 206 |
+
fl_matrix = mean_scores.corr().astype(object)
|
| 207 |
for i, row in validity_df.iterrows():
|
| 208 |
c_name = row['Construct']
|
| 209 |
sqrt_ave = np.sqrt(row['AVE'])
|
|
|
|
| 233 |
return df, simulated_md_prompt, status_msg
|
| 234 |
|
| 235 |
# ==========================================
|
| 236 |
+
# 2. UI 界面布局与初始化
|
| 237 |
# ==========================================
|
| 238 |
+
if "is_running" not in st.session_state: st.session_state.is_running = False
|
| 239 |
+
if "start_pipeline" not in st.session_state: st.session_state.start_pipeline = False
|
| 240 |
+
if "resume_pipeline" not in st.session_state: st.session_state.resume_pipeline = False
|
| 241 |
+
if "zip_buffer" not in st.session_state: st.session_state.zip_buffer = None
|
| 242 |
+
if "run_mode" not in st.session_state: st.session_state.run_mode = "wizard"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
lang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")
|
| 245 |
ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]
|
|
|
|
| 267 |
|
| 268 |
with tab_wizard:
|
| 269 |
st.markdown("### 🛠️ 人在环路:研究材料配置")
|
| 270 |
+
prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",
|
| 271 |
+
options=["工商管理实证研究 (AMJ Style)", "通用学术规范 (Generic Style)"],
|
| 272 |
index=0, disabled=st.session_state.is_running)
|
| 273 |
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)
|
| 274 |
uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)
|
| 275 |
+
|
| 276 |
if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):
|
| 277 |
+
if not global_lock.acquire(blocking=False):
|
| 278 |
+
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。为了保证系统稳定,请大约 5-10 分钟后再试。")
|
| 279 |
else:
|
| 280 |
+
global_lock.release()
|
| 281 |
+
st.session_state.run_mode = "wizard"
|
| 282 |
+
st.session_state.start_pipeline = True
|
| 283 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
with tab_clone:
|
| 286 |
st.markdown("### 🧬 高级克隆:骨架与风格复刻")
|
| 287 |
context_differences = st.text_area(
|
| 288 |
+
"1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",
|
| 289 |
+
placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",
|
| 290 |
max_chars=2000,
|
| 291 |
disabled=st.session_state.is_running
|
| 292 |
)
|
| 293 |
+
|
| 294 |
if "extracted_sections" not in st.session_state:
|
| 295 |
st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]
|
| 296 |
if "last_uploaded_clone_ref" not in st.session_state:
|
| 297 |
st.session_state.last_uploaded_clone_ref = None
|
| 298 |
|
| 299 |
uploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)
|
| 300 |
+
|
| 301 |
if uploaded_reference_clone and global_ds_key:
|
| 302 |
if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:
|
| 303 |
with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):
|
| 304 |
temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 305 |
ref_text_raw = extract_text_from_files([uploaded_reference_clone])
|
| 306 |
dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)
|
| 307 |
+
|
| 308 |
st.session_state.extracted_sections = dynamic_sections
|
| 309 |
st.session_state.last_uploaded_clone_ref = uploaded_reference_clone.name
|
| 310 |
st.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")
|
| 311 |
+
|
| 312 |
uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)
|
| 313 |
+
|
| 314 |
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)
|
| 315 |
|
| 316 |
if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):
|
|
|
|
| 318 |
st.error("🚨 启动克隆模式必须填写研究背景与核心差异!")
|
| 319 |
elif not uploaded_reference_clone:
|
| 320 |
st.error("🚨 启动克隆模式必须上传范例论文!")
|
| 321 |
+
elif not global_lock.acquire(blocking=False):
|
| 322 |
+
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请大约 5-10 分钟后再试。")
|
| 323 |
else:
|
| 324 |
+
global_lock.release()
|
| 325 |
+
st.session_state.run_mode = "clone"
|
| 326 |
+
st.session_state.start_pipeline = True
|
| 327 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
progress_bar = st.empty()
|
| 330 |
monitor_ui = st.empty()
|
|
|
|
| 348 |
FLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}
|
| 349 |
|
| 350 |
# ==========================================
|
| 351 |
+
# 3. 后台流水线执行
|
| 352 |
# ==========================================
|
| 353 |
if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
| 354 |
if not global_ds_key:
|
| 355 |
st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")
|
| 356 |
st.stop()
|
| 357 |
+
|
| 358 |
+
if not global_lock.acquire(blocking=False):
|
| 359 |
+
st.warning("⚠️ 糟糕!在您点击的一瞬间,系统刚好被抢占了。请稍后重试。")
|
|
|
|
| 360 |
st.session_state.start_pipeline = False
|
| 361 |
st.session_state.resume_pipeline = False
|
| 362 |
st.stop()
|
|
|
|
| 364 |
st.session_state.is_running = True
|
| 365 |
is_resume = st.session_state.resume_pipeline
|
| 366 |
agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 367 |
+
|
| 368 |
# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取
|
| 369 |
SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_default
|
| 370 |
+
|
| 371 |
try:
|
| 372 |
if is_resume:
|
| 373 |
pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")
|
| 374 |
with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:
|
| 375 |
state = json.load(f)
|
| 376 |
+
|
| 377 |
topic = state["topic"]
|
| 378 |
keywords = state["keywords"]
|
| 379 |
target_lang = state["target_lang"]
|
| 380 |
words = state["words"]
|
| 381 |
user_data_md = state["user_data_md"]
|
| 382 |
user_lit_context = state["user_lit_context"]
|
| 383 |
+
|
| 384 |
agent.load_state(state["agent_state"])
|
| 385 |
adaptive_structure = state["adaptive_structure"]
|
| 386 |
completed_sections = state["completed_sections"]
|
|
|
|
| 392 |
context_tail = state["context_tail"]
|
| 393 |
st.session_state.run_mode = state.get("run_mode", "wizard")
|
| 394 |
APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))
|
| 395 |
+
|
| 396 |
st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")
|
| 397 |
+
|
| 398 |
else:
|
| 399 |
pb = progress_bar.progress(1, text="⏳ 流水线启动...")
|
| 400 |
+
|
| 401 |
user_lit_context = ""
|
| 402 |
user_data_md = ""
|
| 403 |
+
|
| 404 |
if st.session_state.run_mode == "wizard":
|
| 405 |
if uploaded_papers_wiz:
|
| 406 |
if len(uploaded_papers_wiz) > 5:
|
| 407 |
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
| 408 |
uploaded_papers_wiz = uploaded_papers_wiz[:5]
|
| 409 |
user_lit_context = extract_text_from_files(uploaded_papers_wiz)
|
| 410 |
+
if uploaded_data_wiz: user_data_md = extract_data_from_files(uploaded_data_wiz)
|
| 411 |
+
|
|
|
|
| 412 |
elif st.session_state.run_mode == "clone":
|
| 413 |
+
if uploaded_reference_clone: reference_paper_text = extract_text_from_files([uploaded_reference_clone])
|
| 414 |
+
if uploaded_data_clone: user_data_md = extract_data_from_files(uploaded_data_clone)
|
|
|
|
|
|
|
| 415 |
if uploaded_core_papers_clone:
|
| 416 |
if len(uploaded_core_papers_clone) > 5:
|
| 417 |
st.warning("⚠��� 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
|
|
|
| 421 |
if not user_data_md:
|
| 422 |
with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):
|
| 423 |
sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()
|
| 424 |
+
user_data_md = sim_md_prompt
|
| 425 |
st.info(sim_msg)
|
| 426 |
|
| 427 |
state = {
|
|
|
|
| 432 |
}
|
| 433 |
|
| 434 |
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 435 |
+
|
| 436 |
if st.session_state.run_mode == "wizard":
|
| 437 |
if "AMJ" in prompt_style_ui:
|
| 438 |
APP_CONFIG.update(AMJ_PROMPTS)
|
|
|
|
| 440 |
else:
|
| 441 |
APP_CONFIG.update(GENERIC_PROMPTS)
|
| 442 |
st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")
|
| 443 |
+
|
| 444 |
state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTS
|
| 445 |
|
| 446 |
clone_metadata = {}
|
|
|
|
| 456 |
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")
|
| 457 |
|
| 458 |
refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)
|
| 459 |
+
|
| 460 |
if len(agent.citation_map) < 50:
|
| 461 |
+
st.error(f"🚨 终止生成:系统已触发最大轮次的【主题自动泛化与补充策略】,最终仅整合到 {len(agent.citation_map)} 篇有效文献,未达到 50 篇最低要求。")
|
| 462 |
+
st.stop()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
else:
|
| 464 |
st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 465 |
|
|
|
|
| 475 |
pb.progress(12, text="🧠 文献综合...")
|
| 476 |
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 477 |
state["synthesis_result"] = synthesis_result
|
| 478 |
+
|
| 479 |
pb.progress(14, text="⚓ 生成锚点...")
|
| 480 |
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 481 |
agent.global_memory["abstract_anchor"] = abstract_anchor
|
| 482 |
agent.global_memory["conclusion_anchor"] = conclusion_anchor
|
| 483 |
+
|
| 484 |
pb.progress(15, text="📝 大纲设计...")
|
| 485 |
plan = agent.generate_outline(topic, keywords, synthesis_result)
|
| 486 |
en_topic = str(plan.get("en_topic", topic))
|
| 487 |
en_keywords_raw = plan.get("en_keywords", keywords)
|
| 488 |
+
if isinstance(en_keywords_raw, list): en_keywords_raw = "; ".join([str(k) for k in en_keywords_raw])
|
| 489 |
+
else: en_keywords_raw = str(en_keywords_raw)
|
| 490 |
+
|
|
|
|
|
|
|
| 491 |
# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成
|
| 492 |
structure = plan.get("structure", [])
|
| 493 |
clean_structure = [
|
| 494 |
+
sec for sec in structure
|
| 495 |
if sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST
|
| 496 |
]
|
| 497 |
structure = clean_structure
|
|
|
|
| 499 |
# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树
|
| 500 |
en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()
|
| 501 |
en_abstract_clean = clean_markdown_headings(en_abstract_raw)
|
| 502 |
+
|
| 503 |
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)
|
| 504 |
trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()
|
| 505 |
trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)
|
|
|
|
| 523 |
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})
|
| 524 |
else:
|
| 525 |
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})
|
| 526 |
+
|
| 527 |
state["adaptive_structure"] = adaptive_structure
|
| 528 |
state["agent_state"] = agent.export_state()
|
| 529 |
state["full_draft_en"] = full_draft_en
|
| 530 |
state["full_draft_translated"] = full_draft_translated
|
| 531 |
completed_sections = []
|
| 532 |
context_tail = ""
|
| 533 |
+
|
| 534 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 535 |
json.dump(state, f, ensure_ascii=False)
|
| 536 |
|
|
|
|
| 539 |
st.markdown("---")
|
| 540 |
ui_blocks = []
|
| 541 |
target_flag = FLAG_MAP.get(target_lang, "🌐")
|
| 542 |
+
|
| 543 |
for sec in adaptive_structure:
|
| 544 |
display_name = sec["display_name"]
|
| 545 |
st.markdown(f"### ⚙️ {display_name}")
|
|
|
|
| 550 |
with col_trans:
|
| 551 |
st.markdown(f"#### {target_flag} 翻译初稿")
|
| 552 |
trans_ph = st.empty()
|
| 553 |
+
|
| 554 |
if display_name in completed_sections:
|
| 555 |
en_ph.success("✅ 已从快照安全恢复并拼接")
|
| 556 |
trans_ph.success("✅ 已从快照安全恢复并拼接")
|
|
|
|
| 568 |
allocation_map = {}
|
| 569 |
current_cite_idx = 0
|
| 570 |
for idx, vc in enumerate(valid_chunks):
|
| 571 |
+
if idx == len(valid_chunks) - 1: allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx:]
|
|
|
|
| 572 |
else:
|
| 573 |
num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))
|
| 574 |
allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]
|
| 575 |
current_cite_idx += num_cites
|
| 576 |
|
| 577 |
for i, block in enumerate(ui_blocks):
|
| 578 |
+
if generation_aborted: break
|
| 579 |
+
sec = block["sec"]; en_ph = block["en_ph"]; trans_ph = block["trans_ph"]
|
| 580 |
+
sec_title = sec["section"]; display_name = sec["display_name"]
|
| 581 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
if display_name in completed_sections:
|
| 583 |
remaining_sections -= 1
|
| 584 |
+
continue
|
| 585 |
+
|
| 586 |
remaining_sections -= 1
|
| 587 |
adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
|
| 588 |
+
|
| 589 |
# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩
|
| 590 |
max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)
|
| 591 |
adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))
|
| 592 |
+
|
| 593 |
quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]
|
| 594 |
is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)
|
| 595 |
+
|
| 596 |
+
if is_quarantined: quarantine_rule = "【CRITICAL】: NO IN-TEXT CITATIONS ALLOWED IN THIS SECTION."
|
|
|
|
| 597 |
else:
|
| 598 |
assigned_keys = allocation_map.get(display_name, [])
|
| 599 |
assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"
|
| 600 |
quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""
|
| 601 |
+
|
| 602 |
# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容
|
| 603 |
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."
|
| 604 |
+
|
| 605 |
memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)
|
| 606 |
memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""
|
| 607 |
|
|
|
|
| 609 |
upper_bound = int(adjusted_target * 1.1)
|
| 610 |
lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")
|
| 611 |
num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)
|
| 612 |
+
|
| 613 |
adaptive_heading_rule = ""
|
| 614 |
if adjusted_target > 800:
|
| 615 |
adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."
|
|
|
|
| 633 |
for target_key in clone_metadata.keys():
|
| 634 |
target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))
|
| 635 |
sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))
|
| 636 |
+
|
| 637 |
+
if "result" in target_words: target_words.add("analysis")
|
| 638 |
+
if "result" in sec_words: sec_words.add("analysis")
|
| 639 |
+
|
| 640 |
+
if target_words & sec_words:
|
|
|
|
|
|
|
| 641 |
is_clone_target = True
|
| 642 |
active_clone_key = target_key
|
| 643 |
break
|
|
|
|
| 645 |
if is_clone_target:
|
| 646 |
meta = clone_metadata[active_clone_key]
|
| 647 |
sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."
|
| 648 |
+
|
| 649 |
base_user = f"""
|
| 650 |
[CLONE MODE ACTIVATED - TARGET: {sec_title}]
|
| 651 |
Mimic the academic tone, structural flow, and sentence patterns of this reference template:
|
|
|
|
| 661 |
Your previous section ended with: "...{context_tail}..."
|
| 662 |
Write a natural, smooth transitional opening sentence to bridge this.
|
| 663 |
"""
|
| 664 |
+
|
| 665 |
if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():
|
| 666 |
base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]
|
| 667 |
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>.
|
|
|
|
| 672 |
extra_directives = []
|
| 673 |
lower_sec = sec_title.lower()
|
| 674 |
golden_meta = agent.global_memory.get("core_golden_metadata", [])
|
|
|
|
| 675 |
|
| 676 |
if golden_meta:
|
| 677 |
if any(kw in lower_sec for kw in ["introduction", "background"]):
|
| 678 |
+
extra_directives.append("【TARGETED DIRECTIVE: INTRODUCTION】\n你必须审视 [TARGETED INJECTION] 中列出的核心文献的局限性与未来展望 (Future Gaps)。禁止泛泛而谈研究背景。你必须将本研究定位为对这些明确 Gaps 的直接回应,建立极强的学术对话感。")
|
| 679 |
elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
|
| 680 |
+
extra_directives.append("【TARGETED DIRECTIVE: LITERATURE & HYPOTHESES】\n严禁简单罗列前人观点或凭空捏造机制。你必须明确使用 [TARGETED INJECTION] 中提供的理论视角 (Theoretical Lens) 作为推导的底层逻辑。你的论证过程必须引用这些核心文献已验证的因果路径,说明新假设是如何在它们的肩膀上向前推演的。")
|
| 681 |
elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
|
| 682 |
+
extra_directives.append("【TARGETED DIRECTIVE: METHODOLOGY】\n在撰写测量工具 (Measures) 时,你必须明确声明我们的问卷题项改编自 [TARGETED INJECTION] 中记录的核心文献,以此证明量表具有极高的历史信度与效度。将注入�� Items 自然融入行文中。")
|
| 683 |
elif any(kw in lower_sec for kw in ["result", "analysis"]):
|
| 684 |
+
extra_directives.append("【TARGETED DIRECTIVE: RESULTS - ZERO HALLUCINATION】\n【绝对数据忠诚指令】你现在是一个没有感情的统计报告员。1. 必须逐字逐句将 <USER_ACTUAL_DATA> 翻译为规范的学术段落。2. 绝对禁止生成任何表格中不存在的 P值、T值或 R²。3. 必须逐一核对 【ESTABLISHED HYPOTHESES】,并在段末明确写出判定 (如 'H1 is supported')。禁止在此进行理论探讨。")
|
| 685 |
elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"]):
|
| 686 |
+
extra_directives.append("【TARGETED DIRECTIVE: DISCUSSION & CONCLUSION】\n【理论回声与升华指令】本章是全篇灵魂。1. 不要简单重复结果,必须将本研究成立的假设与 [TARGETED INJECTION] 中核心文献的发现进行结构化对比,指出是印证了前人还是得出了矛盾/新边界。2. 基于对比提供高度可操作的管理启示。3. 诚实反思局限并提供具体研究方向。")
|
| 687 |
else:
|
| 688 |
extra_directives.append(APP_CONFIG["deep_refinement_directive"])
|
| 689 |
else:
|
|
|
|
| 693 |
if any(kw in lower_sec for kw in ["theory", "theoretical", "hypothesis", "introduction"]):
|
| 694 |
extra_directives.append(APP_CONFIG["deep_synthesis_directive"])
|
| 695 |
extra_directives.append(APP_CONFIG["hypothesis_development_directive"])
|
| 696 |
+
if "discussion" in lower_sec: extra_directives.append(APP_CONFIG["discussion_depth_directive"])
|
| 697 |
+
if "conclusion" in lower_sec: extra_directives.append(APP_CONFIG["conclusion_anchor_directive"])
|
| 698 |
+
|
|
|
|
|
|
|
| 699 |
theory_injection = "\n\n".join(extra_directives)
|
| 700 |
sys_prompt_m3 = APP_CONFIG["sys_academic_writer"] + "\n" + APP_CONFIG["deep_refinement_directive"]
|
| 701 |
+
|
| 702 |
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 ""
|
| 703 |
+
|
| 704 |
base_user = f"""Generate a polished section '{display_name}'.
|
| 705 |
{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}
|
| 706 |
Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}
|
|
|
|
| 709 |
total_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)
|
| 710 |
if total_tokens > 60000:
|
| 711 |
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
| 712 |
+
|
| 713 |
engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")
|
| 714 |
render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")
|
| 715 |
en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")
|
| 716 |
+
|
| 717 |
try:
|
| 718 |
en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))
|
| 719 |
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()
|
| 720 |
+
|
| 721 |
# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Python
|
| 722 |
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 723 |
+
|
| 724 |
# 统一由 Python 在第一部分拼接大标题
|
| 725 |
if sec["is_first"]:
|
| 726 |
en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"
|
| 727 |
+
|
| 728 |
en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
|
| 729 |
en_ph.markdown(en_resolved)
|
| 730 |
full_draft_en += en_resolved + "\n\n"
|
| 731 |
agent._extract_memory_from_text(en_draft_clean, sec_title)
|
| 732 |
words_tail = en_draft_clean.split()
|
| 733 |
context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_clean
|
| 734 |
+
|
| 735 |
+
actual_words = len(en_draft_clean.split())
|
|
|
|
| 736 |
accumulated_deviation += (actual_words - adjusted_target)
|
| 737 |
st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")
|
| 738 |
+
|
| 739 |
current_step += 1
|
| 740 |
pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")
|
| 741 |
except Exception as e:
|
|
|
|
| 747 |
render_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")
|
| 748 |
trans_ph.empty()
|
| 749 |
try:
|
| 750 |
+
# 此时的 en_draft_clean 已经包含了 Python 安全注入的 `# 标题`,翻译节点会原封不动地将其平滑译出
|
| 751 |
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"))
|
| 752 |
trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()
|
| 753 |
trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)
|
|
|
|
| 760 |
st.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")
|
| 761 |
generation_aborted = True
|
| 762 |
break
|
| 763 |
+
|
| 764 |
state["completed_sections"].append(display_name)
|
| 765 |
state["full_draft_en"] = full_draft_en
|
| 766 |
state["full_draft_translated"] = full_draft_translated
|
| 767 |
state["context_tail"] = context_tail
|
| 768 |
state["agent_state"] = agent.export_state()
|
| 769 |
+
|
| 770 |
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 771 |
json.dump(state, f, ensure_ascii=False)
|
| 772 |
|
| 773 |
if not generation_aborted and full_draft_en.strip():
|
| 774 |
pb.progress(96, text="📦 打包DOCX...")
|
| 775 |
+
|
| 776 |
# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死
|
| 777 |
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 778 |
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 779 |
+
|
| 780 |
+
total_words_en = len(full_draft_en.split())
|
| 781 |
target_words = int(words)
|
| 782 |
+
lower_limit = int(target_words * 0.95); upper_limit = int(target_words * 1.05)
|
|
|
|
| 783 |
st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")
|
| 784 |
+
|
| 785 |
if total_words_en > upper_limit:
|
| 786 |
st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")
|
| 787 |
conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)
|
|
|
|
| 794 |
if compressed_trans:
|
| 795 |
trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")
|
| 796 |
trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)
|
| 797 |
+
if trans_match: full_draft_translated = full_draft_translated.replace(trans_match.group(1), compressed_trans.strip())
|
| 798 |
+
else: full_draft_translated += "\n\n" + compressed_trans.strip()
|
| 799 |
+
total_words_en = len(full_draft_en.split())
|
| 800 |
+
st.success(f"✅ 精简完成,现总字数: {total_words_en}")
|
|
|
|
|
|
|
| 801 |
elif total_words_en < lower_limit:
|
| 802 |
st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")
|
| 803 |
expanded_en = agent.call_deepseek("Continue the conclusion by adding 100-200 words of academically substantive content (future research/limitations).", full_draft_en[-min(2000, len(full_draft_en)):], max_tokens=800)
|
| 804 |
if expanded_en:
|
| 805 |
full_draft_en += "\n\n" + expanded_en.strip()
|
| 806 |
expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)
|
| 807 |
+
if expanded_trans: full_draft_translated += "\n\n" + expanded_trans.strip()
|
| 808 |
+
total_words_en = len(full_draft_en.split())
|
|
|
|
| 809 |
st.success(f"✅ 扩展完成,现总字数: {total_words_en}")
|
| 810 |
+
|
| 811 |
+
if len(agent.used_citations) < 50:
|
| 812 |
unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]
|
| 813 |
+
for tag in unused[:50 - len(agent.used_citations)]: agent.used_citations.add(tag)
|
| 814 |
+
|
|
|
|
| 815 |
used_tags = sorted(list(agent.used_citations))
|
| 816 |
raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]
|
| 817 |
unique_refs = sorted(list(set(raw_refs)))
|
|
|
|
| 828 |
zip_buffer.seek(0)
|
| 829 |
st.session_state.zip_buffer = zip_buffer.getvalue()
|
| 830 |
st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"
|
| 831 |
+
|
| 832 |
if os.path.exists(CHECKPOINT_FILE):
|
| 833 |
os.remove(CHECKPOINT_FILE)
|
| 834 |
+
|
| 835 |
pb.progress(100, text="✅ 完成")
|
| 836 |
render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")
|
| 837 |
+
|
| 838 |
+
except Exception as e:
|
| 839 |
st.error(f"🚨 启动/恢复异常: {e}")
|
| 840 |
finally:
|
| 841 |
+
if global_lock.locked():
|
| 842 |
+
global_lock.release()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 843 |
st.session_state.is_running = False
|
| 844 |
st.session_state.start_pipeline = False
|
| 845 |
st.session_state.resume_pipeline = False
|