Spaces:
Sleeping
Sleeping
Update utils/file_parser.py
Browse files- utils/file_parser.py +72 -857
utils/file_parser.py
CHANGED
|
@@ -1,864 +1,79 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
-
"""Smart Draft - Empirical State Machine (HITL & Hybrid Clone Architecture)"""
|
| 3 |
-
|
| 4 |
import streamlit as st
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
import
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 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 |
-
|
| 31 |
-
# ==========================================
|
| 32 |
-
# 0. 全局常量、工具函数与核心环境准备
|
| 33 |
-
# ==========================================
|
| 34 |
-
os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"
|
| 35 |
-
os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
|
| 36 |
-
|
| 37 |
-
# 🏗️ 架构重构 1:集中化配置非正文黑名单,消除硬编码 (统一从 APP_CONFIG 读取)
|
| 38 |
-
default_meta_sections = {
|
| 39 |
-
"abstract", "keyword", "keywords", "摘要", "关键词", "关键字",
|
| 40 |
-
"reference", "references", "reference list", "参考文献",
|
| 41 |
-
"acknowledgment", "acknowledgements", "致谢",
|
| 42 |
-
"аннотация", "ключевые слова", "түйіндеме", "кілт сөздер"
|
| 43 |
-
}
|
| 44 |
-
META_SECTIONS_BLACKLIST = set(APP_CONFIG.get("blacklists", {}).get("meta_sections", default_meta_sections))
|
| 45 |
-
|
| 46 |
-
# 🏗️ 架构重构 2:顶层纯函数提取,避免正则灾难性回溯
|
| 47 |
-
def clean_trailing_references(text, keywords=("reference", "references", "reference list", "参考文献")):
|
| 48 |
-
"""使用行指针逆向扫描,安全且极速地剥离尾部引用的脏数据"""
|
| 49 |
-
lines = text.split('\n')
|
| 50 |
-
for i in range(len(lines)-1, max(-1, len(lines)-100), -1):
|
| 51 |
-
if any(re.match(rf'^##?\s*{kw}', lines[i], re.IGNORECASE) for kw in keywords):
|
| 52 |
-
return '\n'.join(lines[:i]).strip()
|
| 53 |
-
return text.strip()
|
| 54 |
-
|
| 55 |
-
# 🏗️ 架构重构 3:全局降维拦截器,保护文档树层级
|
| 56 |
-
def clean_markdown_headings(text):
|
| 57 |
-
"""将文本中的 Markdown 标题强制降级为内联加粗,用于保护摘要等特殊元数据区域"""
|
| 58 |
-
return re.sub(r'(?m)^#+\s+(.*)$', r'**\1**', text)
|
| 59 |
-
|
| 60 |
-
global_ds_key = os.environ.get("DEEPSEEK_API_KEY", "")
|
| 61 |
-
if not global_ds_key:
|
| 62 |
-
try: global_ds_key = st.secrets.get("DEEPSEEK_API_KEY", "")
|
| 63 |
-
except: pass
|
| 64 |
-
|
| 65 |
-
global_s2_key = os.environ.get("S2_API_KEY", "")
|
| 66 |
-
if not global_s2_key:
|
| 67 |
-
try: global_s2_key = st.secrets.get("S2_API_KEY", "")
|
| 68 |
-
except: pass
|
| 69 |
-
|
| 70 |
-
# 状态机:断点续传工作区配置 (消除硬编码)
|
| 71 |
-
WORKSPACE_DIR = APP_CONFIG.get("workspace_dir", ".workspace")
|
| 72 |
-
CHECKPOINT_FILE = os.path.join(WORKSPACE_DIR, "snapshot.json")
|
| 73 |
-
if not os.path.exists(WORKSPACE_DIR):
|
| 74 |
-
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 75 |
-
|
| 76 |
-
# 微信拦截与提示
|
| 77 |
-
WECHAT_BLOCKER_JS = """
|
| 78 |
-
<script>
|
| 79 |
-
try {
|
| 80 |
-
var ua = navigator.userAgent.toLowerCase();
|
| 81 |
-
if (ua.indexOf('micromessenger') !== -1) {
|
| 82 |
-
var parentDoc = window.parent.document;
|
| 83 |
-
if (!parentDoc.getElementById('wx-blocker')) {
|
| 84 |
-
var overlay = parentDoc.createElement('div');
|
| 85 |
-
overlay.id = 'wx-blocker';
|
| 86 |
-
overlay.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;background:#1a365d;z-index:9999999;color:white;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;font-family:sans-serif;padding:30px;box-sizing:border-box;';
|
| 87 |
-
overlay.innerHTML = '<h2 style="font-size:26px;margin-bottom:15px;font-weight:bold;">环境受限 / Restricted</h2><p style="font-size:18px;line-height:1.6;color:#e2e8f0;max-width:100%;">为了保障最终双语 ZIP 压缩包正常下载,<b>本系统禁止在微信内直接运行</b>。<br><br>👉 <b>请点击右上角 [···] 菜单,选择“在浏览器打开” (Open in Browser)</b></p>';
|
| 88 |
-
parentDoc.body.appendChild(overlay);
|
| 89 |
-
}
|
| 90 |
-
}
|
| 91 |
-
} catch (e) {}
|
| 92 |
-
</script>
|
| 93 |
-
"""
|
| 94 |
-
components.html(WECHAT_BLOCKER_JS, height=0, width=0)
|
| 95 |
-
|
| 96 |
-
# ==========================================
|
| 97 |
-
# 🚨 访问控制与无感防死锁自愈锁 (AutoExpiringLock)
|
| 98 |
-
# ==========================================
|
| 99 |
-
def check_password():
|
| 100 |
-
expected_password = os.environ.get("APP_PASSWORD", "")
|
| 101 |
-
if not expected_password:
|
| 102 |
-
try: expected_password = st.secrets.get("APP_PASSWORD", "")
|
| 103 |
-
except: pass
|
| 104 |
-
|
| 105 |
-
if not expected_password:
|
| 106 |
-
return True
|
| 107 |
-
|
| 108 |
-
if "password_correct" not in st.session_state:
|
| 109 |
-
st.session_state["password_correct"] = False
|
| 110 |
-
|
| 111 |
-
if not st.session_state["password_correct"]:
|
| 112 |
-
st.markdown("<h3 style='text-align: center;'>🔒 系统已锁定 / System Locked</h3>", unsafe_allow_html=True)
|
| 113 |
-
st.markdown("<p style='text-align: center;'>本系统为高算力私人节点,请输入授权凭证。</p>", unsafe_allow_html=True)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
if pwd == expected_password:
|
| 118 |
-
st.session_state["password_correct"] = True
|
| 119 |
-
st.rerun()
|
| 120 |
-
else:
|
| 121 |
-
st.error("❌ 凭证错误,拒绝访问。")
|
| 122 |
-
st.stop()
|
| 123 |
-
return True
|
| 124 |
-
|
| 125 |
-
class AutoExpiringLock:
|
| 126 |
-
"""自愈锁机制:如果被锁超过 30 分钟,自动判定为死锁并释放。"""
|
| 127 |
-
def __init__(self, timeout=1800):
|
| 128 |
-
self.lock = threading.Lock()
|
| 129 |
-
self.locked_at = 0
|
| 130 |
-
self.timeout = timeout
|
| 131 |
-
|
| 132 |
-
def acquire(self, blocking=False):
|
| 133 |
-
now = time.time()
|
| 134 |
-
if self.lock.locked():
|
| 135 |
-
if now - self.locked_at > self.timeout:
|
| 136 |
-
try: self.lock.release()
|
| 137 |
-
except RuntimeError: pass
|
| 138 |
-
else:
|
| 139 |
-
return False
|
| 140 |
-
success = self.lock.acquire(blocking=blocking)
|
| 141 |
-
if success:
|
| 142 |
-
self.locked_at = time.time()
|
| 143 |
-
return success
|
| 144 |
-
|
| 145 |
-
def release(self):
|
| 146 |
try:
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# ==========================================
|
| 164 |
-
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 165 |
-
if n_constructs == 1: return np.array([[1.0]])
|
| 166 |
-
base_corr = np.random.uniform(0.2, max_corr - 0.1)
|
| 167 |
-
A = np.random.uniform(base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs))
|
| 168 |
-
A = (A + A.T) / 2
|
| 169 |
-
np.fill_diagonal(A, 1.0)
|
| 170 |
-
min_eig = np.min(np.linalg.eigvals(A))
|
| 171 |
-
if min_eig < 0: A -= (min_eig - 0.01) * np.eye(n_constructs)
|
| 172 |
-
d = np.sqrt(np.diag(A))
|
| 173 |
-
return A / np.outer(d, d)
|
| 174 |
-
|
| 175 |
-
def calculate_validity_metrics(df, constructs_info, true_loadings):
|
| 176 |
-
metrics = []
|
| 177 |
-
for const in constructs_info:
|
| 178 |
-
c_name = const['name']
|
| 179 |
-
items = const['items']
|
| 180 |
-
sub_df = df[items]
|
| 181 |
-
var_total = sub_df.sum(axis=1).var(ddof=1)
|
| 182 |
-
sum_var = sub_df.var(ddof=1).sum()
|
| 183 |
-
n_items = len(items)
|
| 184 |
-
alpha = 0.0 if var_total <= 0 else (n_items / (n_items - 1)) * (1 - sum_var / var_total)
|
| 185 |
-
c_loadings = np.array(true_loadings[c_name])
|
| 186 |
-
sum_loadings_sq = np.sum(c_loadings)**2
|
| 187 |
-
sum_sq_loadings = np.sum(c_loadings**2)
|
| 188 |
-
sum_error = np.sum(1 - c_loadings**2)
|
| 189 |
-
cr = sum_loadings_sq / (sum_loadings_sq + sum_error)
|
| 190 |
-
ave = sum_sq_loadings / len(c_loadings)
|
| 191 |
-
metrics.append({"Construct": c_name, "Items": n_items, "Cronbach's α": round(alpha, 3), "CR": round(cr, 3), "AVE": round(ave, 3)})
|
| 192 |
-
return pd.DataFrame(metrics)
|
| 193 |
-
|
| 194 |
-
def generate_empirical_data_robust(construct_names=None, n=300, scale_points=7):
|
| 195 |
-
if not construct_names or len(construct_names) < 2:
|
| 196 |
-
construct_names = ["Independent_Var", "Mediator_Var", "Dependent_Var"]
|
| 197 |
-
n_constructs = len(construct_names)
|
| 198 |
-
corr = generate_psd_corr_matrix(n_constructs, max_corr=0.55)
|
| 199 |
-
latent_scores = np.random.multivariate_normal(mean=[0]*n_constructs, cov=corr, size=n)
|
| 200 |
-
data, true_loadings, constructs_info = {}, {}, []
|
| 201 |
-
target_mean = scale_points / 2.0 + 0.5
|
| 202 |
-
target_std = scale_points / 5.0
|
| 203 |
-
for idx, c_name in enumerate(construct_names):
|
| 204 |
-
true_score = latent_scores[:, idx]
|
| 205 |
-
n_items = np.random.randint(3, 6)
|
| 206 |
-
loadings = np.random.uniform(0.72, 0.88, n_items)
|
| 207 |
-
true_loadings[c_name] = loadings
|
| 208 |
-
item_names = []
|
| 209 |
-
for i, load in enumerate(loadings):
|
| 210 |
-
error = np.random.normal(0, np.sqrt(1 - load**2), n)
|
| 211 |
-
item_score = load * true_score + error
|
| 212 |
-
raw_scaled = item_score * target_std + target_mean
|
| 213 |
-
item_int = np.clip(np.round(raw_scaled), 1, scale_points).astype(int)
|
| 214 |
-
col_name = f"{c_name}_{i+1}"
|
| 215 |
-
data[col_name] = item_int
|
| 216 |
-
item_names.append(col_name)
|
| 217 |
-
constructs_info.append({"name": c_name, "items": item_names})
|
| 218 |
-
df = pd.DataFrame(data)
|
| 219 |
-
validity_df = calculate_validity_metrics(df, constructs_info, true_loadings)
|
| 220 |
-
mean_scores = pd.DataFrame({c['name']: df[c['items']].mean(axis=1) for c in constructs_info})
|
| 221 |
-
fl_matrix = mean_scores.corr().astype(object)
|
| 222 |
-
for i, row in validity_df.iterrows():
|
| 223 |
-
c_name = row['Construct']
|
| 224 |
-
sqrt_ave = np.sqrt(row['AVE'])
|
| 225 |
-
fl_matrix.loc[c_name, c_name] = f"({sqrt_ave:.3f})"
|
| 226 |
-
for i in range(len(fl_matrix.columns)):
|
| 227 |
-
for j in range(i + 1, len(fl_matrix.columns)):
|
| 228 |
-
fl_matrix.iloc[i, j] = ""
|
| 229 |
-
desc_stats = mean_scores.mean().to_frame('Mean').join(mean_scores.std().to_frame('SD'))
|
| 230 |
-
return df, validity_df, desc_stats.join(fl_matrix)
|
| 231 |
-
|
| 232 |
-
def resolve_empirical_data(extracted_vars=None):
|
| 233 |
-
df, validity_df, fl_matrix_df = generate_empirical_data_robust(extracted_vars)
|
| 234 |
-
simulated_md_prompt = f"""
|
| 235 |
-
### Table 1: Reliability and Convergent Validity
|
| 236 |
-
{validity_df.to_markdown(index=False)}
|
| 237 |
-
|
| 238 |
-
### Table 2: Descriptive Statistics and Discriminant Validity (Fornell-Larcker Criterion)
|
| 239 |
-
*Note: Diagonal elements in parentheses are the square roots of AVE.*
|
| 240 |
-
{fl_matrix_df.to_markdown()}
|
| 241 |
-
|
| 242 |
-
[STRICT EMPIRICAL INSTRUCTION]
|
| 243 |
-
1. ZERO HALLUCINATION: You MUST report the exact metrics (Cronbach's α, CR, AVE, correlations) provided in the tables above.
|
| 244 |
-
2. VALIDITY DEFENSE: Explicitly state that Convergent Validity is established because all AVEs > 0.5 and CRs > 0.7.
|
| 245 |
-
3. DISCRIMINANT DEFENSE: Explicitly state that Discriminant Validity is satisfied per the Fornell-Larcker criterion, as the square root of AVE (diagonal values) exceeds inter-construct correlations.
|
| 246 |
-
"""
|
| 247 |
-
status_msg = "✅ 已成功启用稳健信效度生成引擎,AVE与Fornell-Larcker准则均验证达标。"
|
| 248 |
-
return df, simulated_md_prompt, status_msg
|
| 249 |
-
|
| 250 |
-
# ==========================================
|
| 251 |
-
# 2. UI 界面布局与初始化
|
| 252 |
-
# ==========================================
|
| 253 |
-
if "is_running" not in st.session_state: st.session_state.is_running = False
|
| 254 |
-
if "start_pipeline" not in st.session_state: st.session_state.start_pipeline = False
|
| 255 |
-
if "resume_pipeline" not in st.session_state: st.session_state.resume_pipeline = False
|
| 256 |
-
if "zip_buffer" not in st.session_state: st.session_state.zip_buffer = None
|
| 257 |
-
if "run_mode" not in st.session_state: st.session_state.run_mode = "wizard"
|
| 258 |
-
|
| 259 |
-
lang_choice = st.radio("Language", list(APP_CONFIG["ui_labels"].keys()), horizontal=True, label_visibility="collapsed")
|
| 260 |
-
ui, target_lang = APP_CONFIG["ui_labels"][lang_choice], APP_CONFIG["target_lang_map"][lang_choice]
|
| 261 |
-
st.markdown(f"<div class='main-title'><h2>{ui['title']}</h2></div>", unsafe_allow_html=True)
|
| 262 |
-
|
| 263 |
-
if os.path.exists(CHECKPOINT_FILE) and not (st.session_state.is_running or st.session_state.resume_pipeline or st.session_state.start_pipeline):
|
| 264 |
-
st.warning("⚠️ 系统检测到上次因网络或意外中断的未完成论文任务。")
|
| 265 |
-
colA, colB = st.columns([1, 1])
|
| 266 |
-
if colA.button("🔄 恢复断点续传 (Resume Progress)", key="resume_task"):
|
| 267 |
-
st.session_state.resume_pipeline = True
|
| 268 |
-
st.session_state.start_pipeline = False
|
| 269 |
-
st.rerun()
|
| 270 |
-
if colB.button("🗑️ 清除临时数据 (Clear Garbage)", key="clear_task"):
|
| 271 |
-
os.remove(CHECKPOINT_FILE)
|
| 272 |
-
st.rerun()
|
| 273 |
-
st.markdown("---")
|
| 274 |
-
|
| 275 |
-
topic = st.text_input(ui["topic_label"], value="虚拟旅游体验对实地旅游意愿的影响研究", disabled=st.session_state.is_running)
|
| 276 |
-
keywords = st.text_input(ui["keywords_label"], value="临场感;国家公园;全景漫游体验;虚拟旅游体验;消费者行为", disabled=st.session_state.is_running)
|
| 277 |
-
|
| 278 |
-
# 🚨 质量护栏:限定最高 25000 汉字,严防系统崩溃与 LLM 注水
|
| 279 |
-
words = st.number_input(ui["words_label"], min_value=12000, max_value=25000, value=20000, step=1000, disabled=st.session_state.is_running)
|
| 280 |
-
|
| 281 |
-
tab_wizard, tab_clone = st.tabs(["✨ 智能向导模式 (Smart Wizard)", "🧬 靶向克隆模式 (Clone Mode)"])
|
| 282 |
-
|
| 283 |
-
with tab_wizard:
|
| 284 |
-
st.markdown("### 🛠️ 人在环路:研究材料配置")
|
| 285 |
-
prompt_style_ui = st.radio("1. 请选择期望的写作规范与提示词引擎:",
|
| 286 |
-
options=["实证研究 (AMJ Style)", "自适应 (Adaptive Style)"],
|
| 287 |
-
index=0, disabled=st.session_state.is_running)
|
| 288 |
-
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)
|
| 289 |
-
uploaded_data_wiz = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], disabled=st.session_state.is_running)
|
| 290 |
-
|
| 291 |
-
if st.button("🚀 启动智能向导生成", disabled=st.session_state.is_running, key="btn_wiz"):
|
| 292 |
-
if not global_lock.acquire(blocking=False):
|
| 293 |
-
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。为了保证系统稳定,请大约 5-10 分钟后再试。")
|
| 294 |
-
else:
|
| 295 |
-
global_lock.release()
|
| 296 |
-
st.session_state.run_mode = "wizard"
|
| 297 |
-
st.session_state.start_pipeline = True
|
| 298 |
-
st.rerun()
|
| 299 |
-
|
| 300 |
-
with tab_clone:
|
| 301 |
-
st.markdown("### 🧬 高级克隆:骨架与风格复刻")
|
| 302 |
-
context_differences = st.text_area(
|
| 303 |
-
"1. 研究背景与核心差异(Context & Differences)【必填,建议 1-2000 字】",
|
| 304 |
-
placeholder="简述您的新研究与参考论文在数据、案例或背景上的核心区别...",
|
| 305 |
-
max_chars=2000,
|
| 306 |
-
disabled=st.session_state.is_running
|
| 307 |
-
)
|
| 308 |
-
|
| 309 |
-
if "extracted_sections" not in st.session_state:
|
| 310 |
-
st.session_state.extracted_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]
|
| 311 |
-
if "last_uploaded_clone_ref" not in st.session_state:
|
| 312 |
-
st.session_state.last_uploaded_clone_ref = None
|
| 313 |
-
|
| 314 |
-
uploaded_reference_clone = st.file_uploader("2. 上传骨架参考论文 (必填,单篇 PDF/DOCX,系统自动解构目录)", type=["pdf", "doc", "docx"], key="clone_ref", disabled=st.session_state.is_running)
|
| 315 |
-
|
| 316 |
-
if uploaded_reference_clone and global_ds_key:
|
| 317 |
-
if st.session_state.last_uploaded_clone_ref != uploaded_reference_clone.name:
|
| 318 |
-
with st.spinner("🔍 正在智能提取该范例论文的真实目录结构,请稍候..."):
|
| 319 |
-
temp_agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 320 |
-
ref_text_raw = extract_text_from_files([uploaded_reference_clone])
|
| 321 |
-
dynamic_sections = temp_agent.extract_document_structure(ref_text_raw)
|
| 322 |
-
|
| 323 |
-
st.session_state.extracted_sections = dynamic_sections
|
| 324 |
-
st.session_state.last_uploaded_clone_ref = uploaded_reference_clone.name
|
| 325 |
-
st.success(f"✅ 目录提取成功,将自动全量克隆以下结构:{', '.join(dynamic_sections)}")
|
| 326 |
-
|
| 327 |
-
uploaded_data_clone = st.file_uploader("3. 上传统计分析结果 (可选,支持 CSV/Excel,用于防幻觉)", type=["csv", "xlsx", "xls"], key="clone_data", disabled=st.session_state.is_running)
|
| 328 |
-
|
| 329 |
-
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)
|
| 330 |
-
|
| 331 |
-
if st.button("🚀 启动克隆级生成", disabled=st.session_state.is_running, key="btn_clone"):
|
| 332 |
-
if not context_differences.strip():
|
| 333 |
-
st.error("🚨 启动克隆模式必须填写研究背景与核心差异!")
|
| 334 |
-
elif not uploaded_reference_clone:
|
| 335 |
-
st.error("🚨 启动克隆模式必须上传范例论文!")
|
| 336 |
-
elif not global_lock.acquire(blocking=False):
|
| 337 |
-
st.error("⚠️ 系统正忙:当前有其他研究员正在独占系统生成论文。请大约 5-10 分钟后再试。")
|
| 338 |
-
else:
|
| 339 |
-
global_lock.release()
|
| 340 |
-
st.session_state.run_mode = "clone"
|
| 341 |
-
st.session_state.start_pipeline = True
|
| 342 |
-
st.rerun()
|
| 343 |
-
|
| 344 |
-
progress_bar = st.empty()
|
| 345 |
-
monitor_ui = st.empty()
|
| 346 |
-
|
| 347 |
-
def render_monitor(agent, phase, current_sec="", details=""):
|
| 348 |
-
monitor_ui.markdown(f"""
|
| 349 |
-
<div class='log-box'>
|
| 350 |
-
<div><b>🔄 流水线进度:</b> {phase}</div>
|
| 351 |
-
<div><b>📍 当前节点:</b> {current_sec}</div>
|
| 352 |
-
<div><b>📝 动作日志:</b> {details}</div>
|
| 353 |
-
<hr>
|
| 354 |
-
<div><b>📡 三维算力消耗监控:</b></div>
|
| 355 |
-
<div style='display: flex; gap: 8px;'>
|
| 356 |
-
<span style='background: #fef3c7; padding: 4px 8px; border-radius: 4px; color: black;'>🧠 DeepSeek: <b>{agent.ds_calls}</b></span>
|
| 357 |
-
<span style='background: #dbeafe; padding: 4px 8px; border-radius: 4px; color: black;'>📚 S2: <b>{agent.s2_calls}</b></span>
|
| 358 |
-
<span style='background: #d1fae5; padding: 4px 8px; border-radius: 4px; color: black;'>🌐 OpenAlex: <b>{agent.oa_calls}</b></span>
|
| 359 |
-
</div>
|
| 360 |
-
</div>
|
| 361 |
-
""", unsafe_allow_html=True)
|
| 362 |
-
|
| 363 |
-
FLAG_MAP = {"Simplified Chinese (简体中文)": "🇨🇳", "Russian (Русский)": "🇷🇺", "Kazakh (Қазақша)": "🇰🇿"}
|
| 364 |
-
|
| 365 |
-
# ==========================================
|
| 366 |
-
# 3. 后台流水线执行
|
| 367 |
-
# ==========================================
|
| 368 |
-
if st.session_state.start_pipeline or st.session_state.resume_pipeline:
|
| 369 |
-
if not global_ds_key:
|
| 370 |
-
st.error("❌ DEEPSEEK_API_KEY missing. 请配置API KEY。")
|
| 371 |
-
st.stop()
|
| 372 |
-
|
| 373 |
-
if not global_lock.acquire(blocking=False):
|
| 374 |
-
st.warning("⚠️ 糟糕!在您点击的一瞬间,系统刚好被抢占了。请稍后重试。")
|
| 375 |
-
st.session_state.start_pipeline = False
|
| 376 |
-
st.session_state.resume_pipeline = False
|
| 377 |
-
st.stop()
|
| 378 |
-
|
| 379 |
-
st.session_state.is_running = True
|
| 380 |
-
is_resume = st.session_state.resume_pipeline
|
| 381 |
-
agent = SSciPipelineAgent(global_ds_key, global_s2_key)
|
| 382 |
-
|
| 383 |
-
# 全局提取 SAFE_CHUNK_WORDS 确保断点续传时正常读取
|
| 384 |
-
SAFE_CHUNK_WORDS = agent.chunk_words_cyrillic if target_lang in ["Russian (Русский)", "Kazakh (Қазақша)"] else agent.chunk_words_default
|
| 385 |
-
|
| 386 |
-
try:
|
| 387 |
-
if is_resume:
|
| 388 |
-
pb = progress_bar.progress(50, text="🔄 正在从本地安全快照恢复状态...")
|
| 389 |
-
with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:
|
| 390 |
-
state = json.load(f)
|
| 391 |
-
|
| 392 |
-
topic = state["topic"]
|
| 393 |
-
keywords = state["keywords"]
|
| 394 |
-
target_lang = state["target_lang"]
|
| 395 |
-
words = state["words"]
|
| 396 |
-
user_data_md = state["user_data_md"]
|
| 397 |
-
user_lit_context = state["user_lit_context"]
|
| 398 |
-
|
| 399 |
-
agent.load_state(state["agent_state"])
|
| 400 |
-
adaptive_structure = state["adaptive_structure"]
|
| 401 |
-
completed_sections = state["completed_sections"]
|
| 402 |
-
full_draft_en = state["full_draft_en"]
|
| 403 |
-
full_draft_translated = state["full_draft_translated"]
|
| 404 |
-
synthesis_result = state["synthesis_result"]
|
| 405 |
-
refs_text = state["refs_text"]
|
| 406 |
-
clone_metadata = state["clone_metadata"]
|
| 407 |
-
context_tail = state["context_tail"]
|
| 408 |
-
st.session_state.run_mode = state.get("run_mode", "wizard")
|
| 409 |
-
APP_CONFIG.update(state.get("prompt_config", GENERIC_PROMPTS))
|
| 410 |
-
|
| 411 |
-
st.success(f"✅ 断点加载成功!将从节点 {len(completed_sections)}/{len(adaptive_structure)} 安全恢复。")
|
| 412 |
-
|
| 413 |
-
else:
|
| 414 |
-
pb = progress_bar.progress(1, text="⏳ 流水线启动...")
|
| 415 |
-
|
| 416 |
-
user_lit_context = ""
|
| 417 |
-
user_data_md = ""
|
| 418 |
-
|
| 419 |
-
if st.session_state.run_mode == "wizard":
|
| 420 |
-
if uploaded_papers_wiz:
|
| 421 |
-
if len(uploaded_papers_wiz) > 5:
|
| 422 |
-
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
| 423 |
-
uploaded_papers_wiz = uploaded_papers_wiz[:5]
|
| 424 |
-
user_lit_context = extract_text_from_files(uploaded_papers_wiz)
|
| 425 |
-
if uploaded_data_wiz: user_data_md = extract_data_from_files(uploaded_data_wiz)
|
| 426 |
-
|
| 427 |
-
elif st.session_state.run_mode == "clone":
|
| 428 |
-
if uploaded_reference_clone: reference_paper_text = extract_text_from_files([uploaded_reference_clone])
|
| 429 |
-
if uploaded_data_clone: user_data_md = extract_data_from_files(uploaded_data_clone)
|
| 430 |
-
if uploaded_core_papers_clone:
|
| 431 |
-
if len(uploaded_core_papers_clone) > 5:
|
| 432 |
-
st.warning("⚠️ 核心参考论文超过 5 篇,系统仅截取前 5 篇以保证内存稳定性。")
|
| 433 |
-
uploaded_core_papers_clone = uploaded_core_papers_clone[:5]
|
| 434 |
-
user_lit_context = extract_text_from_files(uploaded_core_papers_clone)
|
| 435 |
-
|
| 436 |
-
if not user_data_md:
|
| 437 |
-
with st.spinner("⚙️ 检测到未上传数据,正在通过蒙特卡洛引擎生成合格的底层防幻觉数据..."):
|
| 438 |
-
sim_df, sim_md_prompt, sim_msg = resolve_empirical_data()
|
| 439 |
-
user_data_md = sim_md_prompt
|
| 440 |
-
st.info(sim_msg)
|
| 441 |
-
|
| 442 |
-
state = {
|
| 443 |
-
"topic": topic, "keywords": keywords, "target_lang": target_lang, "words": words,
|
| 444 |
-
"user_data_md": user_data_md, "user_lit_context": user_lit_context,
|
| 445 |
-
"completed_sections": [], "full_draft_en": "", "full_draft_translated": "",
|
| 446 |
-
"context_tail": "", "clone_metadata": {}, "run_mode": st.session_state.run_mode
|
| 447 |
-
}
|
| 448 |
-
|
| 449 |
-
pb.progress(5, text="🕵️ 引擎配置与范式路由...")
|
| 450 |
-
|
| 451 |
-
if st.session_state.run_mode == "wizard":
|
| 452 |
-
if "AMJ" in prompt_style_ui:
|
| 453 |
-
APP_CONFIG.update(AMJ_PROMPTS)
|
| 454 |
-
st.success("🎯 用户显式指定:强制启用 AMJ 顶级期刊写作引擎。")
|
| 455 |
-
else:
|
| 456 |
-
APP_CONFIG.update(GENERIC_PROMPTS)
|
| 457 |
-
st.info("ℹ️ 用户显式指定:启用通用学术规范引擎。")
|
| 458 |
-
|
| 459 |
-
state["prompt_config"] = AMJ_PROMPTS if ("AMJ" in prompt_style_ui) else GENERIC_PROMPTS
|
| 460 |
-
|
| 461 |
-
clone_metadata = {}
|
| 462 |
-
if st.session_state.run_mode == "clone":
|
| 463 |
-
pb.progress(8, text="🧬 正在对参考论文进行逆向解构...")
|
| 464 |
-
for sec_tgt in st.session_state.extracted_sections:
|
| 465 |
-
clone_metadata[sec_tgt] = agent.reverse_engineer_section(reference_paper_text, sec_tgt)
|
| 466 |
-
st.success(f"🧬 逆向解构完成!已提取 {len(clone_metadata)} 个目标章节的骨架与风格。")
|
| 467 |
-
state["clone_metadata"] = clone_metadata
|
| 468 |
-
|
| 469 |
-
pb.progress(10, text="📚 智能文献检索 (已开启深度泛化策略)...")
|
| 470 |
-
def sync_monitor_ui():
|
| 471 |
-
render_monitor(agent, "文献检索", "S2 + OpenAlex", "深度检索中...实时同步算力消耗")
|
| 472 |
-
|
| 473 |
-
refs_text = agent.fetch_references_parallel(topic, keywords, min_required=50, progress_callback=sync_monitor_ui)
|
| 474 |
-
|
| 475 |
-
if len(agent.citation_map) < 50:
|
| 476 |
-
st.error(f"🚨 终止生成:系统已触发最大轮次的【主题自动泛化与补充策略】,最终仅整合到 {len(agent.citation_map)} 篇有效文献,未达到 50 篇最低要求。")
|
| 477 |
-
st.stop()
|
| 478 |
-
else:
|
| 479 |
-
st.success(f"✅ 外围文献检索与扩容成功!最终捕获 {len(agent.citation_map)} 篇高质量文献。")
|
| 480 |
-
|
| 481 |
-
if user_lit_context:
|
| 482 |
-
pb.progress(11, text="🧠 深度解析用户上传的核心文献...")
|
| 483 |
-
core_refs = agent.parse_user_core_literature(user_lit_context)
|
| 484 |
-
if core_refs:
|
| 485 |
-
refs_text = "【USER PROVIDED CORE LITERATURE (HIGHEST PRIORITY)】\n" + core_refs + "\n\n【RETRIEVED LITERATURE】\n" + refs_text
|
| 486 |
-
st.success("✅ 核心参考论文已成功结构化并注入最高优先级 RAG 记忆,且已自动映射 APA 引用!")
|
| 487 |
-
|
| 488 |
-
state["refs_text"] = refs_text
|
| 489 |
-
|
| 490 |
-
pb.progress(12, text="🧠 文献综合...")
|
| 491 |
-
synthesis_result = agent.synthesize_literature(topic, refs_text, user_core_literature=user_lit_context)
|
| 492 |
-
state["synthesis_result"] = synthesis_result
|
| 493 |
-
|
| 494 |
-
pb.progress(14, text="⚓ 生成锚点...")
|
| 495 |
-
abstract_anchor, conclusion_anchor = agent.generate_anchors(topic, keywords, synthesis_result, refs_text)
|
| 496 |
-
agent.global_memory["abstract_anchor"] = abstract_anchor
|
| 497 |
-
agent.global_memory["conclusion_anchor"] = conclusion_anchor
|
| 498 |
-
|
| 499 |
-
pb.progress(15, text="📝 大纲设计...")
|
| 500 |
-
plan = agent.generate_outline(topic, keywords, synthesis_result)
|
| 501 |
-
en_topic = str(plan.get("en_topic", topic))
|
| 502 |
-
en_keywords_raw = plan.get("en_keywords", keywords)
|
| 503 |
-
if isinstance(en_keywords_raw, list): en_keywords_raw = "; ".join([str(k) for k in en_keywords_raw])
|
| 504 |
-
else: en_keywords_raw = str(en_keywords_raw)
|
| 505 |
-
|
| 506 |
-
# 🏗️ 架构重构 1:大纲清洗。使用纯 O(1) 集合查表,拦截元数据版块,彻底解决重复生成
|
| 507 |
-
structure = plan.get("structure", [])
|
| 508 |
-
clean_structure = [
|
| 509 |
-
sec for sec in structure
|
| 510 |
-
if sec.get("section", "").strip().lower() not in META_SECTIONS_BLACKLIST
|
| 511 |
-
]
|
| 512 |
-
structure = clean_structure
|
| 513 |
-
|
| 514 |
-
# 🏗️ 架构重构 3:摘要降维。保护摘要不干扰主文档目录树
|
| 515 |
-
en_abstract_raw = re.sub(r'(?i)^abstract[:\s]*', '', str(abstract_anchor)).strip()
|
| 516 |
-
en_abstract_clean = clean_markdown_headings(en_abstract_raw)
|
| 517 |
-
|
| 518 |
-
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)
|
| 519 |
-
trans_abstract_clean = re.sub(r'(?i)^(摘要|abstract|аннотация|түйіндеме)[:\s]*', '', trans_abstract_raw).strip()
|
| 520 |
-
trans_abstract_clean = clean_markdown_headings(trans_abstract_clean)
|
| 521 |
-
|
| 522 |
-
loc_abs = {"Simplified Chinese (简体中文)": "摘要", "Russian (Русский)": "Аннотация", "Kazakh (Қазақша)": "Түйіндеме"}.get(target_lang, "Abstract")
|
| 523 |
-
loc_kw = {"Simplified Chinese (简体中文)": "关键词", "Russian (Русский)": "Ключевые слова", "Kazakh (Қазақша)": "Кілт сөздер"}.get(target_lang, "Keywords")
|
| 524 |
-
|
| 525 |
-
en_keywords_clean = re.sub(r'(?i)^keywords[:\s]*', '', en_keywords_raw).strip()
|
| 526 |
-
|
| 527 |
-
full_draft_en = f"# {en_topic}\n\n## Abstract\n{en_abstract_clean}\n\n## Keywords\n{en_keywords_clean}\n\n"
|
| 528 |
-
full_draft_translated = f"# {topic}\n\n## {loc_abs}\n{trans_abstract_clean}\n\n## {loc_kw}\n{keywords}\n\n"
|
| 529 |
-
|
| 530 |
-
adaptive_structure = []
|
| 531 |
-
for sec in structure:
|
| 532 |
-
sec_name = sec.get("section", "Section")
|
| 533 |
-
is_method_or_result = sec.get("is_method_or_result", False)
|
| 534 |
-
target_sec_words = int(words * sec.get("weight", 0.1))
|
| 535 |
-
if target_sec_words > SAFE_CHUNK_WORDS:
|
| 536 |
-
num_chunks = max(2, math.ceil(target_sec_words / SAFE_CHUNK_WORDS))
|
| 537 |
-
for i in range(num_chunks):
|
| 538 |
-
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})
|
| 539 |
-
else:
|
| 540 |
-
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})
|
| 541 |
-
|
| 542 |
-
state["adaptive_structure"] = adaptive_structure
|
| 543 |
-
state["agent_state"] = agent.export_state()
|
| 544 |
-
state["full_draft_en"] = full_draft_en
|
| 545 |
-
state["full_draft_translated"] = full_draft_translated
|
| 546 |
-
completed_sections = []
|
| 547 |
-
context_tail = ""
|
| 548 |
-
|
| 549 |
-
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 550 |
-
json.dump(state, f, ensure_ascii=False)
|
| 551 |
-
|
| 552 |
-
total_steps = len(adaptive_structure) * 2
|
| 553 |
-
current_step = len(completed_sections) * 2
|
| 554 |
-
st.markdown("---")
|
| 555 |
-
ui_blocks = []
|
| 556 |
-
target_flag = FLAG_MAP.get(target_lang, "🌐")
|
| 557 |
-
|
| 558 |
-
for sec in adaptive_structure:
|
| 559 |
-
display_name = sec["display_name"]
|
| 560 |
-
st.markdown(f"### ⚙️ {display_name}")
|
| 561 |
-
col_en, col_trans = st.columns(2)
|
| 562 |
-
with col_en:
|
| 563 |
-
st.markdown("#### 🇬🇧 英文初稿")
|
| 564 |
-
en_ph = st.empty()
|
| 565 |
-
with col_trans:
|
| 566 |
-
st.markdown(f"#### {target_flag} 翻译初稿")
|
| 567 |
-
trans_ph = st.empty()
|
| 568 |
-
|
| 569 |
-
if display_name in completed_sections:
|
| 570 |
-
en_ph.success("✅ 已从快照安全恢复并拼接")
|
| 571 |
-
trans_ph.success("✅ 已从快照安全恢复并拼接")
|
| 572 |
-
else:
|
| 573 |
-
en_ph.info("⏳ 等待执行...")
|
| 574 |
-
trans_ph.info("⏳ 等待...")
|
| 575 |
-
ui_blocks.append({"sec": sec, "en_ph": en_ph, "trans_ph": trans_ph})
|
| 576 |
-
|
| 577 |
-
generation_aborted = False
|
| 578 |
-
accumulated_deviation = 0
|
| 579 |
-
remaining_sections = len(adaptive_structure)
|
| 580 |
-
|
| 581 |
-
all_cite_keys = list(agent.citation_map.keys())
|
| 582 |
-
valid_chunks = [s for s in adaptive_structure if not any(kw in s["section"].lower() for kw in ["abstract", "keyword", "摘要", "关键字"])]
|
| 583 |
-
allocation_map = {}
|
| 584 |
-
current_cite_idx = 0
|
| 585 |
-
for idx, vc in enumerate(valid_chunks):
|
| 586 |
-
if idx == len(valid_chunks) - 1: allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx:]
|
| 587 |
-
else:
|
| 588 |
-
num_cites = max(1, math.ceil(len(all_cite_keys) / len(valid_chunks)))
|
| 589 |
-
allocation_map[vc["display_name"]] = all_cite_keys[current_cite_idx : current_cite_idx + num_cites]
|
| 590 |
-
current_cite_idx += num_cites
|
| 591 |
-
|
| 592 |
-
for i, block in enumerate(ui_blocks):
|
| 593 |
-
if generation_aborted: break
|
| 594 |
-
sec = block["sec"]; en_ph = block["en_ph"]; trans_ph = block["trans_ph"]
|
| 595 |
-
sec_title = sec["section"]; display_name = sec["display_name"]
|
| 596 |
-
|
| 597 |
-
if display_name in completed_sections:
|
| 598 |
-
remaining_sections -= 1
|
| 599 |
-
continue
|
| 600 |
-
|
| 601 |
-
remaining_sections -= 1
|
| 602 |
-
adjustment = -accumulated_deviation / remaining_sections if remaining_sections > 0 else 0
|
| 603 |
-
|
| 604 |
-
# 🏗️ 架构重构 5:消除硬编码绝对值,通过基础 Chunk 的 1.5 倍动态封顶,防止大模型雪崩
|
| 605 |
-
max_chunk_limit = int(SAFE_CHUNK_WORDS * 1.5)
|
| 606 |
-
adjusted_target = min(max_chunk_limit, max(50, int(sec['target_words'] + adjustment)))
|
| 607 |
-
|
| 608 |
-
quarantine_keywords = ["abstract", "keyword", "摘要", "关键字", "关键词", "conclusion", "结论", "заключение", "қорытынды", "references"]
|
| 609 |
-
is_quarantined = any(kw in sec_title.lower() for kw in quarantine_keywords)
|
| 610 |
-
|
| 611 |
-
if is_quarantined: quarantine_rule = "【CRITICAL】: NO IN-TEXT CITATIONS ALLOWED IN THIS SECTION."
|
| 612 |
-
else:
|
| 613 |
-
assigned_keys = allocation_map.get(display_name, [])
|
| 614 |
-
assigned_tags_str = ", ".join(assigned_keys) if assigned_keys else "any relevant citations"
|
| 615 |
-
quarantine_rule = f"""【CITATION GUIDANCE】: You are strongly encouraged to integrate citations: {assigned_tags_str}. <AVAILABLE_CITATIONS>{refs_text}</AVAILABLE_CITATIONS>"""
|
| 616 |
-
|
| 617 |
-
# 🏗️ 架构重构 1 (IoC控制反转):收回大模型的标题控制权,强制其只写内容
|
| 618 |
-
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."
|
| 619 |
-
|
| 620 |
-
memory_context = agent._build_memory_context(section_name=sec_title, max_tokens=2500)
|
| 621 |
-
memory_block = f"\n【GLOBAL PAPER MEMORY & TARGETED INJECTIONS】\n{memory_context}\n" if memory_context else ""
|
| 622 |
-
|
| 623 |
-
lower_bound = int(adjusted_target * 0.9)
|
| 624 |
-
upper_bound = int(adjusted_target * 1.1)
|
| 625 |
-
lang_hint = "ru" if "Русский" in target_lang else ("kk" if "Қазақша" in target_lang else "en")
|
| 626 |
-
num_paragraphs = agent._calc_paragraph_count(adjusted_target, lang_hint)
|
| 627 |
-
|
| 628 |
-
adaptive_heading_rule = ""
|
| 629 |
-
if adjusted_target > 800:
|
| 630 |
-
adaptive_heading_rule = f"The section is long. You MUST use Level 2 (##) and Level 3 (###) subheadings to logically structure your arguments."
|
| 631 |
-
elif adjusted_target > 400:
|
| 632 |
-
adaptive_heading_rule = f"Please use Level 2 (##) subheadings to organize your content clearly."
|
| 633 |
-
|
| 634 |
-
table_rule = ""
|
| 635 |
-
if sec["is_method_or_result"]:
|
| 636 |
-
table_rule = "[CRITICAL DATA FORMATTING] You MUST present ALL statistical data, descriptive statistics, validity metrics, and correlation matrices using STANDARD MARKDOWN TABLES. NEVER present dense statistical data in plain text paragraphs."
|
| 637 |
-
|
| 638 |
-
length_directive = f"""
|
| 639 |
-
[LENGTH MANDATE - STRICT] Write between {lower_bound} and {upper_bound} words (approx {num_paragraphs} paragraphs). No fluff.
|
| 640 |
-
{adaptive_heading_rule}
|
| 641 |
-
{table_rule}
|
| 642 |
-
[FINAL CHECK] Do not output a word count statement.
|
| 643 |
-
"""
|
| 644 |
-
|
| 645 |
-
is_clone_target = False
|
| 646 |
-
active_clone_key = None
|
| 647 |
-
if st.session_state.run_mode == "clone":
|
| 648 |
-
for target_key in clone_metadata.keys():
|
| 649 |
-
target_words = set(re.findall(r'[a-zA-Z]{3,}', target_key.lower()))
|
| 650 |
-
sec_words = set(re.findall(r'[a-zA-Z]{3,}', sec_title.lower()))
|
| 651 |
-
|
| 652 |
-
if "result" in target_words: target_words.add("analysis")
|
| 653 |
-
if "result" in sec_words: sec_words.add("analysis")
|
| 654 |
-
|
| 655 |
-
if target_words & sec_words:
|
| 656 |
-
is_clone_target = True
|
| 657 |
-
active_clone_key = target_key
|
| 658 |
break
|
| 659 |
-
|
| 660 |
-
if is_clone_target:
|
| 661 |
-
meta = clone_metadata[active_clone_key]
|
| 662 |
-
sys_prompt_m3 = "You are a top-tier academic ghostwriter executing a structural and stylistic clone."
|
| 663 |
-
|
| 664 |
-
base_user = f"""
|
| 665 |
-
[CLONE MODE ACTIVATED - TARGET: {sec_title}]
|
| 666 |
-
Mimic the academic tone, structural flow, and sentence patterns of this reference template:
|
| 667 |
-
<TONE_PROFILE>{meta.get("tone_and_style", "Objective")}</TONE_PROFILE>
|
| 668 |
-
<REFERENCE_TEMPLATE_SNIPPET>\n{meta.get("few_shot_snippet", "")}\n</REFERENCE_TEMPLATE_SNIPPET>
|
| 669 |
-
|
| 670 |
-
[NEW CONTEXT]
|
| 671 |
-
Write '{display_name}' for the topic: {topic}. Core differences to integrate: {context_differences}
|
| 672 |
-
{length_directive} {quarantine_rule} {heading_instruction}
|
| 673 |
-
{memory_block}
|
| 674 |
-
|
| 675 |
-
【CONTEXT SMOOTHING MANDATE】
|
| 676 |
-
Your previous section ended with: "...{context_tail}..."
|
| 677 |
-
Write a natural, smooth transitional opening sentence to bridge this.
|
| 678 |
-
"""
|
| 679 |
-
|
| 680 |
-
if "method" in sec_title.lower() or "result" in sec_title.lower() or "analysis" in sec_title.lower():
|
| 681 |
-
base_user += f"""\n[CRITICAL STOP - ZERO DATA HALLUCINATION RULE]
|
| 682 |
-
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>.
|
| 683 |
-
You MUST ONLY rely on the user's actual statistical data provided below.
|
| 684 |
-
If a required metric is missing from the user data, insert "[INSERT VALUE]" as a placeholder. DO NOT FABRICATE NUMBERS.
|
| 685 |
-
<USER_ACTUAL_DATA>\n{user_data_md}\n</USER_ACTUAL_DATA>"""
|
| 686 |
else:
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
{length_directive}\n{quarantine_rule}\n{heading_instruction}\n{theory_injection}\n{memory_block}
|
| 721 |
-
Global Research Synthesis: {synthesis_result}\n{wiz_data_injection}
|
| 722 |
-
Previous Context Tail: ...{context_tail}...\nIMPORTANT: Output directly the final academic text."""
|
| 723 |
-
|
| 724 |
-
total_tokens = agent._count_tokens(sys_prompt_m3) + agent._count_tokens(base_user)
|
| 725 |
-
if total_tokens > 60000:
|
| 726 |
-
base_user = agent._truncate_context(base_user, 60000 - agent._count_tokens(sys_prompt_m3))
|
| 727 |
-
|
| 728 |
-
engine_label = "🧬 克隆引擎" if is_clone_target else ("🎯 靶向注入" if golden_meta else "📚 标准引擎")
|
| 729 |
-
render_monitor(agent, f"English Drafting ({current_step+1}/{total_steps})", display_name, f"目标字数: {adjusted_target} ({engine_label})")
|
| 730 |
-
en_ph.info(f"🔄 正在生成高质量章节 (目标: {adjusted_target} 词 | {engine_label})...")
|
| 731 |
-
|
| 732 |
-
try:
|
| 733 |
-
en_draft_stream = en_ph.write_stream(agent.stream_deepseek(sys_prompt_m3, base_user, max_tokens=6000))
|
| 734 |
-
en_draft_clean = re.sub(r'<think>.*?</think>', '', en_draft_stream, flags=re.DOTALL).strip()
|
| 735 |
-
|
| 736 |
-
# 🏗️ 架构重构 1:剥离大模型偶然误生成的主标题,将结构控制权交还给 Python
|
| 737 |
-
en_draft_clean = re.sub(rf'(?im)^#\s*{re.escape(sec_title)}\s*\n+', '', en_draft_clean).strip()
|
| 738 |
-
|
| 739 |
-
# 统一由 Python 在第一部分拼接大标题
|
| 740 |
-
if sec["is_first"]:
|
| 741 |
-
en_draft_clean = f"# {sec_title}\n\n{en_draft_clean}"
|
| 742 |
-
|
| 743 |
-
en_resolved = agent.resolve_citations(en_draft_clean, quarantine=is_quarantined)
|
| 744 |
-
en_ph.markdown(en_resolved)
|
| 745 |
-
full_draft_en += en_resolved + "\n\n"
|
| 746 |
-
agent._extract_memory_from_text(en_draft_clean, sec_title)
|
| 747 |
-
words_tail = en_draft_clean.split()
|
| 748 |
-
context_tail = " ".join(words_tail[-200:]) if len(words_tail) > 200 else en_draft_clean
|
| 749 |
-
|
| 750 |
-
actual_words = len(en_draft_clean.split())
|
| 751 |
-
accumulated_deviation += (actual_words - adjusted_target)
|
| 752 |
-
st.caption(f"📊 本章节实际字数: {actual_words} (目标: {adjusted_target}), 累计偏差: {accumulated_deviation:+d}")
|
| 753 |
-
|
| 754 |
-
current_step += 1
|
| 755 |
-
pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"🇬🇧 {display_name} 英文完成...")
|
| 756 |
-
except Exception as e:
|
| 757 |
-
en_ph.error("🚨 节点网络异常或达到并发限制,生成已自动熔断。")
|
| 758 |
-
st.error(f"异常信息: {e} | 💥 系统已自动保存之前所有的生成快照,您随时可以刷新页面点击【恢复断点续传】继续任务。")
|
| 759 |
-
generation_aborted = True
|
| 760 |
-
break
|
| 761 |
-
|
| 762 |
-
render_monitor(agent, f"Translating ({current_step+1}/{total_steps})", display_name, "翻译中...")
|
| 763 |
-
trans_ph.empty()
|
| 764 |
-
try:
|
| 765 |
-
# 此时的 en_draft_clean 已经包含了 Python 安全注入的 `# 标题`,翻译节点会原封不动地将其平滑译出
|
| 766 |
-
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"))
|
| 767 |
-
trans_chunk_clean = re.sub(r'<think>.*?</think>', '', trans_chunk_raw, flags=re.DOTALL).strip()
|
| 768 |
-
trans_resolved = agent.resolve_citations(trans_chunk_clean, quarantine=is_quarantined)
|
| 769 |
-
trans_ph.markdown(trans_resolved)
|
| 770 |
-
full_draft_translated += trans_resolved + "\n\n"
|
| 771 |
-
current_step += 1
|
| 772 |
-
pb.progress(min(15 + int((current_step / total_steps) * 80), 99), text=f"{target_flag} {display_name} 翻译完成...")
|
| 773 |
-
except Exception as e:
|
| 774 |
-
trans_ph.error("🚨 节点网络异常,翻译已熔断。")
|
| 775 |
-
st.error(f"异常信息: {e} | 💥 系统已保存断点,可随时恢复任务。")
|
| 776 |
-
generation_aborted = True
|
| 777 |
-
break
|
| 778 |
-
|
| 779 |
-
state["completed_sections"].append(display_name)
|
| 780 |
-
state["full_draft_en"] = full_draft_en
|
| 781 |
-
state["full_draft_translated"] = full_draft_translated
|
| 782 |
-
state["context_tail"] = context_tail
|
| 783 |
-
state["agent_state"] = agent.export_state()
|
| 784 |
-
|
| 785 |
-
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as f:
|
| 786 |
-
json.dump(state, f, ensure_ascii=False)
|
| 787 |
-
|
| 788 |
-
if not generation_aborted and full_draft_en.strip():
|
| 789 |
-
pb.progress(96, text="📦 打包DOCX...")
|
| 790 |
-
|
| 791 |
-
# 🏗️ 架构重构 2:调用顶层纯函数,彻底消除回溯假死
|
| 792 |
-
full_draft_en = clean_trailing_references(full_draft_en, ["Reference", "References", "Reference List"])
|
| 793 |
-
full_draft_translated = clean_trailing_references(full_draft_translated, ["参考文献", "Reference", "References", "Reference List"])
|
| 794 |
-
|
| 795 |
-
total_words_en = len(full_draft_en.split())
|
| 796 |
-
target_words = int(words)
|
| 797 |
-
lower_limit = int(target_words * 0.95); upper_limit = int(target_words * 1.05)
|
| 798 |
-
st.info(f"📊 全文总字数: {total_words_en} (目标区间: {lower_limit} - {upper_limit})")
|
| 799 |
-
|
| 800 |
-
if total_words_en > upper_limit:
|
| 801 |
-
st.warning(f"⚠️ 全文超出上限 {total_words_en - upper_limit} 词,正在智能精简 Conclusion...")
|
| 802 |
-
conclusion_match = re.search(r'(#+\s*Conclusion.*?)(?=\n#+ |\Z)', full_draft_en, re.DOTALL | re.IGNORECASE)
|
| 803 |
-
if conclusion_match:
|
| 804 |
-
conclusion_text = conclusion_match.group(1)
|
| 805 |
-
compressed_en = agent.call_deepseek("You are an academic editor. Condense the following conclusion by 15-20% while preserving key findings and citations.", conclusion_text, max_tokens=1500)
|
| 806 |
-
if compressed_en:
|
| 807 |
-
full_draft_en = full_draft_en.replace(conclusion_text, compressed_en.strip())
|
| 808 |
-
compressed_trans = agent._translate_text(compressed_en, target_lang, max_tokens=2000)
|
| 809 |
-
if compressed_trans:
|
| 810 |
-
trans_conc_title = {"Simplified Chinese (简体中文)": "结论", "Russian (Русский)": "Заключение", "Kazakh (Қазақша)": "Қорытынды"}.get(target_lang, "Conclusion")
|
| 811 |
-
trans_match = re.search(rf'(#+\s*{trans_conc_title}.*?)(?=\n#+ |\Z)', full_draft_translated, re.DOTALL | re.IGNORECASE)
|
| 812 |
-
if trans_match: full_draft_translated = full_draft_translated.replace(trans_match.group(1), compressed_trans.strip())
|
| 813 |
-
else: full_draft_translated += "\n\n" + compressed_trans.strip()
|
| 814 |
-
total_words_en = len(full_draft_en.split())
|
| 815 |
-
st.success(f"✅ 精简完成,现总字数: {total_words_en}")
|
| 816 |
-
elif total_words_en < lower_limit:
|
| 817 |
-
st.warning(f"⚠️ 全文低于下限 {lower_limit - total_words_en} 词,正在扩展 Conclusion...")
|
| 818 |
-
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)
|
| 819 |
-
if expanded_en:
|
| 820 |
-
full_draft_en += "\n\n" + expanded_en.strip()
|
| 821 |
-
expanded_trans = agent._translate_text(expanded_en, target_lang, max_tokens=1000)
|
| 822 |
-
if expanded_trans: full_draft_translated += "\n\n" + expanded_trans.strip()
|
| 823 |
-
total_words_en = len(full_draft_en.split())
|
| 824 |
-
st.success(f"✅ 扩展完成,现总字数: {total_words_en}")
|
| 825 |
-
|
| 826 |
-
if len(agent.used_citations) < 50:
|
| 827 |
-
unused = [tag for tag in agent.citation_map if tag not in agent.used_citations]
|
| 828 |
-
for tag in unused[:50 - len(agent.used_citations)]: agent.used_citations.add(tag)
|
| 829 |
-
|
| 830 |
-
used_tags = sorted(list(agent.used_citations))
|
| 831 |
-
raw_refs = [agent.citation_map[tag]['ref'] for tag in used_tags if tag in agent.citation_map]
|
| 832 |
-
unique_refs = sorted(list(set(raw_refs)))
|
| 833 |
-
apa_refs = "\n\n".join([f"- {ref}" for ref in unique_refs])
|
| 834 |
-
full_draft_en += "\n\n# References\n" + apa_refs
|
| 835 |
-
full_draft_translated += "\n\n# 参考文献\n" + apa_refs
|
| 836 |
-
|
| 837 |
-
bj_time = datetime.now(timezone(timedelta(hours=8))).strftime("%Y%m%d_%H%M")
|
| 838 |
-
lang_prefix = {"Simplified Chinese (简体中文)": "ZH", "Russian (Русский)": "RU", "Kazakh (Қазақша)": "KK"}.get(target_lang, "ZH")
|
| 839 |
-
zip_buffer = io.BytesIO()
|
| 840 |
-
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 841 |
-
zf.writestr(f"Empirical_Research_EN_{bj_time}.docx", text_to_docx(full_draft_en).getvalue())
|
| 842 |
-
zf.writestr(f"Empirical_Research_Trans_{lang_prefix}_{bj_time}.docx", text_to_docx(full_draft_translated).getvalue())
|
| 843 |
-
zip_buffer.seek(0)
|
| 844 |
-
st.session_state.zip_buffer = zip_buffer.getvalue()
|
| 845 |
-
st.session_state.zip_filename = f"Article_Draft_{bj_time}.zip"
|
| 846 |
-
|
| 847 |
-
if os.path.exists(CHECKPOINT_FILE):
|
| 848 |
-
os.remove(CHECKPOINT_FILE)
|
| 849 |
-
|
| 850 |
-
pb.progress(100, text="✅ 完成")
|
| 851 |
-
render_monitor(agent, "完成", "✅", "文档已生成并已清空本地临时快照空间")
|
| 852 |
-
|
| 853 |
-
except Exception as e:
|
| 854 |
-
st.error(f"🚨 启动/恢复异常: {e}")
|
| 855 |
finally:
|
| 856 |
-
|
| 857 |
-
global_lock.release()
|
| 858 |
-
st.session_state.is_running = False
|
| 859 |
-
st.session_state.start_pipeline = False
|
| 860 |
-
st.session_state.resume_pipeline = False
|
| 861 |
-
|
| 862 |
-
if st.session_state.zip_buffer:
|
| 863 |
-
st.success(ui["success"])
|
| 864 |
-
st.download_button(label=ui["btn_download"], data=st.session_state.zip_buffer, file_name=st.session_state.zip_filename, mime="application/zip")
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
+
from docx import Document
|
| 4 |
+
from config import APP_CONFIG
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
import pandas as pd
|
| 8 |
+
PANDAS_AVAILABLE = True
|
| 9 |
+
except ImportError:
|
| 10 |
+
PANDAS_AVAILABLE = False
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import PyPDF2
|
| 14 |
+
PYPDF2_AVAILABLE = True
|
| 15 |
+
except ImportError:
|
| 16 |
+
PYPDF2_AVAILABLE = False
|
| 17 |
+
|
| 18 |
+
def extract_text_from_files(uploaded_files, max_chars=None):
|
| 19 |
+
"""提取上传文件的文本内容,自动截断以防止上下文溢出。"""
|
| 20 |
+
# 🚨 核心修复:从 config.py 动态读取全局最大字符截断数,消除硬编码
|
| 21 |
+
if max_chars is None:
|
| 22 |
+
max_chars = APP_CONFIG.get("max_extract_chars", 150000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
extracted_text = ""
|
| 25 |
+
for file in uploaded_files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
try:
|
| 27 |
+
file.seek(0) # [Robustness fix] Ensure file pointer is at the beginning
|
| 28 |
+
if file.name.lower().endswith('.pdf') and PYPDF2_AVAILABLE:
|
| 29 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
| 30 |
+
for page_num, page in enumerate(pdf_reader.pages):
|
| 31 |
+
text = page.extract_text()
|
| 32 |
+
if text:
|
| 33 |
+
extracted_text += text + "\n"
|
| 34 |
+
if len(extracted_text) > max_chars:
|
| 35 |
+
st.warning(f"⚠️ 文件 {file.name} 过长,已截断至约 {max_chars} 字符。")
|
| 36 |
+
break
|
| 37 |
+
elif file.name.lower().endswith(('.docx', '.doc')):
|
| 38 |
+
doc = Document(file)
|
| 39 |
+
for para in doc.paragraphs:
|
| 40 |
+
extracted_text += para.text + "\n"
|
| 41 |
+
if len(extracted_text) > max_chars:
|
| 42 |
+
st.warning(f"⚠️ 文件 {file.name} 过长,已截断至约 {max_chars} 字符。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
else:
|
| 45 |
+
content = file.getvalue().decode('utf-8', errors='ignore')
|
| 46 |
+
extracted_text += content + "\n"
|
| 47 |
+
if len(extracted_text) > max_chars:
|
| 48 |
+
st.warning(f"⚠️ 文件 {file.name} 过长,已截断至约 {max_chars} 字符。")
|
| 49 |
+
break
|
| 50 |
+
except Exception as e:
|
| 51 |
+
st.warning(f"⚠️ 解析文件 {file.name} 失败: {e}")
|
| 52 |
+
finally:
|
| 53 |
+
file.seek(0) # Leave the pointer clean for subsequent readings
|
| 54 |
+
return extracted_text[:max_chars]
|
| 55 |
+
|
| 56 |
+
def extract_data_from_files(uploaded_file, max_chars=20000):
|
| 57 |
+
"""提取 CSV/Excel 数据并转换为 Markdown 表格。"""
|
| 58 |
+
if not uploaded_file:
|
| 59 |
+
return ""
|
| 60 |
+
try:
|
| 61 |
+
uploaded_file.seek(0) # [Robustness fix] Reset cursor before parsing
|
| 62 |
+
if PANDAS_AVAILABLE:
|
| 63 |
+
if uploaded_file.name.lower().endswith('.csv'):
|
| 64 |
+
df = pd.read_csv(uploaded_file)
|
| 65 |
+
else:
|
| 66 |
+
df = pd.read_excel(uploaded_file)
|
| 67 |
+
# 限制表格行数,避免过长
|
| 68 |
+
if len(df) > 100:
|
| 69 |
+
st.warning(f"⚠️ 数据表 {uploaded_file.name} 超过100行,仅截取前100行。")
|
| 70 |
+
df = df.head(100)
|
| 71 |
+
return df.to_markdown(index=False)
|
| 72 |
+
else:
|
| 73 |
+
content = uploaded_file.getvalue().decode('utf-8', errors='ignore')
|
| 74 |
+
return content[:max_chars]
|
| 75 |
+
except Exception as e:
|
| 76 |
+
st.warning(f"⚠️ 解析数据表 {uploaded_file.name} 失败: {e}")
|
| 77 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
finally:
|
| 79 |
+
uploaded_file.seek(0) # Cleanup
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|