GuXiaopeng commited on
Commit
cf2ce06
·
verified ·
1 Parent(s): a8135f1

Update config.py

Browse files
Files changed (1) hide show
  1. config.py +468 -62
config.py CHANGED
@@ -1,66 +1,472 @@
1
  # -*- coding: utf-8 -*-
2
  import os
3
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
4
 
5
- @st.cache_data
6
- def load_config():
7
- base_config = {
8
- "lit_target_papers": int(os.environ.get("LIT_TARGET_PAPERS", "80")),
9
- "lit_per_page": int(os.environ.get("LIT_PER_PAGE", "100")),
10
- "lit_max_workers": int(os.environ.get("LIT_MAX_WORKERS", "1")),
11
- "lit_max_page_batches": int(os.environ.get("LIT_MAX_PAGE_BATCHES", "20")),
12
- "chunk_words_default": int(os.environ.get("CHUNK_WORDS_DEFAULT", "800")),
13
- "chunk_words_cyrillic": int(os.environ.get("CHUNK_WORDS_CYRILLIC", "600")),
14
- "deepseek_api_url": os.environ.get("DEEPSEEK_API_URL", "https://api.deepseek.com/chat/completions"),
15
- "openalex_api_url": os.environ.get("OPENALEX_API_URL", "https://api.openalex.org/works"),
16
- "s2_api_url": os.environ.get("S2_API_URL", "https://api.semanticscholar.org/graph/v1"),
17
- "ui_labels": {
18
- "中文": {"title": "📊 科研论文AI智能体", "btn_generate": "🚀 生成初稿", "btn_download": "📥 下载文件", "topic_label": "📝 论文名称", "keywords_label": "🔍 关键字", "words_label": "📏 目标总字数 (500-50000字)", "success": "🎉 流水线推演完毕!双语文档已就绪。"},
19
- "English": {"title": "📊 Article AI Agent", "btn_generate": "🚀 Generate Draft", "btn_download": "📥 Download", "topic_label": "📝 Article Title", "keywords_label": "🔍 Keywords", "words_label": "📏 Target Word Count", "success": "🎉 Task complete!"},
20
- "Русский": {"title": "📊 ИИ-агент", "btn_generate": "🚀 Черновик", "btn_download": "📥 Скачать", "topic_label": "📝 Тема", "keywords_label": "🔍 Ключевые слова", "words_label": "📏 Количество слов", "success": "🎉 Задача выполнена!"},
21
- "Қазақша": {"title": "📊 ИИ агенті", "btn_generate": "🚀 Қарапайым", "btn_download": "📥 Жүктеу", "topic_label": "📝 Тақырыбы", "keywords_label": "🔍 Кілт сөздер", "words_label": "📏 Сөз саны", "success": "🎉 Дайын!"}
22
- },
23
- "target_lang_map": {
24
- "中文": "Simplified Chinese (简体中文)",
25
- "English": "Simplified Chinese (简体中文)",
26
- "Русский": "Russian (Русский)",
27
- "Қазақша": "Kazakh (Қазақша)"
28
- },
29
- }
30
-
31
- generic_prompts = {
32
- "sys_academic_writer": "You are a distinguished professor writing for a premier SSCI journal. Maintain an authoritative yet measured tone. Avoid first-person pronouns. Every paragraph must advance a clear argument.",
33
- "deep_refinement_directive": "Produce a final, polished section ready for journal submission. Ensure logical flow and preserve all [CITE-XX] tags exactly.",
34
- "deep_synthesis_directive": "Synthesize the provided literature to demonstrate original theoretical insight. Identify tensions and propose conceptual integration.",
35
- "hypothesis_development_directive": "Elaborate the mechanism logic and state hypotheses explicitly.",
36
- "methodological_defense_directive": "Justify sampling, address biases, detail measurement validity, and defend analytical choices.",
37
- "discussion_depth_directive": "Detail theoretical implications, practical interventions, and boundaries.",
38
- "conclusion_anchor_directive": "Summarize the core contribution and outline future research trajectories.",
39
- "anchor_generation_directive": "Generate a STRUCTURED ABSTRACT (200 words) and CONCLUSION ANCHOR (150 words).",
40
- "empirical_data_logic": "Maintain strict adherence to APA 7th edition reporting standards.",
41
- }
42
-
43
- amj_prompts = {
44
- "sys_academic_writer": """You are a distinguished, highly cited scholar writing a manuscript for the Academy of Management Journal (AMJ). Your writing must exhibit unparalleled theoretical rigor, causal depth, and academic authority.
45
- [ABSOLUTE ANTI-AI-TONE MANDATES]:
46
- 1. CRITICAL: NEVER use these cliché AI words: delve into, intricate, paramount, overarching, pivotal, foster, seamlessly, multifaceted, beacon.
47
- 2. CRITICAL: NEVER use robotic transition phrases (e.g., Firstly, Moreover, Furthermore, In conclusion, To summarize). Use conceptual bridges instead.
48
- 3. SYNTAX: Use varying sentence lengths. Prefer active voice where appropriate, but maintain objective distance.
49
- 4. FOCUS ON CAUSALITY: Do not merely state that X is related to Y. You MUST articulate the exact theoretical mechanism driving the relationship.
50
- """,
51
- "deep_refinement_directive": "Produce a final, polished section ready for top-tier submission. Ensure flawless logical flow without meta-commentary. Ground claims in [CITE-XX] tags.",
52
- "deep_synthesis_directive": "Structure this synthesis to expose a critical theoretical tension: Consensus vs Paradox, Competing Perspectives, Theoretical Blind Spot, and Resolution Strategy.",
53
- "hypothesis_development_directive": "Construct a rigorous causal chain: 1. Base Theory. 2. Mechanism (Mediator logic). 3. Boundary Condition (Moderator logic). 4. Hypothesis Phrasing (italicized).",
54
- "methodological_defense_directive": "Write with extreme defensive precision: Justify Contextual Relevance, Detail Endogeneity & Bias Mitigation, Measurement Validity, and Analytical Strategy.",
55
- "discussion_depth_directive": "Elevate findings back to grand theory. Explicitly state how the study extends, refines, or challenges named theories. Provide counter-intuitive implications.",
56
- "conclusion_anchor_directive": "1. Conceptual Pivot. 2. Mechanism Summary. 3. Call to Action for the next decade.",
57
- "anchor_generation_directive": "Generate a STRUCTURED ABSTRACT (approx. 200 words) mimicking an AMJ abstract, and a CONCLUSION ANCHOR (approx. 150 words). Output format:\n---ABSTRACT---\n...\n---CONCLUSION---\n...",
58
- "empirical_data_logic": "Maintain strict adherence to APA 7th edition reporting standards. Include plausible degrees of freedom, exact p-values, confidence intervals, and effect sizes.",
59
- }
60
-
61
- default_config = base_config.copy()
62
- default_config.update(generic_prompts)
63
- return default_config, amj_prompts, generic_prompts
64
-
65
- DEFAULT_CONFIG, AMJ_PROMPTS, GENERIC_PROMPTS = load_config()
66
- APP_CONFIG = DEFAULT_CONFIG.copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # -*- coding: utf-8 -*-
2
  import os
