Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -36,12 +36,54 @@ os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
|
|
| 36 |
WORKSPACE_DIR = APP_CONFIG.get("workspace_dir", ".workspace")
|
| 37 |
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 38 |
CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")
|
| 39 |
-
|
| 40 |
OUTPUT_DIR = "outputs"
|
| 41 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 42 |
|
| 43 |
META_SECTIONS_BLACKLIST = set(APP_CONFIG["blacklists"]["meta_sections"])
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):
|
| 46 |
lines = text.split('\n')
|
| 47 |
for i in range(len(lines)-1, max(-1, len(lines)-100), -1):
|
|
@@ -93,18 +135,23 @@ def check_password():
|
|
| 93 |
def get_global_lock():
|
| 94 |
return threading.Lock()
|
| 95 |
|
|
|
|
| 96 |
check_password()
|
| 97 |
global_lock = get_global_lock()
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
if not
|
| 104 |
st.markdown("<h3 style='text-align: center; color: #e6a23c;'>⏳ 系统忙碌 / System Busy</h3>", unsafe_allow_html=True)
|
| 105 |
st.warning("🚨 有小伙伴正在写作中")
|
| 106 |
-
st.info("💡 预计
|
| 107 |
-
st.stop()
|
|
|
|
| 108 |
|
| 109 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 110 |
if n_constructs == 1: return np.array([[1.0]])
|
|
@@ -216,58 +263,60 @@ if os.path.exists(CHECKPOINT_FILE) and not (st.session_state.is_running or st.se
|
|
| 216 |
st.warning("⚠️ 系统检测到上次因网络或意外中断的未完成论文任务。")
|
| 217 |
colA, colB = st.columns([1, 1])
|
| 218 |
if colA.button("🔄 恢复断点续传 (Resume Progress)", key="resume_task"):
|
| 219 |
-
if
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
| 225 |
if colB.button("🗑️ 清除临时数据 (Clear Garbage)", key="clear_task"):
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
try: global_lock.release()
|
| 232 |
except: pass
|
| 233 |
-
|
|
|
|
| 234 |
st.markdown("---")
|
| 235 |
|
| 236 |
topic = st.text_input(ui["topic_label"], value="Generative Artificial Intelligence in Ubiquitous Learning: Evaluating a Chatbot-based Recommendation Engine for Personalized and Context-aware Education", disabled=st.session_state.is_running)
|
| 237 |
keywords = st.text_input(ui["keywords_label"], value="Ubiquitous computing; Context awareness; Deep learning; Personalized educational; Educational technologies; HCI; Recommendation system; LLMs; Generative AI; ChatGPT; Prompting engineering; Few-shot prompting", disabled=st.session_state.is_running)
|
| 238 |
words = st.number_input(ui["words_label"], min_value=12000, max_value=25000, value=20000, step=1000, disabled=st.session_state.is_running)
|
| 239 |
|
| 240 |
-
|
| 241 |
-
# [UI 重塑] 废除 Wizard/Clone,全面拥抱 AMJ/ASQ 双轨制
|
| 242 |
-
# =====================================================================
|
| 243 |
-
tab_amj, tab_asq = st.tabs(["✨ 定量实证研究 (AMJ 引擎)", "📝 定性案例研究 (ASQ 引擎)"])
|
| 244 |
|
| 245 |
with tab_amj:
|
| 246 |
st.markdown("### 📊 定量研究配置 (Academy of Management Journal Style)")
|
| 247 |
st.info("💡 该模式聚焦理论演绎、假设检验与因果推断。结构锁定为:引言、理论与假设、方法、结果、讨论、结论。")
|
| 248 |
-
uploaded_papers_amj = st.file_uploader("1. 上传核心参考论文 (可选,仅限PDF
|
| 249 |
-
uploaded_data_amj = st.file_uploader("2. 上传科研数据表 (可选,仅限Excel/CSV
|
| 250 |
|
| 251 |
if st.button("🚀 启动 AMJ 模式生成", disabled=st.session_state.is_running, key="btn_amj"):
|
| 252 |
-
if
|
| 253 |
-
|
|
|
|
| 254 |
else:
|
| 255 |
-
|
| 256 |
st.session_state.run_mode = "amj"
|
| 257 |
st.session_state.start_pipeline = True
|
| 258 |
st.rerun()
|
| 259 |
|
| 260 |
with tab_asq:
|
| 261 |
st.markdown("### 📝 定性研究配置 (Administrative Science Quarterly Style)")
|
| 262 |
-
st.info("💡 该模式聚焦现象发现、意义建构与扎根理论(Gioia方法)。结构锁定为:引言、理论框架、研究情境与方法、发现、讨论、结论。")
|
| 263 |
-
uploaded_papers_asq = st.file_uploader("1. 上传核心参考论文 (可选,仅限PDF
|
| 264 |
-
uploaded_interviews = st.file_uploader("2. 上传真实访谈/田野资料 (可选,仅限TXT/DOCX
|
| 265 |
|
| 266 |
if st.button("🚀 启动 ASQ 模式生成", disabled=st.session_state.is_running, key="btn_asq"):
|
| 267 |
-
if
|
| 268 |
-
|
|
|
|
| 269 |
else:
|
| 270 |
-
|
| 271 |
st.session_state.run_mode = "asq"
|
| 272 |
st.session_state.start_pipeline = True
|
| 273 |
st.rerun()
|
|
@@ -296,20 +345,12 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 296 |
st.stop()
|
| 297 |
|
| 298 |
if st.session_state.get("is_running", False):
|
| 299 |
-
if global_lock.locked():
|
| 300 |
-
try: global_lock.release()
|
| 301 |
-
except: pass
|
| 302 |
st.toast("🔄 检测到页面刷新或网络抖动,系统正在自动恢复进度...", icon="⚡")
|
|
|
|
| 303 |
st.session_state.is_running = False
|
| 304 |
st.session_state.start_pipeline = False
|
| 305 |
st.session_state.resume_pipeline = True
|
| 306 |
st.rerun()
|
| 307 |
-
|
| 308 |
-
if not global_lock.acquire(blocking=False):
|
| 309 |
-
st.warning("⏳ 有小伙伴在写作,预计35-45分钟后可用。")
|
| 310 |
-
st.session_state.start_pipeline = False
|
| 311 |
-
st.session_state.resume_pipeline = False
|
| 312 |
-
st.stop()
|
| 313 |
|
| 314 |
st.session_state.is_running = True
|
| 315 |
is_resume = st.session_state.resume_pipeline
|
|
@@ -319,6 +360,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 319 |
qual_engine = get_qualitative_engine(agent)
|
| 320 |
|
| 321 |
try:
|
|
|
|
| 322 |
loaded_state = None
|
| 323 |
if is_resume:
|
| 324 |
try:
|
|
@@ -357,16 +399,17 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 357 |
user_lit_context = ""
|
| 358 |
user_data_md = ""
|
| 359 |
|
| 360 |
-
# [数据与文档获取分轨]
|
| 361 |
if st.session_state.run_mode == "amj":
|
| 362 |
if uploaded_papers_amj:
|
| 363 |
user_lit_context = extract_text_from_files(uploaded_papers_amj[:20])
|
| 364 |
with st.spinner(f"🧠 正在从文献中榨取黄金数据并构建 RAG 索引..."):
|
|
|
|
| 365 |
all_paper_texts = [extract_text_from_files([f]) for f in uploaded_papers_amj[:20]]
|
| 366 |
agent.global_memory["core_golden_metadata"] = extract_golden_metadata(agent, all_paper_texts)
|
| 367 |
st.session_state.rag_engine = initialize_rag(all_paper_texts)
|
| 368 |
|
| 369 |
with st.spinner("⚙️ 正在解析定量实证数据..."):
|
|
|
|
| 370 |
_, user_data_md, msg = resolve_empirical_data(uploaded_data_amj)
|
| 371 |
st.info(msg)
|
| 372 |
|
|
@@ -374,11 +417,13 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 374 |
if uploaded_papers_asq:
|
| 375 |
user_lit_context = extract_text_from_files(uploaded_papers_asq[:20])
|
| 376 |
with st.spinner(f"🧠 正在从文献中榨取黄金数据并构建 RAG 索引..."):
|
|
|
|
| 377 |
all_paper_texts = [extract_text_from_files([f]) for f in uploaded_papers_asq[:20]]
|
| 378 |
agent.global_memory["core_golden_metadata"] = extract_golden_metadata(agent, all_paper_texts)
|
| 379 |
st.session_state.rag_engine = initialize_rag(all_paper_texts)
|
| 380 |
|
| 381 |
with st.spinner("⚙️ 正在解析访谈资料与构建定性编码树..."):
|
|
|
|
| 382 |
raw_interviews = extract_text_from_files([uploaded_interviews]) if uploaded_interviews else ""
|
| 383 |
user_data_md, msg = qual_engine.resolve_qualitative_data(topic, keywords, raw_interviews)
|
| 384 |
st.info(msg)
|
|
@@ -392,7 +437,6 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 392 |
|
| 393 |
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 394 |
|
| 395 |
-
# 动态加载对应流派的提示词
|
| 396 |
if st.session_state.run_mode == "amj":
|
| 397 |
APP_CONFIG.update(AMJ_PROMPTS)
|
| 398 |
state["prompt_config"] = AMJ_PROMPTS
|
|
@@ -401,7 +445,8 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 401 |
state["prompt_config"] = ASQ_PROMPTS
|
| 402 |
|
| 403 |
pb.progress(10, text="📚 智能文献检索...")
|
| 404 |
-
def sync_monitor_ui():
|
|
|
|
| 405 |
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度并发检索中...")
|
| 406 |
|
| 407 |
target_refs_count = 50
|
|
@@ -414,6 +459,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 414 |
st.success(f"✅ 文献扩容成功!捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 415 |
|
| 416 |
with st.spinner("🧠 正在将 API 扩容文献同步注入 RAG 引擎以提升理论深度..."):
|
|
|
|
| 417 |
if hasattr(st.session_state, "rag_engine") and st.session_state.rag_engine is not None:
|
| 418 |
st.session_state.rag_engine._initialize_chunks([refs_text])
|
| 419 |
else:
|
|
@@ -422,6 +468,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 422 |
|
| 423 |
if user_lit_context:
|
| 424 |
pb.progress(11, text="🧠 深度解析用户上传的核心文献...")
|
|
|
|
| 425 |
core_refs = agent.parse_user_core_literature(user_lit_context)
|
| 426 |
if core_refs:
|
| 427 |
refs_text = "【USER PROVIDED CORE LITERATURE】\n" + core_refs + "\n\n【RETRIEVED LITERATURE】\n" + refs_text
|
|
@@ -430,15 +477,16 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 430 |
state["refs_text"] = refs_text
|
| 431 |
|
| 432 |
pb.progress(12, text="🧠 文献综合...")
|
|
|
|
| 433 |
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 434 |
state["synthesis_result"] = synthesis_result
|
| 435 |
|
| 436 |
pb.progress(14, text="⚓ 生成锚点...")
|
|
|
|
| 437 |
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 438 |
|
| 439 |
pb.progress(15, text="📝 大纲设计与路由分发...")
|
| 440 |
-
|
| 441 |
-
# [核心修复] 使用硬编码锁死的双轨制大纲
|
| 442 |
plan = agent.generate_outline(topic, keywords, mode=st.session_state.run_mode)
|
| 443 |
en_topic = str(plan.get("en_topic", topic))
|
| 444 |
structure = plan.get("structure", [])
|
|
@@ -468,6 +516,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 468 |
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})
|
| 469 |
|
| 470 |
with st.spinner("🔄 全局预加载:正在为方法与结果章节提取专属支撑文献 (JIT Pre-fetch)..."):
|
|
|
|
| 471 |
jit_texts = agent.prefetch_jit_literature(topic, keywords, adaptive_structure)
|
| 472 |
if jit_texts:
|
| 473 |
if hasattr(st.session_state, "rag_engine") and st.session_state.rag_engine is not None:
|
|
@@ -549,6 +598,9 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 549 |
if previous_task:
|
| 550 |
with st.spinner(f"⏳ 正在同步保存上一节【{previous_task['name']}】的翻译状态..."):
|
| 551 |
try:
|
|
|
|
|
|
|
|
|
|
| 552 |
trans_text = previous_task["future"].result()
|
| 553 |
if trans_text:
|
| 554 |
full_draft_translated += trans_text + "\n\n"
|
|
@@ -601,7 +653,6 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 601 |
|
| 602 |
length_directive = f"[LANGUAGE MANDATE] Output strictly in ENGLISH.\n[LENGTH MANDATE - STRICT] Write between {int(adjusted_target * 0.9)} and {int(adjusted_target * 1.1)} words (approx {num_paragraphs} paragraphs).\n{adaptive_heading_rule}\n{table_rule}\n[FINAL CHECK] Do not output a word count statement."
|
| 603 |
|
| 604 |
-
# [架构升级] 直接使用配置的 Prompt 字典组装,物理隔离防重复
|
| 605 |
extra_directives = []
|
| 606 |
lower_sec = sec_title.lower()
|
| 607 |
golden_meta = agent.global_memory.get("core_golden_metadata", [])
|
|
@@ -636,7 +687,12 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 636 |
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 ""
|
| 637 |
|
| 638 |
action_verb = f"Generate the main section '{sec_title}'" if sec["is_first"] else f"Continue generating the subsequent paragraphs for the section '{sec_title}' (DO NOT restate the main section title)"
|
| 639 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 640 |
|
| 641 |
if agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user) > 60000:
|
| 642 |
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
|
@@ -647,17 +703,19 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 647 |
|
| 648 |
try:
|
| 649 |
with st.status(f"🤖 引擎启动: 执笔编写【{display_name}】...", expanded=True) as status:
|
|
|
|
| 650 |
st.write(f"📡 已发起 DeepSeek API 请求...")
|
| 651 |
|
| 652 |
target_model = "deepseek-chat"
|
| 653 |
st.write(f"✍️ 核心推导由 R1 完成,当前节点使用 {target_model} 高速执笔...")
|
| 654 |
|
| 655 |
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_ph.write_stream(
|
| 656 |
-
agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000, model_name=target_model)
|
| 657 |
), flags=re.DOTALL).strip()
|
| 658 |
|
| 659 |
status.update(label=f"✅ 【{display_name}】撰写完毕!", state="complete", expanded=False)
|
| 660 |
|
|
|
|
| 661 |
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 662 |
en_draft_clean = re.sub(r'(?im)^#+\s*.*\(Part\s*\d+/\d+\).*?\n+', '', en_draft_clean)
|
| 663 |
en_draft_clean = re.sub(r'(?m)^(#{2,3})\s+[\d\.\s一二三四五六七八九十、]+\s*(.*)', r'\1 \2', en_draft_clean)
|
|
@@ -710,6 +768,9 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 710 |
if not generation_aborted and previous_task:
|
| 711 |
with st.spinner(f"⏳ 正在同步保存最后一节【{previous_task['name']}】的翻译状态..."):
|
| 712 |
try:
|
|
|
|
|
|
|
|
|
|
| 713 |
trans_text = previous_task["future"].result()
|
| 714 |
if trans_text:
|
| 715 |
full_draft_translated += trans_text + "\n\n"
|
|
@@ -728,6 +789,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 728 |
|
| 729 |
if not generation_aborted and full_draft_en.strip():
|
| 730 |
pb.progress(96, text="📦 打包DOCX...")
|
|
|
|
| 731 |
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 732 |
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 733 |
|
|
@@ -801,8 +863,8 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
|
| 801 |
except Exception as e:
|
| 802 |
st.error(f"🚨 启动/恢复异常: {e}")
|
| 803 |
finally:
|
| 804 |
-
|
| 805 |
-
|
| 806 |
st.session_state.is_running = False
|
| 807 |
st.session_state.start_pipeline = False
|
| 808 |
st.session_state.resume_pipeline = False
|
|
|
|
| 36 |
WORKSPACE_DIR = APP_CONFIG.get("workspace_dir", ".workspace")
|
| 37 |
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 38 |
CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")
|
|
|
|
| 39 |
OUTPUT_DIR = "outputs"
|
| 40 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 41 |
|
| 42 |
META_SECTIONS_BLACKLIST = set(APP_CONFIG["blacklists"]["meta_sections"])
|
| 43 |
|
| 44 |
+
# =====================================================================
|
| 45 |
+
# [架构升级] 强硬的文件心跳锁机制,彻底解决跨设备/跨进程并发漏洞
|
| 46 |
+
# =====================================================================
|
| 47 |
+
HEARTBEAT_FILE = os.path.join(WORKSPACE_DIR, "heartbeat.lock")
|
| 48 |
+
HEARTBEAT_TIMEOUT = 120 # 2分钟心跳超时
|
| 49 |
+
|
| 50 |
+
def update_heartbeat():
|
| 51 |
+
try:
|
| 52 |
+
with open(HEARTBEAT_FILE, "w") as f:
|
| 53 |
+
f.write(str(time.time()))
|
| 54 |
+
except:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
def is_system_busy():
|
| 58 |
+
if not os.path.exists(HEARTBEAT_FILE):
|
| 59 |
+
return False
|
| 60 |
+
try:
|
| 61 |
+
with open(HEARTBEAT_FILE, "r") as f:
|
| 62 |
+
last_active = float(f.read().strip())
|
| 63 |
+
if time.time() - last_active < HEARTBEAT_TIMEOUT:
|
| 64 |
+
return True
|
| 65 |
+
except:
|
| 66 |
+
pass
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
def clear_heartbeat():
|
| 70 |
+
try:
|
| 71 |
+
if os.path.exists(HEARTBEAT_FILE):
|
| 72 |
+
os.remove(HEARTBEAT_FILE)
|
| 73 |
+
except:
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
def stream_with_heartbeat(generator):
|
| 77 |
+
"""包裹器:确保大模型长时间流式输出时,能够持续发送心跳,防止锁被释放"""
|
| 78 |
+
last_beat = time.time()
|
| 79 |
+
for chunk in generator:
|
| 80 |
+
now = time.time()
|
| 81 |
+
if now - last_beat > 5:
|
| 82 |
+
update_heartbeat()
|
| 83 |
+
last_beat = now
|
| 84 |
+
yield chunk
|
| 85 |
+
# =====================================================================
|
| 86 |
+
|
| 87 |
def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):
|
| 88 |
lines = text.split('\n')
|
| 89 |
for i in range(len(lines)-1, max(-1, len(lines)-100), -1):
|
|
|
|
| 135 |
def get_global_lock():
|
| 136 |
return threading.Lock()
|
| 137 |
|
| 138 |
+
# 身份校验
|
| 139 |
check_password()
|
| 140 |
global_lock = get_global_lock()
|
| 141 |
|
| 142 |
+
# =====================================================================
|
| 143 |
+
# [核心防线] 前置心跳锁检测,拦截跨设备的新用户 (提示词已还原)
|
| 144 |
+
# =====================================================================
|
| 145 |
+
is_my_session = st.session_state.get("is_running", False) or \
|
| 146 |
+
st.session_state.get("start_pipeline", False) or \
|
| 147 |
+
st.session_state.get("resume_pipeline", False)
|
| 148 |
|
| 149 |
+
if not is_my_session and is_system_busy():
|
| 150 |
st.markdown("<h3 style='text-align: center; color: #e6a23c;'>⏳ 系统忙碌 / System Busy</h3>", unsafe_allow_html=True)
|
| 151 |
st.warning("🚨 有小伙伴正在写作中")
|
| 152 |
+
st.info("💡 预计15-25分钟后可正常使用")
|
| 153 |
+
st.stop() # 绝对拦截,不给显示断点续传界面的机会
|
| 154 |
+
# =====================================================================
|
| 155 |
|
| 156 |
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 157 |
if n_constructs == 1: return np.array([[1.0]])
|
|
|
|
| 263 |
st.warning("⚠️ 系统检测到上次因网络或意外中断的未完成论文任务。")
|
| 264 |
colA, colB = st.columns([1, 1])
|
| 265 |
if colA.button("🔄 恢复断点续传 (Resume Progress)", key="resume_task"):
|
| 266 |
+
if is_system_busy():
|
| 267 |
+
# [修正点] 还原为原版的锁定提示词
|
| 268 |
+
st.warning("⏳ 有小伙伴在写作,预计15-25分钟后可用。")
|
| 269 |
+
else:
|
| 270 |
+
update_heartbeat()
|
| 271 |
+
st.session_state.resume_pipeline = True
|
| 272 |
+
st.session_state.start_pipeline = False
|
| 273 |
+
st.rerun()
|
| 274 |
+
|
| 275 |
if colB.button("🗑️ 清除临时数据 (Clear Garbage)", key="clear_task"):
|
| 276 |
+
if is_system_busy():
|
| 277 |
+
# [修正点] 还原为原版的锁定提示词
|
| 278 |
+
st.warning("⏳ 有小伙伴在写作,预计15-25分钟后可用。")
|
| 279 |
+
else:
|
| 280 |
+
try: os.remove(CHECKPOINT_FILE)
|
|
|
|
| 281 |
except: pass
|
| 282 |
+
clear_heartbeat()
|
| 283 |
+
st.rerun()
|
| 284 |
st.markdown("---")
|
| 285 |
|
| 286 |
topic = st.text_input(ui["topic_label"], value="Generative Artificial Intelligence in Ubiquitous Learning: Evaluating a Chatbot-based Recommendation Engine for Personalized and Context-aware Education", disabled=st.session_state.is_running)
|
| 287 |
keywords = st.text_input(ui["keywords_label"], value="Ubiquitous computing; Context awareness; Deep learning; Personalized educational; Educational technologies; HCI; Recommendation system; LLMs; Generative AI; ChatGPT; Prompting engineering; Few-shot prompting", disabled=st.session_state.is_running)
|
| 288 |
words = st.number_input(ui["words_label"], min_value=12000, max_value=25000, value=20000, step=1000, disabled=st.session_state.is_running)
|
| 289 |
|
| 290 |
+
tab_amj, tab_asq = st.tabs(["✨ 定量研究 (AMJ 引擎)", "📝 定性研究 (ASQ 引擎)"])
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
with tab_amj:
|
| 293 |
st.markdown("### 📊 定量研究配置 (Academy of Management Journal Style)")
|
| 294 |
st.info("💡 该模式聚焦理论演绎、假设检验与因果推断。结构锁定为:引言、理论与假设、方法、结果、讨论、结论。")
|
| 295 |
+
uploaded_papers_amj = st.file_uploader("1. 上传核心参考论文 (可选,仅限PDF/DOCX,建议1-20篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, key="up_amj_ref", disabled=st.session_state.is_running)
|
| 296 |
+
uploaded_data_amj = st.file_uploader("2. 上传科研数据表 (可选,仅限Excel/CSV)", type=["csv", "xlsx", "xls"], key="up_amj_data", disabled=st.session_state.is_running)
|
| 297 |
|
| 298 |
if st.button("🚀 启动 AMJ 模式生成", disabled=st.session_state.is_running, key="btn_amj"):
|
| 299 |
+
if is_system_busy():
|
| 300 |
+
# [修正点] 还原为原版的锁定提示词
|
| 301 |
+
st.warning("⏳ 有小伙伴在写作,预计15-25分钟后可用。")
|
| 302 |
else:
|
| 303 |
+
update_heartbeat()
|
| 304 |
st.session_state.run_mode = "amj"
|
| 305 |
st.session_state.start_pipeline = True
|
| 306 |
st.rerun()
|
| 307 |
|
| 308 |
with tab_asq:
|
| 309 |
st.markdown("### 📝 定性研究配置 (Administrative Science Quarterly Style)")
|
| 310 |
+
st.info("💡 该模式聚焦现象发现、意义建构与扎根理论(Gioia方法)。结构锁定为:引言、理论框架、研究情境与方法、发现(厚数据叙事)、讨论、结论。")
|
| 311 |
+
uploaded_papers_asq = st.file_uploader("1. 上传核心参考论文 (可选,仅限PDF/DOCX,建议1-20篇)", type=["pdf", "doc", "docx"], accept_multiple_files=True, key="up_asq_ref", disabled=st.session_state.is_running)
|
| 312 |
+
uploaded_interviews = st.file_uploader("2. 上传真实访谈/田野资料 (可选,仅限TXT/PDF/DOCX)", type=["txt", "pdf", "doc", "docx"], key="up_asq_data", disabled=st.session_state.is_running)
|
| 313 |
|
| 314 |
if st.button("🚀 启动 ASQ 模式生成", disabled=st.session_state.is_running, key="btn_asq"):
|
| 315 |
+
if is_system_busy():
|
| 316 |
+
# [修正点] 还原为原版的锁定提示词
|
| 317 |
+
st.warning("⏳ 有小伙伴在写作,预计15-25分钟后可用。")
|
| 318 |
else:
|
| 319 |
+
update_heartbeat()
|
| 320 |
st.session_state.run_mode = "asq"
|
| 321 |
st.session_state.start_pipeline = True
|
| 322 |
st.rerun()
|
|
|
|
| 345 |
st.stop()
|
| 346 |
|
| 347 |
if st.session_state.get("is_running", False):
|
|
|
|
|
|
|
|
|
|
| 348 |
st.toast("🔄 检测到页面刷新或网络抖动,系统正在自动恢复进度...", icon="⚡")
|
| 349 |
+
update_heartbeat() # 确保刷新不断连
|
| 350 |
st.session_state.is_running = False
|
| 351 |
st.session_state.start_pipeline = False
|
| 352 |
st.session_state.resume_pipeline = True
|
| 353 |
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
|
| 355 |
st.session_state.is_running = True
|
| 356 |
is_resume = st.session_state.resume_pipeline
|
|
|
|
| 360 |
qual_engine = get_qualitative_engine(agent)
|
| 361 |
|
| 362 |
try:
|
| 363 |
+
update_heartbeat()
|
| 364 |
loaded_state = None
|
| 365 |
if is_resume:
|
| 366 |
try:
|
|
|
|
| 399 |
user_lit_context = ""
|
| 400 |
user_data_md = ""
|
| 401 |
|
|
|
|
| 402 |
if st.session_state.run_mode == "amj":
|
| 403 |
if uploaded_papers_amj:
|
| 404 |
user_lit_context = extract_text_from_files(uploaded_papers_amj[:20])
|
| 405 |
with st.spinner(f"🧠 正在从文献中榨取黄金数据并构建 RAG 索引..."):
|
| 406 |
+
update_heartbeat()
|
| 407 |
all_paper_texts = [extract_text_from_files([f]) for f in uploaded_papers_amj[:20]]
|
| 408 |
agent.global_memory["core_golden_metadata"] = extract_golden_metadata(agent, all_paper_texts)
|
| 409 |
st.session_state.rag_engine = initialize_rag(all_paper_texts)
|
| 410 |
|
| 411 |
with st.spinner("⚙️ 正在解析定量实证数据..."):
|
| 412 |
+
update_heartbeat()
|
| 413 |
_, user_data_md, msg = resolve_empirical_data(uploaded_data_amj)
|
| 414 |
st.info(msg)
|
| 415 |
|
|
|
|
| 417 |
if uploaded_papers_asq:
|
| 418 |
user_lit_context = extract_text_from_files(uploaded_papers_asq[:20])
|
| 419 |
with st.spinner(f"🧠 正在从文献中榨取黄金数据并构建 RAG 索引..."):
|
| 420 |
+
update_heartbeat()
|
| 421 |
all_paper_texts = [extract_text_from_files([f]) for f in uploaded_papers_asq[:20]]
|
| 422 |
agent.global_memory["core_golden_metadata"] = extract_golden_metadata(agent, all_paper_texts)
|
| 423 |
st.session_state.rag_engine = initialize_rag(all_paper_texts)
|
| 424 |
|
| 425 |
with st.spinner("⚙️ 正在解析访谈资料与构建定性编码树..."):
|
| 426 |
+
update_heartbeat()
|
| 427 |
raw_interviews = extract_text_from_files([uploaded_interviews]) if uploaded_interviews else ""
|
| 428 |
user_data_md, msg = qual_engine.resolve_qualitative_data(topic, keywords, raw_interviews)
|
| 429 |
st.info(msg)
|
|
|
|
| 437 |
|
| 438 |
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 439 |
|
|
|
|
| 440 |
if st.session_state.run_mode == "amj":
|
| 441 |
APP_CONFIG.update(AMJ_PROMPTS)
|
| 442 |
state["prompt_config"] = AMJ_PROMPTS
|
|
|
|
| 445 |
state["prompt_config"] = ASQ_PROMPTS
|
| 446 |
|
| 447 |
pb.progress(10, text="📚 智能文献检索...")
|
| 448 |
+
def sync_monitor_ui():
|
| 449 |
+
update_heartbeat()
|
| 450 |
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度并发检索中...")
|
| 451 |
|
| 452 |
target_refs_count = 50
|
|
|
|
| 459 |
st.success(f"✅ 文献扩容成功!捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 460 |
|
| 461 |
with st.spinner("🧠 正在将 API 扩容文献同步注入 RAG 引擎以提升理论深度..."):
|
| 462 |
+
update_heartbeat()
|
| 463 |
if hasattr(st.session_state, "rag_engine") and st.session_state.rag_engine is not None:
|
| 464 |
st.session_state.rag_engine._initialize_chunks([refs_text])
|
| 465 |
else:
|
|
|
|
| 468 |
|
| 469 |
if user_lit_context:
|
| 470 |
pb.progress(11, text="🧠 深度解析用户上传的核心文献...")
|
| 471 |
+
update_heartbeat()
|
| 472 |
core_refs = agent.parse_user_core_literature(user_lit_context)
|
| 473 |
if core_refs:
|
| 474 |
refs_text = "【USER PROVIDED CORE LITERATURE】\n" + core_refs + "\n\n【RETRIEVED LITERATURE】\n" + refs_text
|
|
|
|
| 477 |
state["refs_text"] = refs_text
|
| 478 |
|
| 479 |
pb.progress(12, text="🧠 文献综合...")
|
| 480 |
+
update_heartbeat()
|
| 481 |
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 482 |
state["synthesis_result"] = synthesis_result
|
| 483 |
|
| 484 |
pb.progress(14, text="⚓ 生成锚点...")
|
| 485 |
+
update_heartbeat()
|
| 486 |
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 487 |
|
| 488 |
pb.progress(15, text="📝 大纲设计与路由分发...")
|
| 489 |
+
update_heartbeat()
|
|
|
|
| 490 |
plan = agent.generate_outline(topic, keywords, mode=st.session_state.run_mode)
|
| 491 |
en_topic = str(plan.get("en_topic", topic))
|
| 492 |
structure = plan.get("structure", [])
|
|
|
|
| 516 |
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})
|
| 517 |
|
| 518 |
with st.spinner("🔄 全局预加载:正在为方法与结果章节提取专属支撑文献 (JIT Pre-fetch)..."):
|
| 519 |
+
update_heartbeat()
|
| 520 |
jit_texts = agent.prefetch_jit_literature(topic, keywords, adaptive_structure)
|
| 521 |
if jit_texts:
|
| 522 |
if hasattr(st.session_state, "rag_engine") and st.session_state.rag_engine is not None:
|
|
|
|
| 598 |
if previous_task:
|
| 599 |
with st.spinner(f"⏳ 正在同步保存上一节【{previous_task['name']}】的翻译状态..."):
|
| 600 |
try:
|
| 601 |
+
while not previous_task["future"].done():
|
| 602 |
+
update_heartbeat() # 等待翻译时继续发心跳
|
| 603 |
+
time.sleep(1)
|
| 604 |
trans_text = previous_task["future"].result()
|
| 605 |
if trans_text:
|
| 606 |
full_draft_translated += trans_text + "\n\n"
|
|
|
|
| 653 |
|
| 654 |
length_directive = f"[LANGUAGE MANDATE] Output strictly in ENGLISH.\n[LENGTH MANDATE - STRICT] Write between {int(adjusted_target * 0.9)} and {int(adjusted_target * 1.1)} words (approx {num_paragraphs} paragraphs).\n{adaptive_heading_rule}\n{table_rule}\n[FINAL CHECK] Do not output a word count statement."
|
| 655 |
|
|
|
|
| 656 |
extra_directives = []
|
| 657 |
lower_sec = sec_title.lower()
|
| 658 |
golden_meta = agent.global_memory.get("core_golden_metadata", [])
|
|
|
|
| 687 |
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 ""
|
| 688 |
|
| 689 |
action_verb = f"Generate the main section '{sec_title}'" if sec["is_first"] else f"Continue generating the subsequent paragraphs for the section '{sec_title}' (DO NOT restate the main section title)"
|
| 690 |
+
|
| 691 |
+
# [核心修复] 加入已经完成的章节列表,产生白熊隔离效应
|
| 692 |
+
done_list = ", ".join(completed_sections)
|
| 693 |
+
anti_repeat = f"\n[ANTI-REPETITION MANDATE] You have already generated: [{done_list}]. Do NOT restate core arguments, research gaps, or background introductions belonging to those completed sections." if done_list else ""
|
| 694 |
+
|
| 695 |
+
base_user = f"{action_verb}.\n{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{anti_repeat}\n{memory_block}\nSynthesis: {synthesis_result}\n{wiz_data_injection}\nPrevious Tail: ...{context_tail}...\nIMPORTANT: Output final text."
|
| 696 |
|
| 697 |
if agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user) > 60000:
|
| 698 |
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
|
|
|
| 703 |
|
| 704 |
try:
|
| 705 |
with st.status(f"🤖 引擎启动: 执笔编写【{display_name}】...", expanded=True) as status:
|
| 706 |
+
update_heartbeat()
|
| 707 |
st.write(f"📡 已发起 DeepSeek API 请求...")
|
| 708 |
|
| 709 |
target_model = "deepseek-chat"
|
| 710 |
st.write(f"✍️ 核心推导由 R1 完成,当前节点使用 {target_model} 高速执笔...")
|
| 711 |
|
| 712 |
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_ph.write_stream(
|
| 713 |
+
stream_with_heartbeat(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000, model_name=target_model))
|
| 714 |
), flags=re.DOTALL).strip()
|
| 715 |
|
| 716 |
status.update(label=f"✅ 【{display_name}】撰写完毕!", state="complete", expanded=False)
|
| 717 |
|
| 718 |
+
update_heartbeat()
|
| 719 |
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 720 |
en_draft_clean = re.sub(r'(?im)^#+\s*.*\(Part\s*\d+/\d+\).*?\n+', '', en_draft_clean)
|
| 721 |
en_draft_clean = re.sub(r'(?m)^(#{2,3})\s+[\d\.\s一二三四五六七八九十、]+\s*(.*)', r'\1 \2', en_draft_clean)
|
|
|
|
| 768 |
if not generation_aborted and previous_task:
|
| 769 |
with st.spinner(f"⏳ 正在同步保存最后一节【{previous_task['name']}】的翻译状态..."):
|
| 770 |
try:
|
| 771 |
+
while not previous_task["future"].done():
|
| 772 |
+
update_heartbeat()
|
| 773 |
+
time.sleep(1)
|
| 774 |
trans_text = previous_task["future"].result()
|
| 775 |
if trans_text:
|
| 776 |
full_draft_translated += trans_text + "\n\n"
|
|
|
|
| 789 |
|
| 790 |
if not generation_aborted and full_draft_en.strip():
|
| 791 |
pb.progress(96, text="📦 打包DOCX...")
|
| 792 |
+
update_heartbeat()
|
| 793 |
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 794 |
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 795 |
|
|
|
|
| 863 |
except Exception as e:
|
| 864 |
st.error(f"🚨 启动/恢复异常: {e}")
|
| 865 |
finally:
|
| 866 |
+
# [核心防线解锁]:确保任何情况中止后,释放全局锁定
|
| 867 |
+
clear_heartbeat()
|
| 868 |
st.session_state.is_running = False
|
| 869 |
st.session_state.start_pipeline = False
|
| 870 |
st.session_state.resume_pipeline = False
|