GuXiaopeng commited on
Commit
41c2250
·
verified ·
1 Parent(s): a79975e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -27
app.py CHANGED
@@ -177,7 +177,6 @@ def resolve_empirical_data(extracted_vars=None):
177
  def async_translate_task(agent, en_text, placeholder, target_lang, quarantine_flag):
178
  try:
179
  sys_p = f"Translate into {target_lang}. Preserve formatting and [CITE-XX]. Output ONLY the translation."
180
- # 使用非流式调用,以节省并发时的系统和网络资源
181
  trans_text = agent.call_deepseek(sys_p, f"TEXT:\n{en_text}", max_tokens=6000, model_name="deepseek-chat")
182
  trans_resolved = agent.resolve_citations(trans_text, quarantine=quarantine_flag)
183
  placeholder.markdown(trans_resolved)
@@ -465,7 +464,14 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
465
  pb.progress(14, text="⚓ 生成锚点...")
466
 
467
  original_anchor_dir = APP_CONFIG.get('anchor_generation_directive', '')
468
- APP_CONFIG['anchor_generation_directive'] = original_anchor_dir + "\n[LENGTH MANDATE] The Abstract MUST be comprehensive and detailed, containing at least 250-350 words. Thoroughly cover the research background, specific methodology, main empirical findings, and theoretical/practical implications."
 
 
 
 
 
 
 
469
 
470
  abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
471
 
@@ -572,7 +578,7 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
572
  current_cite_idx += num_cites
573
 
574
  translation_executor = ThreadPoolExecutor(max_workers=3)
575
- async_translation_tasks = []
576
 
577
  for i, block in enumerate(ui_blocks):
578
  if generation_aborted:
@@ -588,6 +594,28 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
588
  remaining_sections -= 1
589
  continue
590
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
591
  remaining_sections -= 1
592
  adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
593
  adjusted_target = min(int(SAFE_CHUNK_WORDS * 1.5), max(50, int(sec['target_words'] + adjustment)))
@@ -713,7 +741,6 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
713
 
714
  en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
715
  en_ph.markdown(en_resolved)
716
- full_draft_en += en_resolved + "\n\n"
717
 
718
  agent._extract_memory_from_text(en_draft_clean, sec_title)
719
  words_tail = en_draft_clean.split()
@@ -728,42 +755,46 @@ if st.session_state.start_pipeline or st.session_state.resume_pipeline:
728
 
729
  trans_ph.info("⏳ 英文已完成,正在后台异步翻译...")
730
 
731
- # 获取当前主线程的 Streamlit 上下文
732
  ctx = get_script_run_ctx()
733
-
734
- # 定义包装器,在子线程内强制绑定��下文
735
  def thread_wrapper(agent_obj, text, ph, lang, q_flag):
736
  add_script_run_ctx(threading.current_thread(), ctx)
737
  return async_translate_task(agent_obj, text, ph, lang, q_flag)
738
 
739
- # 提交带上下文的包装器函数到线程池
740
  future = translation_executor.submit(thread_wrapper, agent, en_draft_clean, trans_ph, target_lang, is_quarantined)
741
- async_translation_tasks.append({"name": display_name, "future": future})
 
 
 
 
 
 
 
742
 
743
  except Exception as e:
744
  en_ph.error("🚨 节点异常已熔断。")
745
  st.error(f"异常: {e} | 💥 系统已保存断点,随时可恢复。")
746
  generation_aborted = True
747
  break
748
-
749
- state["completed_sections"].append(display_name)
750
- state["full_draft_en"] = full_draft_en
751
- state["context_tail"] = context_tail
752
- state["agent_state"] = agent.export_state()
753
-
754
- os.makedirs(WORKSPACE_DIR, exist_ok=True)
755
- with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
756
- json.dump(state, f, ensure_ascii=False)
757
 
758
- if not generation_aborted and async_translation_tasks:
759
- with st.spinner(f"⏳ 英文底稿已全部生成完毕!正在等待后台 {len(async_translation_tasks)} 个异步翻译任务收尾..."):
760
- for task in async_translation_tasks:
761
- try:
762
- translated_text = task["future"].result()
763
- if translated_text:
764
- full_draft_translated += translated_text + "\n\n"
765
- except Exception as e:
766
- logging.error(f"翻译任务 {task['name']} 获取结果失败: {e}")
 
 
 
 
 
 
 
 
 
 
767
 
768
  if not generation_aborted and full_draft_en.strip():
769
  pb.progress(96, text="📦 打包DOCX...")
 
177
  def async_translate_task(agent, en_text, placeholder, target_lang, quarantine_flag):
178
  try:
179
  sys_p = f"Translate into {target_lang}. Preserve formatting and [CITE-XX]. Output ONLY the translation."
 
180
  trans_text = agent.call_deepseek(sys_p, f"TEXT:\n{en_text}", max_tokens=6000, model_name="deepseek-chat")
181
  trans_resolved = agent.resolve_citations(trans_text, quarantine=quarantine_flag)
182
  placeholder.markdown(trans_resolved)
 