3
  import streamlit as st
4
+ import time
5
+ import re
6
+ import json
7
+ import requests
8
+ import concurrent.futures
9
+ import threading
10
+ import math
11
+ import random
12
+ import tiktoken
13
+ from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
14
 
15
+ try:
16
+ from langdetect import detect
17
+ LANGDETECT_AVAILABLE = True
18
+ except ImportError:
19
+ LANGDETECT_AVAILABLE = False
20
+
21
+ from config import APP_CONFIG
22
+
23
+ class SSciPipelineAgent:
24
+ def __init__(self, ds_key, s2_key=""):
25
+ self.ds_key = ds_key
26
+ try:
27
+ self.s2_key = st.secrets.get("S2_API_KEY", s2_key)
28
+ except:
29
+ self.s2_key = os.environ.get("S2_API_KEY", s2_key)
30
+ try:
31
+ self.openalex_key = st.secrets.get("OA_API_KEY", "")
32
+ except:
33
+ self.openalex_key = os.environ.get("OA_API_KEY", "")
34
+
35
+ self.ds_calls = 0
36
+ self.oa_calls = 0
37
+ self.s2_calls = 0
38
+ self.citation_map = {}
39
+ self.used_citations = set()
40
+ self.lock = threading.RLock()
41
+ self.lit_target_papers = APP_CONFIG["lit_target_papers"]
42
+ self.lit_per_page = APP_CONFIG["lit_per_page"]
43
+ self.lit_max_workers = APP_CONFIG["lit_max_workers"]
44
+ self.lit_max_page_batches = APP_CONFIG["lit_max_page_batches"]
45
+ self.chunk_words_default = APP_CONFIG["chunk_words_default"]
46
+ self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]
47
+ self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]
48
+ self.openalex_api_url = APP_CONFIG["openalex_api_url"]
49
+ self.s2_api_url = APP_CONFIG["s2_api_url"]
50
+ self.global_memory = {
51
+ "hypotheses": "", "variables": "", "model_summary": "",
52
+ "method_summary": "", "abstract_anchor": "", "conclusion_anchor": ""
53
+ }
54
+ try:
55
+ self.tokenizer = tiktoken.get_encoding("cl100k_base")
56
+ except:
57
+ self.tokenizer = tiktoken.get_encoding("gpt2")
58
+
59
+ def _calc_paragraph_count(self, target_words, lang_hint="en"):
60
+ words_per_para = 100 if lang_hint in ["ru", "kk"] else 130
61
+ return max(2, int(target_words / words_per_para))
62
+
63
+ def _translate_text(self, text, target_lang, max_tokens=2000):
64
+ if not text.strip(): return ""
65
+ sys_prompt = f"Translate the following text into {target_lang}. Preserve all formatting, line breaks, and [CITE-XX] tags exactly. Output ONLY the translation."
66
+ return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2)
67
+
68
+ def _is_empirical_business_research(self, topic, keywords):
69
+ combined_text = f"{topic} {keywords}".lower()
70
+
71
+ empirical_strong_keywords = ["实证", "问卷", "定量", "量表", "empirical", "sem", "pls", "回归", "中介", "调节", "假设检验"]
72
+ if any(kw in combined_text for kw in empirical_strong_keywords):
73
+ st.success("🎯 规则拦截:命中强显式实证关键字,强制启用 AMJ 顶级期刊写作风格引擎。")
74
+ return True
75
+
76
+ sys_prompt = "You are an expert academic classifier. Your task is to determine if a given research topic falls into the category of 'empirical business/management research'."
77
+ user_prompt = f"""
78
+ Research Topic: {topic}
79
+ Keywords: {keywords}
80
+ Based on the topic and keywords, answer ONLY with a JSON object: {{"is_empirical": true/false, "reason": "brief justification"}}.
81
+ """
82
+ try:
83
+ response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=100, temp=0.1)
84
+ json_match = re.search(r'\{.*\}', response, re.DOTALL)
85
+ if json_match:
86
+ result = json.loads(json_match.group(0))
87
+ is_empirical = result.get("is_empirical", False)
88
+ reason = result.get("reason", "")
89
+ if is_empirical:
90
+ st.success(f"🎯 LLM嗅探:识别为工商管理实证研究,启用 AMJ 写作引擎。理由:{reason}")
91
+ else:
92
+ st.info(f"ℹ️ LLM嗅探:未识别为实证研究,采用通用学术规范引擎。理由:{reason}")
93
+ return is_empirical
94
+ return False
95
+ except Exception:
96
+ return False
97
+
98
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10), retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError)))
99
+ def _requests_get_with_retry(self, url, headers=None, params=None, timeout=15):
100
+ resp = requests.get(url, headers=headers, params=params, timeout=timeout)
101
+ if resp.status_code == 429:
102
+ time.sleep(5)
103
+ resp.raise_for_status()
104
+ resp.raise_for_status()
105
+ return resp
106
+
107
+ def _is_english_dominant(self, text):
108
+ if not text: return False
109
+ if LANGDETECT_AVAILABLE:
110
+ try: return detect(text) == 'en'
111
+ except: pass
112
+ alpha_chars = sum(1 for c in str(text) if c.isalpha())
113
+ if alpha_chars == 0: return False
114
+ return (len(re.findall(r'[a-zA-Z]', str(text))) / alpha_chars) > 0.8
115
+
116
+ def _extract_memory_from_text(self, text, section_name):
117
+ lower_sec = section_name.lower()
118
+ if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):
119
+ hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)
120
+ if hypo_matches: self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])
121
+ if any(kw in lower_sec for kw in ["method", "measure", "variable"]):
122
+ var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)
123
+ if var_matches: self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])
124
+ if "model" in lower_sec or "figure" in lower_sec:
125
+ model_match = re.search(r'(Figure\s*\d+[^\.]+\.)', text, re.IGNORECASE)
126
+ if model_match: self.global_memory["model_summary"] = model_match.group(1)
127
+ if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):
128
+ method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)
129
+ if method_match: self.global_memory["method_summary"] = method_match.group(1)
130
+
131
+ def _count_tokens(self, text):
132
+ return len(self.tokenizer.encode(text))
133
+
134
+ def _truncate_context(self, text, max_tokens):
135
+ tokens = self.tokenizer.encode(text)
136
+ if len(tokens) <= max_tokens: return text
137
+ return self.tokenizer.decode(tokens[:max_tokens])
138
+
139
+ def _build_memory_context(self, max_tokens=2000):
140
+ memory_parts = []
141
+ if self.global_memory["abstract_anchor"]: memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")
142
+ if self.global_memory["conclusion_anchor"]: memory_parts.append(f"【PAPER ANCHOR - EXPECTED CONCLUSION】\n{self.global_memory['conclusion_anchor']}")
143
+ if self.global_memory["hypotheses"]: memory_parts.append(f"【ESTABLISHED HYPOTHESES】\n{self.global_memory['hypotheses']}")
144
+ if self.global_memory["variables"]: memory_parts.append(f"【CORE CONSTRUCT DEFINITIONS】\n{self.global_memory['variables']}")
145
+ if self.global_memory["model_summary"]: memory_parts.append(f"【RESEARCH MODEL】\n{self.global_memory['model_summary']}")
146
+ if self.global_memory["method_summary"]: memory_parts.append(f"【METHODOLOGICAL SUMMARY】\n{self.global_memory['method_summary']}")
147
+ full = "\n\n".join(memory_parts)
148
+ if self._count_tokens(full) > max_tokens: return self._truncate_context(full, max_tokens)
149
+ return full
150
+
151
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
152
+ def call_deepseek(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3):
153
+ with self.lock: self.ds_calls += 1
154
+ payload = {"model": "deepseek-reasoner", "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}], "max_tokens": max_tokens, "temperature": temp}
155
+ resp = requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, timeout=600)
156
+ if resp.status_code == 429:
157
+ time.sleep(5)
158
+ resp.raise_for_status()
159
+ resp.raise_for_status()
160
+ data = resp.json()
161
+ if "choices" in data:
162
+ return re.sub(r'<think>.*?</think>', '', data["choices"][0]["message"].get("content", ""), flags=re.DOTALL).strip()
163
+ return ""
164
+
165
+ def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000):
166
+ with self.lock: self.ds_calls += 1
167
+ payload = {"model": "deepseek-reasoner", "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}], "max_tokens": max_tokens, "temperature": 0.2, "stream": True}
168
+ with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=600) as response:
169
+ response.raise_for_status()
170
+ for line in response.iter_lines():
171
+ if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':
172
+ try:
173
+ delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})
174
+ if 'content' in delta and delta['content']: yield delta['content']
175
+ except: pass
176
+
177
+ # ================= 自适应目录提取核心 =================
178
+ def extract_document_structure(self, text):
179
+ default_sections = ["Introduction", "Literature Review", "Methodology", "Results", "Discussion"]
180
+ if not text or len(text.strip()) < 100:
181
+ return default_sections
182
+
183
+ sys_prompt = "You are an expert academic editor. Extract the main section headings from the provided academic paper text."
184
+ user_prompt = f"""
185
+ Analyze the following academic text and extract the top-level section headings (e.g., Introduction, Theoretical Background, Method, Data Analysis, Conclusion, etc.).
186
+ Return ONLY a valid JSON array of strings representing these exact headings in the order they appear.
187
+ Do not include subheadings.
188
+ If you cannot find clear headings, return the standard empirical sections: {json.dumps(default_sections)}.
189
+
190
+ Text snippet:
191
+ {text[:20000]}
192
+ """
193
+ for attempt in range(2):
194
+ response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=500, temp=0.1)
195
+ clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)
196
+ try:
197
+ headings = json.loads(clean)
198
+ if isinstance(headings, list) and len(headings) > 0:
199
+ return [str(h).strip() for h in headings]
200
+ except: pass
201
+ return default_sections
202
+
203
+ def reverse_engineer_section(self, reference_text, section_name):
204
+ sys_prompt = "You are an expert academic reverse-engineer. Analyze the provided text from a top-tier journal paper section."
205
+ user_prompt = f"""
206
+ Target Section Type: {section_name}
207
+
208
+ Analyze the following reference text and extract the structural and stylistic DNA:
209
+ <REFERENCE_TEXT>
210
+ {reference_text[:10000]}
211
+ </REFERENCE_TEXT>
212
+
213
+ Output ONLY a valid JSON object with the following schema:
214
+ {{
215
+ "tone_and_style": "Describe the writing style in 3-5 precise adjectives/phrases (e.g., highly objective, uses complex subordinate clauses, passive voice dominant).",
216
+ "reporting_structure": "Describe the sequence of information presented (e.g., 'Reports reliability first, then CFA fit indices, then structural paths').",
217
+ "few_shot_snippet": "Extract a highly representative, continuous 150-200 word snippet from the text that embodies its style perfectly."
218
+ }}
219
+ """
220
+ for attempt in range(3):
221
+ response = self.call_deepseek(sys_prompt, user_prompt, temp=0.2)
222
+ clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)
223
+ try:
224
+ result = json.loads(clean)
225
+ if "few_shot_snippet" in result: return result
226
+ except:
227
+ time.sleep(1)
228
+ return {"tone_and_style": "objective academic tone", "reporting_structure": "standard empirical reporting", "few_shot_snippet": ""}
229
+
230
+ def synthesize_literature(self, topic, refs_text, user_core_literature=""):
231
+ sys_prompt = "You are a top-tier academic researcher in Business Administration and Information Systems."
232
+ user_injection = f"\n\nCRITICAL MANDATE: Prioritize and integrate the following User-Provided Core Literature:\n<USER_CORE_LITERATURE>\n{user_core_literature}\n</USER_CORE_LITERATURE>\n" if user_core_literature else ""
233
+ user_prompt = f"""Topic: {topic}{user_injection}\nLiterature Metadata:\n<LIT_DATA>\n{refs_text}\n</LIT_DATA>\n\n{APP_CONFIG['deep_synthesis_directive']}"""
234
+ return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)
235
+
236
+ def generate_anchors(self, topic, keywords, synthesis_result, refs_text):
237
+ sys_prompt = "You are a senior scholar conceptualizing a high-impact empirical paper."
238
+ user_prompt = f"""Topic: {topic}\nKeywords: {keywords}\n\nLiterature Synthesis:\n{synthesis_result}\n\nRelevant Citation Context:\n{refs_text[:3000]}\n\n{APP_CONFIG['anchor_generation_directive']}"""
239
+ response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=1500, temp=0.3)
240
+ abstract_match = re.search(r'---ABSTRACT---\s*(.*?)\s*---CONCLUSION---', response, re.DOTALL | re.IGNORECASE)
241
+ conclusion_match = re.search(r'---CONCLUSION---\s*(.*?)$', response, re.DOTALL | re.IGNORECASE)
242
+ abstract = abstract_match.group(1).strip() if abstract_match else ""
243
+ conclusion = conclusion_match.group(1).strip() if conclusion_match else ""
244
+ return abstract, conclusion
245
+
246
+ def generate_outline(self, topic, keywords, synthesis_result):
247
+ sys_prompt = "You are a senior academic journal reviewer. Design a strict empirical research paper outline."
248
+ user_prompt = f"""Topic: {topic}\nKeywords: {keywords}\nLiterature Synthesis & Gaps:\n{synthesis_result}\n\nConstruct a detailed empirical outline. Your response must be a single valid JSON object: {{"en_topic": "...", "en_keywords": "...", "structure": [{{"section": "...", "weight": 0.15, "is_method_or_result": false}}]}}. Do not include any other text."""
249
+ for attempt in range(3):
250
+ response = self.call_deepseek(sys_prompt, user_prompt, temp=0.2)
251
+ clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)
252
+ try:
253
+ plan = json.loads(clean)
254
+ if "structure" in plan: return plan
255
+ except Exception as e:
256
+ time.sleep(2)
257
+ raise ValueError("Outline Generation Failed. Invalid JSON structure.")
258
+
259
+ def generate_search_queries(self, topic, keywords):
260
+ sys_prompt = "You are an expert academic librarian. Generate English search queries."
261
+ user_prompt = f"""Topic: {topic}\nKeywords: {keywords}\nGenerate exactly 3 concise English search queries (max 3-4 words each). Return ONLY a valid JSON array of strings."""
262
+ for attempt in range(3):
263
+ response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1 + attempt * 0.1)
264
+ clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)
265
+ try:
266
+ queries = json.loads(clean)
267
+ if isinstance(queries, list) and len(queries) > 0:
268
+ final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]
269
+ if final_queries: return final_queries[:3]
270
+ except:
271
+ fallback_queries = re.findall(r'"([a-zA-Z\s\-]+)"', response)
272
+ if fallback_queries:
273
+ final_queries = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())]
274
+ if final_queries: return final_queries[:3]
275
+ time.sleep(1)
276
+ st.warning("⚠️ LLM 检索词生成失败,启用动态正则特征提取...")
277
+ combined_text = f"{topic} {keywords}"
278
+ english_chunks = re.findall(r'[a-zA-Z0-9\s\-]{4,}', combined_text)
279
+ clean_chunks = [chunk.strip() for chunk in english_chunks if len(chunk.strip()) >= 4 and self._is_english_dominant(chunk.strip())]
280
+ return clean_chunks[:3] if clean_chunks else []
281
+
282
+ def _fetch_s2_page(self, search_term, offset=0, limit=50):
283
+ headers = {}
284
+ if self.s2_key and str(self.s2_key).strip(): headers["x-api-key"] = str(self.s2_key).strip()
285
+ params = {"query": search_term, "offset": offset, "limit": limit, "fields": "title,authors,year,venue,abstract,externalIds"}
286
+ for attempt in range(3):
287
+ try:
288
+ resp = requests.get(f"{self.s2_api_url}/paper/search", headers=headers, params=params, timeout=15)
289
+ if resp.status_code == 200: return resp.json().get("data", [])
290
+ elif resp.status_code == 429: time.sleep((2 ** attempt) + random.uniform(0, 1))
291
+ elif resp.status_code == 403: break
292
+ else: break
293
+ except: time.sleep(2)
294
+ return []
295
+
296
+ @retry(stop=stop_after_attempt(2), wait=wait_exponential(multiplier=1, min=1, max=3))
297
+ def _fetch_openalex_page(self, search_term, page, filter_str):
298
+ headers = {"User-Agent": "mailto:ssci_agent@example.com"}
299
+ if self.openalex_key: headers["Authorization"] = f"Bearer {self.openalex_key}"
300
+ params = {"search": search_term, "per-page": self.lit_per_page, "page": page, "filter": filter_str, "sort": "cited_by_count:desc"}
301
+ resp = self._requests_get_with_retry(self.openalex_api_url, headers=headers, params=params, timeout=15)
302
+ return resp.json().get("results", [])
303
+
304
+ def fetch_references_parallel(self, topic, keywords):
305
+ with self.lock: self.citation_map.clear()
306
+ llm_rag_context = []
307
+ seen_identifiers = set()
308
+
309
+ search_terms = self.generate_search_queries(topic, keywords)
310
+ if not search_terms: return ""
311
+
312
+ filters_to_try = [
313
+ "language:en,type:article,has_doi:true,is_paratext:false",
314
+ "language:en,type:article,is_paratext:false",
315
+ "type:article,is_paratext:false",
316
+ "language:en,is_paratext:false"
317
+ ]
318
+
319
+ for filter_str in filters_to_try:
320
+ if len(self.citation_map) >= self.lit_target_papers: break
321
+ for term in search_terms:
322
+ if len(self.citation_map) >= self.lit_target_papers: break
323
+ page_batch = 1
324
+ while len(self.citation_map) < self.lit_target_papers and page_batch <= self.lit_max_page_batches:
325
+ batch_pages = range((page_batch-1)*5 + 1, page_batch*5 + 1)
326
+ raw_results = []
327
+ with concurrent.futures.ThreadPoolExecutor(max_workers=self.lit_max_workers) as executor:
328
+ futures = [executor.submit(self._fetch_openalex_page, term, p, filter_str) for p in batch_pages]
329
+ for future in concurrent.futures.as_completed(futures):
330
+ try: raw_results.extend(future.result())
331
+ except: pass
332
+ for item in raw_results:
333
+ if len(self.citation_map) >= self.lit_target_papers: break
334
+ title = item.get("title")
335
+ if not title or not self._is_english_dominant(title): continue
336
+ year = item.get("publication_year", "n.d.")
337
+ identifier = (title.lower().strip(), str(year))
338
+ if identifier in seen_identifiers: continue
339
+ seen_identifiers.add(identifier)
340
+
341
+ venue = ((item.get("primary_location") or {}).get("source") or {}).get("display_name", "Journal")
342
+ doi_clean = (item.get("doi") or "").replace("https://doi.org/", "")
343
+ formatted_authors, last_names = [], []
344
+ for a in item.get("authorships", []):
345
+ name_raw = a.get("author", {}).get("display_name", "")
346
+ if name_raw and name_raw.strip():
347
+ parts = name_raw.strip().split()
348
+ if len(parts) > 1:
349
+ last_names.append(parts[-1])
350
+ formatted_authors.append(f"{parts[-1]}, {parts[0][0]}.")
351
+ else:
352
+ last_names.append(name_raw)
353
+ formatted_authors.append(name_raw)
354
+ if not formatted_authors: continue
355
+
356
+ year_str = str(year)
357
+ if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"
358
+ elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
359
+ else: in_text = f"({last_names[0]} et al., {year_str})"
360
+
361
+ if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
362
+ elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)
363
+ else: author_str = formatted_authors[0]
364
+
365
+ apa_full = f"{author_str} ({year_str}). {title}. {venue}."
366
+ if doi_clean: apa_full += f" https://doi.org/{doi_clean}"
367
+
368
+ with self.lock:
369
+ cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
370
+ self.citation_map[cite_tag] = {"in_text": in_text, "ref": apa_full}
371
+ self.oa_calls += 1
372
+
373
+ abstract_index = item.get("abstract_inverted_index")
374
+ raw_abstract = None
375
+ if abstract_index:
376
+ word_index = [(pos, word) for word, positions in abstract_index.items() for pos in positions]
377
+ word_index.sort()
378
+ raw_abstract = " ".join([word for pos, word in word_index])
379
+ abs_snippet = " ".join(str(raw_abstract).split()[:60]) + "..." if raw_abstract else "Empirical data available."
380
+ llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
381
+ page_batch += 1
382
+
383
+ if len(self.citation_map) < self.lit_target_papers:
384
+ for term in search_terms:
385
+ if len(self.citation_map) >= self.lit_target_papers: break
386
+ offset = 0
387
+ while len(self.citation_map) < self.lit_target_papers and offset < 500:
388
+ papers = self._fetch_s2_page(term, offset=offset, limit=50)
389
+ if not papers: break
390
+ for paper in papers:
391
+ if len(self.citation_map) >= self.lit_target_papers: break
392
+ title = paper.get("title")
393
+ year = paper.get("year")
394
+ if not title or not year: continue
395
+ identifier = (title.lower().strip(), str(year))
396
+ if identifier in seen_identifiers: continue
397
+ seen_identifiers.add(identifier)
398
+
399
+ authors = paper.get("authors", [])
400
+ last_names, formatted_authors = [], []
401
+ for a in authors:
402
+ name = a.get("name", "")
403
+ if name:
404
+ parts = name.split()
405
+ if len(parts) > 1:
406
+ last_names.append(parts[-1])
407
+ formatted_authors.append(f"{parts[-1]}, {parts[0][0]}.")
408
+ else:
409
+ last_names.append(name)
410
+ formatted_authors.append(name)
411
+ if not last_names: continue
412
+
413
+ year_str = str(year)
414
+ venue = paper.get("venue") or "Journal"
415
+ doi = paper.get("externalIds", {}).get("DOI", "")
416
+ abstract = paper.get("abstract", "")
417
+
418
+ if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"
419
+ elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
420
+ else: in_text = f"({last_names[0]} et al., {year_str})"
421
+
422
+ if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
423
+ elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)
424
+ else: author_str = formatted_authors[0]
425
+
426
+ apa_full = f"{author_str} ({year_str}). {title}. {venue}."
427
+ if doi: apa_full += f" https://doi.org/{doi}"
428
+
429
+ with self.lock:
430
+ cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
431
+ self.citation_map[cite_tag] = {"in_text": in_text, "ref": apa_full}
432
+ self.s2_calls += 1
433
+
434
+ abs_snippet = " ".join(abstract.split()[:60]) + "..." if abstract else "Empirical data available."
435
+ llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
436
+ offset += 50
437
+ time.sleep(0.5)
438
+
439
+ return "\n".join(llm_rag_context)
440
+
441
+ def resolve_citations(self, text, quarantine=False):
442
+ if quarantine:
443
+ text = re.sub(r'\s*\(?[A-Z][a-z]+ (?:& [A-Z][a-z]+ |et al\., )\d{4}\)?\s*', '', text)
444
+ text = re.sub(r'\[?CITE-\d+(?:,\s*CITE-\d+)*\]?', '', text, flags=re.IGNORECASE)
445
+ return text
446
+
447
+ def bracket_replacer(match):
448
+ inner = match.group(1)
449
+ if not re.search(r'CITE-\d+', inner, re.IGNORECASE): return match.group(0)
450
+ cites = re.findall(r'CITE-\d+', inner, flags=re.IGNORECASE)
451
+ resolved = []
452
+ for c in cites:
453
+ full_c = f"[{c.upper()}]"
454
+ with self.lock:
455
+ if full_c in self.citation_map:
456
+ self.used_citations.add(full_c)
457
+ resolved.append(self.citation_map[full_c]["in_text"].strip("()"))
458
+ else: resolved.append(c.upper())
459
+ return "(" + "; ".join(resolved) + ")"
460
+
461
+ text = re.sub(r'\[(.*?)\]', bracket_replacer, text)
462
+ text = re.sub(r'\((.*?)\)', bracket_replacer, text)
463
+
464
+ def loose_replacer(match):
465
+ full_c = f"[{match.group(0).upper()}]"
466
+ with self.lock:
467
+ if full_c in self.citation_map:
468
+ self.used_citations.add(full_c)
469
+ return self.citation_map[full_c]["in_text"]
470
+ return match.group(0)
471
+ text = re.sub(r'CITE-\d+', loose_replacer, text, flags=re.IGNORECASE)
472
+ return text