Spaces:
Sleeping
Sleeping
Upload 3 files
Browse filesFiles changed (3)
- core/pipeline_agent.py+296-126
- core/qualitative_engine.py+192-48
- core/quantitative_engine.pyAdded+193
76 unmodified lines777879808182838485868788899091929394959673 unmodified lines170171172173174175176118 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263277 unmodified lines3353363373383393403413423433443453468 unmodified lines3553563573583593603613623633644 unmodified lines36937037137237337437549 unmodified lines42542642742842943043110 unmodified lines4424434444454464474484494504514524534544554564574584594604614624634642 unmodified lines4674684694704714724734744754764774784794804814824834841 unmodified line4864874884894904914924934944954964974984995005015025035045055064 unmodified lines51151251351451551651731 unmodified lines54955055155255355455555655755813 unmodified lines5725735745755765775783 unmodified lines5825835845855865875882 unmodified lines5915925935945955965975985996006016026036046056066076086091 unmodified line6116126136146156166176186196206216226236246256266276286296306314 unmodified lines63663763863964064164236 unmodified lines6796806816826836846855 unmodified lines6916926936946956966979 unmodified lines7077087097107117127137147157162 unmodified lines71972072172272372472514 unmodified lines74074174274374474574611 unmodified lines7587597607617627637649 unmodified lines77477577677777877978048 unmodified lines8298308318328338348358368378388398408418428438448458468478488498508518528538545 unmodified lines8608618628638648658668678688698708718728738748758768778788798808814 unmodified lines88688788888989089189217 unmodified lines91091191291391491591632 unmodified lines949950951952953954955149 unmodified lines110511061107110811091110111176 unmodified linesself.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]self.deepseek_default_model = str(APP_CONFIG.get("deepseek_default_model", "deepseek-v4-flash")).strip()self.deepseek_fallback_model = str(APP_CONFIG.get("deepseek_fallback_model", "deepseek-v4-flash")).strip()self.deepseek_default_thinking = bool(APP_CONFIG.get("deepseek_default_thinking", True))self.deepseek_reasoning_effort = str(APP_CONFIG.get("deepseek_reasoning_effort", "high")).strip().lower()self.deepseek_max_retries = max(1, int(APP_CONFIG.get("deepseek_max_retries", 3)))self.deepseek_show_reasoning = bool(APP_CONFIG.get("deepseek_show_reasoning", False)73 unmodified linesif not text.strip():return ""sys_prompt = f"Translate the following text into {target_lang}. Preserve formatting and [CITE-XX] tags exactly. Output ONLY the translation."return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2, model_name="deepseek-chat")@retry(stop=stop_after_attempt(4), wait=wait_random_exponential(multiplier=1.5, max=15), retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError)))def _requests_get_with_retry(self, url, headers=None, params=None, timeout=None):118 unmodified linesreturn self._truncate_context(full, max_tokens)return fulldef _resolve_deepseek_model(self, model_name=None, thinking=None):# Legacy names are accepted only as internal aliases.requested = str(model_name or self.deepseek_default_model).strip().lower()legacy_aliases = {"deepseek-chat": ("deepseek-v4-flash", False),"deepseek-reasoner": ("deepseek-v4-flash", True),}if requested in legacy_aliases:public_model, alias_thinking = legacy_aliases[requested]if thinking is None:thinking = alias_thinkingreturn public_model, bool(thinking)allowed_models = {"deepseek-v4-flash", "deepseek-v4-pro"}if requested not in allowed_models:raise DeepSeekRequestError(f"Unsupported DeepSeek model: {requested!r}. ""Use 'deepseek-v4-flash' or 'deepseek-v4-pro'.")if thinking is None:thinking = self.deepseek_default_thinkingreturn requested, bool(thinking)def _build_deepseek_payload(self,7 unmodified linesstream,reasoning_effort,):effort = str(reasoning_effort or self.deepseek_reasoning_effort).strip().lower()if effort not in {"high", "max"}:effort = "high"payload = {"model": model_name,"messages": [8 unmodified lines}if thinking:payload["reasoning_effort"] = effortelse:payload["temperature"] = max(0.0, min(float(temp), 2.0))return payload4 unmodified lines"Authorization": f"Bearer {api_key}","Content-Type": "application/json","Accept": "application/json","User-Agent": "SmartPaper/DeepSeekV4",}@staticmethod49 unmodified linesif raw_line is None:return Noneif isinstance(raw_line, bytes):line = raw_line.decode("utf-8", errors="replace").strip()else:line = str(raw_line).strip()10 unmodified linesreturn json.loads(data)except json.JSONDecodeError:logging.warning("⚠️ Ignored malformed DeepSeek SSE chunk: %s",data[:160],)return Nonedef _attempt_plan(self, requested_model, requested_thinking):total = self.deepseek_max_retriesfor attempt in range(total):model = requested_modelthinking = requested_thinkingif attempt == total - 1:if model != self.deepseek_fallback_model:model = self.deepseek_fallback_modelif thinking:thinking = Falseyield attempt, model, thinkingdef call_deepseek(2 unmodified linesuser_prompt,max_tokens=8000,temp=0.3,model_name="deepseek-reasoner",thinking=None,reasoning_effort=None,):requested_model, requested_thinking = (self._resolve_deepseek_model(model_name, thinking))tokens_est = self._count_tokens(str(user_prompt))logging.info("🚀 [DeepSeek 静态请求] 模型=%s | Thinking=%s | ""MaxTokens=%s | 输入估算=%s tokens",requested_model,requested_thinking,max_tokens,1 unmodified line)last_error = Nonefor attempt, current_model, current_thinking in self._attempt_plan(requested_model, requested_thinking):with self.lock:self.ds_calls += 1if (current_model != requested_modelor current_thinking != requested_thinking):logging.warning("⚠️ 最后一次尝试降级:模型=%s | Thinking=%s",current_model,current_thinking,)payload = self._build_deepseek_payload(4 unmodified linesmax_tokens=max_tokens,temp=temp,stream=False,reasoning_effort=reasoning_effort,)start_time = time.time()31 unmodified linesf"finish_reason={finish_reason!r}")elapsed = time.time() - start_timelogging.info("✅ [静态请求返回] 耗时=%.2fs | 输出长度=%s 字符",elapsed,len(content),)return content13 unmodified lineslast_error = excis_last = attempt == self.deepseek_max_retries - 1logging.error("❌ DeepSeek 尝试 %s/%s 失败: %s",attempt + 1,self.deepseek_max_retries,exc,3 unmodified linestime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError(f"DeepSeek API failed after "f"{self.deepseek_max_retries} attempts: {last_error}")2 unmodified linessystem_prompt,user_prompt,max_tokens=8000,model_name="deepseek-reasoner",thinking=None,reasoning_effort=None,temp=0.3,):requested_model, requested_thinking = (self._resolve_deepseek_model(model_name, thinking))tokens_est = self._count_tokens(str(user_prompt))logging.info("🚀 [DeepSeek 流式请求] 模型=%s | Thinking=%s | ""MaxTokens=%s | 输入估算=%s tokens",requested_model,requested_thinking,max_tokens,1 unmodified line)last_error = Nonefor attempt, current_model, current_thinking in self._attempt_plan(requested_model, requested_thinking):with self.lock:self.ds_calls += 1if (current_model != requested_modelor current_thinking != requested_thinking):logging.warning("⚠️ 最后一次尝试降级:模型=%s | Thinking=%s",current_model,current_thinking,)payload = self._build_deepseek_payload(4 unmodified linesmax_tokens=max_tokens,temp=temp,stream=True,reasoning_effort=reasoning_effort,)emitted_content = False36 unmodified linesif not reasoning_open:reasoning_open = Truelogging.info("🧠 DeepSeek thinking started.")if self.deepseek_show_reasoning:yield "\n<think>\n"5 unmodified linesif reasoning_chunks % 25 == 0:logging.info("⏳ DeepSeek thinking heartbeat: ""%.1fs, %s chunks",time.time() - start_time,reasoning_chunks,9 unmodified linesemitted_content = Trueyield str(content)if (reasoning_openand self.deepseek_show_reasoning):yield "\n</think>\n"if not emitted_content:2 unmodified lines)logging.info("✅ [流式生成结束] 总耗时=%.1fs",time.time() - start_time,)return14 unmodified lines) as exc:last_error = exclogging.error("❌ DeepSeek 流式尝试 %s/%s 失败: %s",attempt + 1,self.deepseek_max_retries,exc,11 unmodified linestime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError(f"DeepSeek streaming failed after "f"{self.deepseek_max_retries} attempts: {last_error}")9 unmodified linesfor attempt in range(2):try:logging.info("📄 [本地解析] 正在榨取用户上传的核心文献...")response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1, model_name="deepseek-chat")papers = self._extract_json_from_text(response)if not papers:raise ValueError("Invalid JSON")48 unmodified lines"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)def generate_anchors(self, topic, keywords, synthesis_result, refs_text):sys_prompt = "You are a senior scholar conceptualizing a high-impact empirical paper."format_mandate = """\n\n[CRITICAL FORMAT MANDATE]You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings like ## before them:---ABSTRACT---(Write the comprehensive abstract here)---CONCLUSION---(Write the expected conclusion here)"""base_directive = APP_CONFIG.get('anchor_generation_directive', '')user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nLiterature Synthesis:\n{synthesis_result}\nCitation Context:\n{refs_text[:3000]}\n{base_directive}{format_mandate}"response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=8000, temp=0.3, model_name="deepseek-reasoner")abstract_match = re.search(r'-+\s*ABSTRACT\s*-+\s*(.*?)(?=\s*-+\s*CONCLUSION\s*-+|$)', response, re.DOTALL | re.IGNORECASE)conclusion_match = re.search(r'-+\s*CONCLUSION\s*-+\s*(.*?)$', response, re.DOTALL | re.IGNORECASE)final_abstract = abstract_match.group(1).strip() if abstract_match else response.strip()final_conclusion = conclusion_match.group(1).strip() if conclusion_match else ""return final_abstract, final_conclusion# ... 保留上面的 synthesize_literature 和 generate_anchors 函数不变 ...5 unmodified linesuser_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace("{topic}", topic).replace("{user_injection}", user_injection).replace("{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.stream_deepseek(sys_prompt, user_prompt, model_name="deepseek-chat")# [新增] 生成锚点的流式输出方法def stream_generate_anchors(self, topic, keywords, synthesis_result, refs_text):sys_prompt = "You are a senior scholar conceptualizing a high-impact empirical paper."format_mandate = """\n\n[CRITICAL FORMAT MANDATE]You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings like ## before them:---ABSTRACT---(Write the comprehensive abstract here)---CONCLUSION---(Write the expected conclusion here)"""base_directive = APP_CONFIG.get('anchor_generation_directive', '')user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nLiterature Synthesis:\n{synthesis_result}\nCitation Context:\n{refs_text[:3000]}\n{base_directive}{format_mandate}"return self.stream_deepseek(sys_prompt, user_prompt, max_tokens=8000, model_name="deepseek-reasoner")# =====================================================================# [核心架构升级] 双轨制大纲路由,取代自由生成的结构断层风险4 unmodified linessys_prompt = "You are a senior academic editor. Polish the provided section titles to be more professional but DO NOT change the structure."structure_str = " || ".join([s["section"] for s in sections])response = self.call_deepseek(sys_prompt, f"Topic: {topic}. Structure: {structure_str}. Output refined titles only, separated by ' || '.", model_name="deepseek-chat")refined_titles = [t.strip() for t in response.split("||")]17 unmodified linessec_title = sec.get("section", "")if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result", "finding", "setting"]):jit_prompt = f"Topic: '{topic}'. Keywords: '{keywords}'. Section: '{sec_title}'. Generate exactly 1 highly specific English search query (e.g., a specific statistical method, measurement scale, or analytical framework needed). Keep it UNDER 5 terms. NO complex boolean logic. Return ONLY the query string, no quotes."query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2, model_name="deepseek-chat").strip(' "\'')if query:queries_to_fetch.add(query)32 unmodified linesReturn ONLY a valid JSON array of strings."""user_prompt = f"Topic: {topic}\nKeywords: {keywords}"for attempt in range(3):queries = self._extract_json_from_text(self.call_deepseek(sys_prompt, user_prompt, temp=0.1 + attempt * 0.1, model_name="deepseek-reasoner"))if queries and isinstance(queries, list) and len(queries) > 0:final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]if final_queries:149 unmodified lines3. Output simple, space-separated keyword combinations under 5 terms.Return ONLY a JSON array of strings."""user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nUsed Queries: {list(all_used_terms)}\nGenerate 3 NEW, BROADER English search queries."response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5, model_name="deepseek-chat")queries = self._extract_json_from_text(response)if isinstance(queries, list):search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]76 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911073 unmodified lines184185186187188189190191192193194195196197198118 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763777 unmodified lines3853863873883893908 unmodified lines3994004014024034044054064074084094 unmodified lines41441541641741841942049 unmodified lines47047147247347447547647747847910 unmodified lines4904914924934944954964974984995005015025035045055065075085095105115125135145155165175182 unmodified lines5215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505511 unmodified line5535545555565575585595605615625635645655665675685695704 unmodified lines57557657757857958058131 unmodified lines61361461561661761861962062113 unmodified lines6356366376386396406413 unmodified lines6456466476486496506512 unmodified lines6546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846851 unmodified line6876886896906916926936946956966976986997007017027037044 unmodified lines70971071171271371471536 unmodified lines7527537547557567577585 unmodified lines7647657667677687697709 unmodified lines7807817827837847857862 unmodified lines78979079179279379479514 unmodified lines81081181281381481581611 unmodified lines8288298308318328338349 unmodified lines84484584684784884985085185285385485585685748 unmodified lines9069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789795 unmodified lines985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510464 unmodified lines105110521053105410551056105717 unmodified lines107510761077107810791080108132 unmodified lines111411151116111711181119112011211122112311241125149 unmodified lines127512761277127812791280128176 unmodified linesself.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]configured_models = APP_CONFIG.get("deepseek_models") or {}self.deepseek_models = {str(role).strip().lower(): str(model or "").strip()for role, model in configured_models.items()}required_roles = {"reasoning","writing","translation","fast","fallback",}missing_roles = [role for role in required_rolesif not self.deepseek_models.get(role)]if missing_roles:raise DeepSeekRequestError("Missing DeepSeek model role configuration: "+ ", ".join(sorted(missing_roles)))self.deepseek_task_settings = APP_CONFIG.get("deepseek_task_settings",{},)self.deepseek_max_retries = max(1,int(APP_CONFIG.get("deepseek_max_retries", 3)),)self.deepseek_show_reasoning = bool(APP_CONFIG.get("deepseek_show_reasoning", False)73 unmodified linesif not text.strip():return ""sys_prompt = f"Translate the following text into {target_lang}. Preserve formatting and [CITE-XX] tags exactly. Output ONLY the translation."return self.call_deepseek(sys_prompt,text,max_tokens=max_tokens,temp=0.2,model_role="translation",thinking=False,allow_fallback=False,)@retry(stop=stop_after_attempt(4), wait=wait_random_exponential(multiplier=1.5, max=15), retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError)))def _requests_get_with_retry(self, url, headers=None, params=None, timeout=None):118 unmodified linesreturn self._truncate_context(full, max_tokens)return fulldef model_for(self, model_role="reasoning"):role = str(model_role or "reasoning").strip().lower()model = self.deepseek_models.get(role)if not model:raise DeepSeekRequestError(f"Unknown or unconfigured DeepSeek model role: {role!r}.")return modeldef _task_settings(self, model_role):role = str(model_role or "reasoning").strip().lower()raw = self.deepseek_task_settings.get(role) or {}effort = str(raw.get("reasoning_effort", "high")).strip().lower()if effort not in {"low", "high", "max"}:effort = "high"return {"thinking": bool(raw.get("thinking", role == "reasoning")),"reasoning_effort": effort,"allow_fallback": bool(raw.get("allow_fallback", False)),}def _resolve_deepseek_request(self,model_name=None,model_role="reasoning",thinking=None,reasoning_effort=None,allow_fallback=None,):role = str(model_role or "reasoning").strip().lower()requested_name = str(model_name or "").strip()settings = self._task_settings(role)model = requested_name or self.model_for(role)if not model:raise DeepSeekRequestError(f"No DeepSeek model configured for role {role!r}.")if thinking is None:thinking = settings["thinking"]if reasoning_effort is None:reasoning_effort = settings["reasoning_effort"]effort = str(reasoning_effort).strip().lower()if effort not in {"low", "high", "max"}:effort = "high"if allow_fallback is None:allow_fallback = settings["allow_fallback"]return (model,bool(thinking),effort,bool(allow_fallback),role,)def _build_deepseek_payload(self,7 unmodified linesstream,reasoning_effort,):payload = {"model": model_name,"messages": [8 unmodified lines}if thinking:payload["reasoning_effort"] = reasoning_effortelse:payload["temperature"] = max(0.0,min(float(temp), 2.0),)return payload4 unmodified lines"Authorization": f"Bearer {api_key}","Content-Type": "application/json","Accept": "application/json","User-Agent": "SmartPaper/DeepSeek",}@staticmethod49 unmodified linesif raw_line is None:return Noneif isinstance(raw_line, bytes):line = raw_line.decode("utf-8",errors="replace",).strip()else:line = str(raw_line).strip()10 unmodified linesreturn json.loads(data)except json.JSONDecodeError:logging.warning("Ignored malformed DeepSeek SSE chunk: %s",data[:160],)return Nonedef _attempt_plan(self,requested_model,requested_thinking,allow_fallback,):total = self.deepseek_max_retriesfallback_model = self.deepseek_models.get("fallback", "")for attempt in range(total):model = requested_modelthinking = requested_thinkingif (allow_fallbackand attempt == total - 1and fallback_modeland fallback_model != requested_model):model = fallback_modelyield attempt, model, thinkingdef call_deepseek(2 unmodified linesuser_prompt,max_tokens=8000,temp=0.3,model_name=None,model_role="reasoning",thinking=None,reasoning_effort=None,allow_fallback=None,):(requested_model,requested_thinking,resolved_effort,resolved_fallback,resolved_role,) = self._resolve_deepseek_request(model_name=model_name,model_role=model_role,thinking=thinking,reasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)tokens_est = self._count_tokens(str(user_prompt))logging.info("DeepSeek static request | role=%s | model=%s | ""thinking=%s | max_tokens=%s | input_est=%s",resolved_role,requested_model,requested_thinking,max_tokens,1 unmodified line)last_error = Nonefor attempt, current_model, current_thinking in self._attempt_plan(requested_model,requested_thinking,resolved_fallback,):with self.lock:self.ds_calls += 1if current_model != requested_model:logging.warning("Non-critical final fallback: model=%s",current_model,)payload = self._build_deepseek_payload(4 unmodified linesmax_tokens=max_tokens,temp=temp,stream=False,reasoning_effort=resolved_effort,)start_time = time.time()31 unmodified linesf"finish_reason={finish_reason!r}")logging.info("DeepSeek static response | seconds=%.2f | chars=%s",time.time() - start_time,len(content),)return content13 unmodified lineslast_error = excis_last = attempt == self.deepseek_max_retries - 1logging.error("DeepSeek attempt %s/%s failed: %s",attempt + 1,self.deepseek_max_retries,exc,3 unmodified linestime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError("DeepSeek API failed after "f"{self.deepseek_max_retries} attempts: {last_error}")2 unmodified linessystem_prompt,user_prompt,max_tokens=8000,model_name=None,model_role="reasoning",thinking=None,reasoning_effort=None,temp=0.3,allow_fallback=None,):(requested_model,requested_thinking,resolved_effort,resolved_fallback,resolved_role,) = self._resolve_deepseek_request(model_name=model_name,model_role=model_role,thinking=thinking,reasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)tokens_est = self._count_tokens(str(user_prompt))logging.info("DeepSeek stream request | role=%s | model=%s | ""thinking=%s | max_tokens=%s | input_est=%s",resolved_role,requested_model,requested_thinking,max_tokens,1 unmodified line)last_error = Nonefor attempt, current_model, current_thinking in self._attempt_plan(requested_model,requested_thinking,resolved_fallback,):with self.lock:self.ds_calls += 1if current_model != requested_model:logging.warning("Non-critical final fallback: model=%s",current_model,)payload = self._build_deepseek_payload(4 unmodified linesmax_tokens=max_tokens,temp=temp,stream=True,reasoning_effort=resolved_effort,)emitted_content = False36 unmodified linesif not reasoning_open:reasoning_open = Truelogging.info("DeepSeek thinking started.")if self.deepseek_show_reasoning:yield "\n<think>\n"5 unmodified linesif reasoning_chunks % 25 == 0:logging.info("DeepSeek thinking heartbeat: ""%.1fs, %s chunks",time.time() - start_time,reasoning_chunks,9 unmodified linesemitted_content = Trueyield str(content)if reasoning_open and self.deepseek_show_reasoning:yield "\n</think>\n"if not emitted_content:2 unmodified lines)logging.info("DeepSeek stream complete | seconds=%.1f",time.time() - start_time,)return14 unmodified lines) as exc:last_error = exclogging.error("DeepSeek stream attempt %s/%s failed: %s",attempt + 1,self.deepseek_max_retries,exc,11 unmodified linestime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError("DeepSeek streaming failed after "f"{self.deepseek_max_retries} attempts: {last_error}")9 unmodified linesfor attempt in range(2):try:logging.info("📄 [本地解析] 正在榨取用户上传的核心文献...")response = self.call_deepseek(sys_prompt,user_prompt,temp=0.1,model_role="reasoning",thinking=True,allow_fallback=False,)papers = self._extract_json_from_text(response)if not papers:raise ValueError("Invalid JSON")48 unmodified lines"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)def generate_anchors(self,topic,keywords,synthesis_result,refs_text,data_evidence="",mode="amj",):sys_prompt = ("You are a senior scholar conceptualizing a high-impact ""empirical paper.")format_mandate = """\n\n[CRITICAL FORMAT MANDATE]You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings before them:---ABSTRACT---(Write the comprehensive abstract here)---CONCLUSION---(Write the expected conclusion here)"""evidence_block = (f"\nResearch Mode: {mode}\n""The following evidence packet is the single source of truth ""for setting, sample, data sources, method, findings, and all ""numerical details. Do not invent or alter them.\n"f"<RESEARCH_EVIDENCE>\n{data_evidence[:12000]}\n""</RESEARCH_EVIDENCE>\n"if data_evidenceelse "")base_directive = APP_CONFIG.get("anchor_generation_directive","",)user_prompt = (f"Topic: {topic}\nKeywords: {keywords}\n"f"Literature Synthesis:\n{synthesis_result}\n"f"Citation Context:\n{refs_text[:3000]}\n"f"{evidence_block}{base_directive}{format_mandate}")response = self.call_deepseek(sys_prompt,user_prompt,max_tokens=8000,temp=0.3,model_role="reasoning",thinking=True,allow_fallback=False,)abstract_match = re.search(r"-+\s*ABSTRACT\s*-+\s*(.*?)(?=\s*-+\s*CONCLUSION\s*-+|$)",response,re.DOTALL | re.IGNORECASE,)conclusion_match = re.search(r"-+\s*CONCLUSION\s*-+\s*(.*?)$",response,re.DOTALL | re.IGNORECASE,)final_abstract = (abstract_match.group(1).strip()if abstract_matchelse response.strip())final_conclusion = (conclusion_match.group(1).strip()if conclusion_matchelse "")return final_abstract, final_conclusion# ... 保留上面的 synthesize_literature 和 generate_anchors 函数不变 ...5 unmodified linesuser_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace("{topic}", topic).replace("{user_injection}", user_injection).replace("{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.stream_deepseek(sys_prompt,user_prompt,model_role="reasoning",thinking=True,allow_fallback=False,)# Generate abstract and conclusion anchors from literature plus evidence.def stream_generate_anchors(self,topic,keywords,synthesis_result,refs_text,data_evidence="",mode="amj",):sys_prompt = ("You are a senior scholar conceptualizing a high-impact ""empirical paper.")format_mandate = """\n\n[CRITICAL FORMAT MANDATE]You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings before them:---ABSTRACT---(Write the comprehensive abstract here)---CONCLUSION---(Write the expected conclusion here)"""evidence_block = (f"\nResearch Mode: {mode}\n""The following evidence packet is the single source of truth ""for setting, sample, data sources, method, findings, and all ""numerical details. Do not invent or alter them.\n"f"<RESEARCH_EVIDENCE>\n{data_evidence[:12000]}\n""</RESEARCH_EVIDENCE>\n"if data_evidenceelse "")base_directive = APP_CONFIG.get("anchor_generation_directive","",)user_prompt = (f"Topic: {topic}\nKeywords: {keywords}\n"f"Literature Synthesis:\n{synthesis_result}\n"f"Citation Context:\n{refs_text[:3000]}\n"f"{evidence_block}{base_directive}{format_mandate}")return self.stream_deepseek(sys_prompt,user_prompt,max_tokens=8000,model_role="reasoning",thinking=True,allow_fallback=False,)# =====================================================================# [核心架构升级] 双轨制大纲路由,取代自由生成的结构断层风险4 unmodified linessys_prompt = "You are a senior academic editor. Polish the provided section titles to be more professional but DO NOT change the structure."structure_str = " || ".join([s["section"] for s in sections])response = self.call_deepseek(sys_prompt, f"Topic: {topic}. Structure: {structure_str}. Output refined titles only, separated by ' || '.", model_role="fast")refined_titles = [t.strip() for t in response.split("||")]17 unmodified linessec_title = sec.get("section", "")if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result", "finding", "setting"]):jit_prompt = f"Topic: '{topic}'. Keywords: '{keywords}'. Section: '{sec_title}'. Generate exactly 1 highly specific English search query (e.g., a specific statistical method, measurement scale, or analytical framework needed). Keep it UNDER 5 terms. NO complex boolean logic. Return ONLY the query string, no quotes."query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2, model_role="fast").strip(' "\'')if query:queries_to_fetch.add(query)32 unmodified linesReturn ONLY a valid JSON array of strings."""user_prompt = f"Topic: {topic}\nKeywords: {keywords}"for attempt in range(3):queries = self._extract_json_from_text(self.call_deepseek(sys_prompt,user_prompt,temp=0.1 + attempt * 0.1,model_role="fast",))if queries and isinstance(queries, list) and len(queries) > 0:final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]if final_queries:149 unmodified lines3. Output simple, space-separated keyword combinations under 5 terms.Return ONLY a JSON array of strings."""user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nUsed Queries: {list(all_used_terms)}\nGenerate 3 NEW, BROADER English search queries."response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5, model_role="fast")queries = self._extract_json_from_text(response)if isinstance(queries, list):search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# -*- coding: utf-8 -*-import jsonimport loggingimport reimport streamlit as stclass QualitativeEngine:def __init__(self, agent):self.agent = agentdef resolve_qualitative_data(self, topic, keywords, raw_interviews=""):"""核心逻辑:解析真实访谈数据,或在无数据时模拟 ASQ 级别的定性数据结构表。引入流式状态机,防止 WebSocket 假死超时。"""if raw_interviews and len(raw_interviews) > 100:logging.info("📝 检测到用户上传访谈记录,正在通过 DeepSeek-Reasoner 进行深度主题萃取...")prompt = f"Topic: {topic}. Extract the 15 most powerful, representative quotes from the following interview/field text. Organize into a Gioia-style coding structure. Return ONLY a valid JSON array of objects with keys: 'theme' (2nd-order), 'concept' (1st-order), and 'quote' (exact words)."# [修复点 1] 改用流式渲染,保活网关连接with st.status("🧠 正在使用 R1 模型深度萃取访谈语录 (耗时较长,请观察下方思考流以防断连)...", expanded=True) as status:ph = st.empty()response = ph.write_stream(self.agent.stream_deepseek("You are an expert qualitative analyst.", f"DATA:\n{raw_interviews[:30000]}", model_name="deepseek-reasoner"))status.update(label="✅ 访谈主题萃取完成!", state="complete", expanded=False)# 清理流式输出中带有的 think 标签response = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()else:logging.info("⚙️ 未检测到真实访谈记录,正在通过蒙特卡洛引擎模拟高质量定性编码树防幻觉...")prompt = f"Topic: {topic}. Keywords: {keywords}. As an ASQ researcher, simulate a rigorous set of qualitative data for this study. Provide 12 highly realistic, human-sounding representative interview quotes. Group them into emergent 1st-order concepts and 2nd-order themes. Return ONLY a valid JSON array of objects with keys: 'theme', 'concept', 'quote'."# [修复点 2] 模拟过程同样流式化with st.status("⚙️ 正在通过 V3 模型极速模拟定性编码树...", expanded=True) as status:ph = st.empty()response = ph.write_stream(self.agent.stream_deepseek("You are an expert qualitative analyst.", prompt, model_name="deepseek-chat"))status.update(label="✅ 模拟定性编码树构建完成!", state="complete", expanded=False)data = self.agent._extract_json_from_text(response)if not data:logging.error("❌ 定性数据 JSON 解析失败,回退至默认模拟数据。")return "### Table: Qualitative Coding Structure\n| 2nd-order Theme | 1st-order Concept | Representative Quote |\n| :--- | :--- | :--- |\n| Sensemaking | Initial Confusion | \"We really didn't know how to adapt to the new framework.\" [QUOTE-01] |", "⚠️ 数据解析出现偏差,已启用降级保护预案。"if isinstance(data, dict):items = data.get("data", data.get("quotes", []))elif isinstance(data, list):items = dataelse:items = []md = "### Table: Qualitative Coding Structure (Data Evidence)\n| 2nd-order Theme | 1st-order Concept | Representative Quote |\n| :--- | :--- | :--- |\n"for i, item in enumerate(items[:15]):q = str(item.get("quote", "")).replace('"', "'").replace("\n", " ")c = str(item.get("concept", "Analysis")).replace("\n", " ")t = str(item.get("theme", "Observation")).replace("\n", " ")md += f"| {t} | {c} | \"{q}\" [QUOTE-{i+1:02d}] |\n"status_msg = "✅ 已成功启用稳健定性数据生成引擎,Gioia编码结构与代表性语录已就绪。"return md, status_msgdef get_qualitative_engine(agent):return QualitativeEngine(agent)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206# -*- coding: utf-8 -*-"""Qualitative evidence preparation for SmartPaper's ASQ track."""from __future__ import annotationsimport loggingimport reimport streamlit as stclass QualitativeEngine:def __init__(self, agent):self.agent = agent@staticmethoddef _clean_cell(value, default="Not specified"):cleaned = str(value or default).replace("\n", " ").strip()return cleaned or defaultdef _build_request(self, topic, keywords, raw_interviews):schema = """Return ONLY one valid JSON object with this schema:{"study_facts": {"research_setting": "string","data_sources": ["string"],"participant_count": integer or null,"interview_count": integer or null,"analysis_method": "string"},"evidence": [{"theme": "2nd-order theme", "concept": "1st-order concept", "quote": "verbatim quote"}]}"""if raw_interviews and len(raw_interviews) > 100:return f"""Topic: {topic}Keywords: {keywords}Analyze the supplied interview or field material.Rules:1. Use only setting, sample, source, and count information supported by the supplied material. Use null or "Not specified" when absent.2. Extract up to 15 representative quotations verbatim; do not rewrite quotations.3. Build a coherent Gioia-style coding structure.4. The study_facts object will become the single source of truth for the entire manuscript.{schema}<QUALITATIVE_MATERIAL>{raw_interviews[:30000]}</QUALITATIVE_MATERIAL>"""return f"""Topic: {topic}Keywords: {keywords}Construct one internally coherent qualitative study design and evidence packet for a complete ASQ-style manuscript when no interview material is supplied.Rules:1. Choose one research setting and keep it fixed.2. Choose one participant count, interview count, data-source set, and analysis method; do not create conflicting counts.3. Produce exactly 12 natural representative quotations organized into a Gioia-style coding structure.4. The study_facts object will become the single source of truth for the entire manuscript.5. Avoid decorative language, generic AI phrasing, and repetitive quotation patterns.{schema}"""def resolve_qualitative_data(self, topic, keywords, raw_interviews=""):has_user_data = bool(raw_interviews and len(raw_interviews) > 100)prompt = self._build_request(topic, keywords, raw_interviews)model_label = self.agent.model_for("reasoning")if has_user_data:status_label = (f"🧠 正在使用 {model_label} 分析访谈材料并冻结研究事实…")complete_label = "✅ 访谈材料、研究事实与编码结构已完成"else:status_label = (f"🧠 正在使用 {model_label} 构建一致的定性研究证据包…")complete_label = "✅ 定性研究事实与编码结构已完成"with st.status(status_label, expanded=True) as status:placeholder = st.empty()response = placeholder.write_stream(self.agent.stream_deepseek("You are a rigorous qualitative research analyst.",prompt,model_role="reasoning",thinking=True,allow_fallback=False,))status.update(label=complete_label,state="complete",expanded=False,)response = re.sub(r"<think>.*?</think>","",response,flags=re.DOTALL,).strip()data = self.agent._extract_json_from_text(response)if not isinstance(data, dict):logging.error("Qualitative JSON parsing failed; using safe fallback.")data = {"study_facts": {"research_setting": "Not specified","data_sources": ["Interview or field material"],"participant_count": None,"interview_count": None,"analysis_method": "Gioia-style inductive coding",},"evidence": [{"theme": "Sensemaking","concept": "Initial uncertainty","quote": ("We did not yet have a shared understanding ""of how to respond."),}],}facts = data.get("study_facts") or {}evidence = data.get("evidence") or data.get("quotes") or []if not isinstance(evidence, list):evidence = []data_sources = facts.get("data_sources") or ["Not specified"]if not isinstance(data_sources, list):data_sources = [data_sources]setting = self._clean_cell(facts.get("research_setting"))sources = ", ".join(self._clean_cell(item) for item in data_sources)participants = facts.get("participant_count")interviews = facts.get("interview_count")method = self._clean_cell(facts.get("analysis_method"),"Gioia-style inductive coding",)md = ("### Qualitative Study Design Summary\n""| Field | Frozen value |\n""| :--- | :--- |\n"f"| Research setting | {setting} |\n"f"| Data sources | {sources} |\n"f"| Participants | {participants if participants is not None else 'Not specified'} |\n"f"| Interviews | {interviews if interviews is not None else 'Not specified'} |\n"f"| Analysis method | {method} |\n\n""[CONSISTENCY MANDATE]\n""Use the study-design summary above as the single source of truth. ""Do not change the setting, sample, interview count, data sources, ""or analysis method in any section.\n\n""### Table: Qualitative Coding Structure (Data Evidence)\n""| 2nd-order Theme | 1st-order Concept | Representative Quote |\n""| :--- | :--- | :--- |\n")clean_evidence = []for index, item in enumerate(evidence[:15]):if not isinstance(item, dict):continuequote = self._clean_cell(item.get("quote"), "").replace('"', "'")concept = self._clean_cell(item.get("concept"), "Analysis")theme = self._clean_cell(item.get("theme"), "Observation")if not quote:continuetag = f"QUOTE-{index + 1:02d}"md += f'| {theme} | {concept} | "{quote}" [{tag}] |\n'clean_evidence.append({"theme": theme,"concept": concept,"quote": quote,"tag": tag,})metadata = {"mode": "qualitative","source_type": ("user_provided" if has_user_data else "system_generated"),"disclosure_required": not has_user_data,"study_facts": {"research_setting": setting,"data_sources": data_sources,"participant_count": participants,"interview_count": interviews,"analysis_method": method,},"evidence_count": len(clean_evidence),}status_message = "✅ 定性研究事实、摘要锚点输入和Gioia编码证据已准备完成。"return md, status_message, metadatadef get_qualitative_engine(agent):return QualitativeEngine(agent)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# -*- coding: utf-8 -*-"""Quantitative data preparation for SmartPaper's AMJ track."""
from __future__ import annotations
import numpy as npimport pandas as pd
from i18n import trfrom utils.file_parser import extract_data_from_files
class QuantitativeEngine: """Keep quantitative preparation isolated from the Streamlit UI."""
@staticmethod def generate_psd_corr_matrix(n_constructs, max_corr=0.5): if n_constructs == 1: return np.array([[1.0]]) base_corr = np.random.uniform(0.2, max_corr - 0.1) matrix = np.random.uniform( base_corr - 0.1, base_corr + 0.1, (n_constructs, n_constructs), ) matrix = (matrix + matrix.T) / 2 np.fill_diagonal(matrix, 1.0) min_eig = np.min(np.linalg.eigvals(matrix)) if min_eig < 0: matrix -= (min_eig - 0.01) * np.eye(n_constructs) diagonal = np.sqrt(np.diag(matrix)) return matrix / np.outer(diagonal, diagonal)
@staticmethod def calculate_validity_metrics(df, constructs_info, true_loadings): metrics = [] for construct in constructs_info: construct_name = construct["name"] items = construct["items"] sub_df = df[items] var_total = sub_df.sum(axis=1).var(ddof=1) sum_var = sub_df.var(ddof=1).sum() n_items = len(items) alpha = ( 0.0 if var_total <= 0 else (n_items / (n_items - 1)) * (1 - sum_var / var_total) ) loadings = np.array(true_loadings[construct_name]) sum_loadings_sq = np.sum(loadings) ** 2 sum_sq_loadings = np.sum(loadings**2) sum_error = np.sum(1 - loadings**2) cr = sum_loadings_sq / (sum_loadings_sq + sum_error) ave = sum_sq_loadings / len(loadings) metrics.append( { "Construct": construct_name, "Items": n_items, "Cronbach's α": round(alpha, 3), "CR": round(cr, 3), "AVE": round(ave, 3), } ) return pd.DataFrame(metrics)
def generate_empirical_data_robust( self, construct_names=None, n=300, scale_points=7, ): if not construct_names or len(construct_names) < 2: construct_names = [ "Independent_Var", "Mediator_Var", "Dependent_Var", ]
n_constructs = len(construct_names) corr = self.generate_psd_corr_matrix(n_constructs, max_corr=0.55) latent_scores = np.random.multivariate_normal( mean=[0] * n_constructs, cov=corr, size=n, ) data = {} true_loadings = {} constructs_info = [] target_mean = scale_points / 2.0 + 0.5 target_std = scale_points / 5.0
for index, construct_name in enumerate(construct_names): true_score = latent_scores[:, index] n_items = np.random.randint(3, 6) loadings = np.random.uniform(0.72, 0.88, n_items) true_loadings[construct_name] = loadings item_names = [] for item_index, loading in enumerate(loadings): error = np.random.normal( 0, np.sqrt(1 - loading**2), n, ) item_score = loading * true_score + error raw_scaled = item_score * target_std + target_mean item_int = np.clip( np.round(raw_scaled), 1, scale_points, ).astype(int) column_name = f"{construct_name}_{item_index + 1}" data[column_name] = item_int item_names.append(column_name) constructs_info.append( {"name": construct_name, "items": item_names} )
df = pd.DataFrame(data) validity_df = self.calculate_validity_metrics( df, constructs_info, true_loadings, ) mean_scores = pd.DataFrame( { construct["name"]: df[construct["items"]].mean(axis=1) for construct in constructs_info } ) fl_matrix = mean_scores.corr().astype(object)
for _, row in validity_df.iterrows(): construct_name = row["Construct"] sqrt_ave = np.sqrt(row["AVE"]) fl_matrix.loc[construct_name, construct_name] = ( f"({sqrt_ave:.3f})" )
for row_index in range(len(fl_matrix.columns)): for column_index in range(row_index + 1, len(fl_matrix.columns)): fl_matrix.iloc[row_index, column_index] = ""
desc_stats = mean_scores.mean().to_frame("Mean").join( mean_scores.std().to_frame("SD") ) return df, validity_df, desc_stats.join(fl_matrix)
def resolve_empirical_data(self, uploaded_files=None, language="zh"): if uploaded_files: user_md = extract_data_from_files(uploaded_files) if user_md: metadata = { "mode": "quantitative", "source_type": "user_provided", "disclosure_required": False, } return None, user_md, tr(language, "actual_stats_parsed"), metadata
df, validity_df, fl_matrix_df = self.generate_empirical_data_robust() generated_prompt = f"""### Table 1: Reliability and Convergent Validity{validity_df.to_markdown(index=False)}### Table 2: Descriptive Statistics and Discriminant Validity (Fornell-Larcker Criterion)*Note: Diagonal elements in parentheses are the square roots of AVE.*{fl_matrix_df.to_markdown()}[STRICT EMPIRICAL INSTRUCTION]1. ZERO HALLUCINATION: Report the exact metrics provided above.2. VALIDITY DEFENSE: State convergent validity only when the displayed AVE and CR values support it.3. DISCRIMINANT DEFENSE: State discriminant validity only when the displayed diagonal and correlation values support it.4. CONSISTENCY: Use these tables as the single source of numerical truth throughout the paper.""" metadata = { "mode": "quantitative", "source_type": "system_generated", "disclosure_required": True, "sample_size": int(len(df)), "scale_points": 7, "method": ( "Positive-semidefinite latent correlation generation, " "indicator loadings, discretization, and derived " "reliability/validity summaries." ), } return ( df, generated_prompt, tr(language, "synthetic_stats_generated"), metadata, )
def get_quantitative_engine(): return QuantitativeEngine()core/pipeline_agent.py+296-126
core/qualitative_engine.py+192-48
core/quantitative_engine.pyAdded+193