464
  pb.progress(14, text="⚓ 生成锚点...")
465
 
466
  original_anchor_dir = APP_CONFIG.get('anchor_generation_directive', '')
467
+
468
+ # 【修复 2:针对克隆模式的摘要长度进行强硬扩写要求】
469
+ if st.session_state.run_mode == "clone":
470
+ length_mandate = "\n[LENGTH MANDATE] The Abstract MUST be extremely comprehensive and detailed. It MUST be at least 50-60 words LONGER than the reference paper's abstract. Aim for 300-400 words. Thoroughly cover the research background, specific methodology, main empirical findings, and theoretical/practical implications."
471
+ else:
472
+ length_mandate = "\n[LENGTH MANDATE] The Abstract MUST be comprehensive and detailed, containing at least 300-400 words. Thoroughly cover the research background, specific methodology, main empirical findings, and theoretical/practical implications."
473
+
474
+ APP_CONFIG['anchor_generation_directive'] = original_anchor_dir + length_mandate
475
 
476
  abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
477
 
 
578
  current_cite_idx += num_cites
579
 
580
  translation_executor = ThreadPoolExecutor(max_workers=3)
581
+ previous_task = None
582
 
583
  for i, block in enumerate(ui_blocks):
584
  if generation_aborted:
 
594
  remaining_sections -= 1
595
  continue
596
 
597
+ # 【修复 1:断点状态同步原子化】
598
+ if previous_task:
599
+ with st.spinner(f"⏳ 正在同步保存上一节【{previous_task['name']}】的翻译状态..."):
600
+ try:
601
+ trans_text = previous_task["future"].result()
602
+ if trans_text:
603
+ full_draft_translated += trans_text + "\n\n"
604
+ except Exception as e:
605
+ logging.error(f"翻译任务失败: {e}")
606
+
607
+ full_draft_en += previous_task["en_text"] + "\n\n"
608
+ state["completed_sections"].append(previous_task["name"])
609
+ state["full_draft_translated"] = full_draft_translated
610
+ state["full_draft_en"] = full_draft_en
611
+ state["context_tail"] = previous_task["context_tail"]
612
+ state["agent_state"] = agent.export_state()
613
+
614
+ os.makedirs(WORKSPACE_DIR, exist_ok=True)
615
+ with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
616
+ json.dump(state, f, ensure_ascii=False)
617
+ previous_task = None
618
+
619
  remaining_sections -= 1
620
  adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
621
  adjusted_target = min(int(SAFE_CHUNK_WORDS * 1.5), max(50, int(sec['target_words'] + adjustment)))
 
741
 
742
  en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
743
  en_ph.markdown(en_resolved)
 
744
 
745
  agent._extract_memory_from_text(en_draft_clean, sec_title)
746
  words_tail = en_draft_clean.split()
 
755
 
756
  trans_ph.info("⏳ 英文已完成,正在后台异步翻译...")
757
 
 
758
  ctx = get_script_run_ctx()
 
 
759
  def thread_wrapper(agent_obj, text, ph, lang, q_flag):
760
  add_script_run_ctx(threading.current_thread(), ctx)
761
  return async_translate_task(agent_obj, text, ph, lang, q_flag)
762
 
 
763
  future = translation_executor.submit(thread_wrapper, agent, en_draft_clean, trans_ph, target_lang, is_quarantined)
764
+
765
+ # 将任务打包暂存,待下一节循环开始时强制原子化同步保存,确保断点无损
766
+ previous_task = {
767
+ "name": display_name,
768
+ "future": future,
769
+ "en_text": en_resolved,
770
+ "context_tail": context_tail
771
+ }
772
 
773
  except Exception as e:
774
  en_ph.error("🚨 节点异常已熔断。")
775
  st.error(f"异常: {e} | 💥 系统已保存断点,随时可恢复。")
776
  generation_aborted = True
777
  break
 
 
 
 
 
 
 
 
 
778
 
779
+ # 循环结束后的收尾:处理最后一条挂起的翻译同步任务
780
+ if not generation_aborted and previous_task:
781
+ with st.spinner(f"⏳ 正在同步保存最后一节【{previous_task['name']}】的翻译状态..."):
782
+ try:
783
+ trans_text = previous_task["future"].result()
784
+ if trans_text:
785
+ full_draft_translated += trans_text + "\n\n"
786
+ except Exception as e:
787
+ logging.error(f"翻译任务失败: {e}")
788
+
789
+ full_draft_en += previous_task["en_text"] + "\n\n"
790
+ state["completed_sections"].append(previous_task["name"])
791
+ state["full_draft_translated"] = full_draft_translated
792
+ state["full_draft_en"] = full_draft_en
793
+ state["context_tail"] = previous_task["context_tail"]
794
+ state["agent_state"] = agent.export_state()
795
+
796
+ with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
797
+ json.dump(state, f, ensure_ascii=False)
798
 
799
  if not generation_aborted and full_draft_en.strip():
800
  pb.progress(96, text="📦 打包DOCX...")