Spaces:
Running
Running
Upload 3 files
Browse files- core/pipeline_agent.py +296 -126
- core/qualitative_engine.py +192 -48
- core/quantitative_engine.py +193 -0
core/pipeline_agent.py
CHANGED
|
@@ -77,20 +77,34 @@ class SSciPipelineAgent:
|
|
| 77 |
self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]
|
| 78 |
|
| 79 |
self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
)
|
| 89 |
-
self.deepseek_reasoning_effort = str(
|
| 90 |
-
APP_CONFIG.get("deepseek_reasoning_effort", "high")
|
| 91 |
-
).strip().lower()
|
| 92 |
self.deepseek_max_retries = max(
|
| 93 |
-
1,
|
|
|
|
| 94 |
)
|
| 95 |
self.deepseek_show_reasoning = bool(
|
| 96 |
APP_CONFIG.get("deepseek_show_reasoning", False)
|
|
@@ -170,7 +184,15 @@ class SSciPipelineAgent:
|
|
| 170 |
if not text.strip():
|
| 171 |
return ""
|
| 172 |
sys_prompt = f"Translate the following text into {target_lang}. Preserve formatting and [CITE-XX] tags exactly. Output ONLY the translation."
|
| 173 |
-
return self.call_deepseek(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
@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)))
|
| 176 |
def _requests_get_with_retry(self, url, headers=None, params=None, timeout=None):
|
|
@@ -295,33 +317,61 @@ class SSciPipelineAgent:
|
|
| 295 |
return self._truncate_context(full, max_tokens)
|
| 296 |
return full
|
| 297 |
|
| 298 |
-
def
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
}
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
raise DeepSeekRequestError(
|
| 317 |
-
f"
|
| 318 |
-
"Use 'deepseek-v4-flash' or 'deepseek-v4-pro'."
|
| 319 |
)
|
| 320 |
-
|
| 321 |
if thinking is None:
|
| 322 |
-
thinking =
|
| 323 |
-
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
def _build_deepseek_payload(
|
| 327 |
self,
|
|
@@ -335,12 +385,6 @@ class SSciPipelineAgent:
|
|
| 335 |
stream,
|
| 336 |
reasoning_effort,
|
| 337 |
):
|
| 338 |
-
effort = str(
|
| 339 |
-
reasoning_effort or self.deepseek_reasoning_effort
|
| 340 |
-
).strip().lower()
|
| 341 |
-
if effort not in {"high", "max"}:
|
| 342 |
-
effort = "high"
|
| 343 |
-
|
| 344 |
payload = {
|
| 345 |
"model": model_name,
|
| 346 |
"messages": [
|
|
@@ -355,10 +399,11 @@ class SSciPipelineAgent:
|
|
| 355 |
}
|
| 356 |
|
| 357 |
if thinking:
|
| 358 |
-
payload["reasoning_effort"] =
|
| 359 |
else:
|
| 360 |
payload["temperature"] = max(
|
| 361 |
-
0.0,
|
|
|
|
| 362 |
)
|
| 363 |
|
| 364 |
return payload
|
|
@@ -369,7 +414,7 @@ class SSciPipelineAgent:
|
|
| 369 |
"Authorization": f"Bearer {api_key}",
|
| 370 |
"Content-Type": "application/json",
|
| 371 |
"Accept": "application/json",
|
| 372 |
-
"User-Agent": "SmartPaper/
|
| 373 |
}
|
| 374 |
|
| 375 |
@staticmethod
|
|
@@ -425,7 +470,10 @@ class SSciPipelineAgent:
|
|
| 425 |
if raw_line is None:
|
| 426 |
return None
|
| 427 |
if isinstance(raw_line, bytes):
|
| 428 |
-
line = raw_line.decode(
|
|
|
|
|
|
|
|
|
|
| 429 |
else:
|
| 430 |
line = str(raw_line).strip()
|
| 431 |
|
|
@@ -442,23 +490,29 @@ class SSciPipelineAgent:
|
|
| 442 |
return json.loads(data)
|
| 443 |
except json.JSONDecodeError:
|
| 444 |
logging.warning(
|
| 445 |
-
"
|
| 446 |
data[:160],
|
| 447 |
)
|
| 448 |
return None
|
| 449 |
|
| 450 |
-
def _attempt_plan(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
total = self.deepseek_max_retries
|
|
|
|
| 452 |
for attempt in range(total):
|
| 453 |
model = requested_model
|
| 454 |
thinking = requested_thinking
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
yield attempt, model, thinking
|
| 463 |
|
| 464 |
def call_deepseek(
|
|
@@ -467,18 +521,31 @@ class SSciPipelineAgent:
|
|
| 467 |
user_prompt,
|
| 468 |
max_tokens=8000,
|
| 469 |
temp=0.3,
|
| 470 |
-
model_name=
|
|
|
|
| 471 |
thinking=None,
|
| 472 |
reasoning_effort=None,
|
|
|
|
| 473 |
):
|
| 474 |
-
|
| 475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
)
|
| 477 |
tokens_est = self._count_tokens(str(user_prompt))
|
| 478 |
|
| 479 |
logging.info(
|
| 480 |
-
"
|
| 481 |
-
"
|
|
|
|
| 482 |
requested_model,
|
| 483 |
requested_thinking,
|
| 484 |
max_tokens,
|
|
@@ -486,21 +553,18 @@ class SSciPipelineAgent:
|
|
| 486 |
)
|
| 487 |
|
| 488 |
last_error = None
|
| 489 |
-
|
| 490 |
for attempt, current_model, current_thinking in self._attempt_plan(
|
| 491 |
-
requested_model,
|
|
|
|
|
|
|
| 492 |
):
|
| 493 |
with self.lock:
|
| 494 |
self.ds_calls += 1
|
| 495 |
|
| 496 |
-
if
|
| 497 |
-
current_model != requested_model
|
| 498 |
-
or current_thinking != requested_thinking
|
| 499 |
-
):
|
| 500 |
logging.warning(
|
| 501 |
-
"
|
| 502 |
current_model,
|
| 503 |
-
current_thinking,
|
| 504 |
)
|
| 505 |
|
| 506 |
payload = self._build_deepseek_payload(
|
|
@@ -511,7 +575,7 @@ class SSciPipelineAgent:
|
|
| 511 |
max_tokens=max_tokens,
|
| 512 |
temp=temp,
|
| 513 |
stream=False,
|
| 514 |
-
reasoning_effort=
|
| 515 |
)
|
| 516 |
start_time = time.time()
|
| 517 |
|
|
@@ -549,10 +613,9 @@ class SSciPipelineAgent:
|
|
| 549 |
f"finish_reason={finish_reason!r}"
|
| 550 |
)
|
| 551 |
|
| 552 |
-
elapsed = time.time() - start_time
|
| 553 |
logging.info(
|
| 554 |
-
"
|
| 555 |
-
|
| 556 |
len(content),
|
| 557 |
)
|
| 558 |
return content
|
|
@@ -572,7 +635,7 @@ class SSciPipelineAgent:
|
|
| 572 |
last_error = exc
|
| 573 |
is_last = attempt == self.deepseek_max_retries - 1
|
| 574 |
logging.error(
|
| 575 |
-
"
|
| 576 |
attempt + 1,
|
| 577 |
self.deepseek_max_retries,
|
| 578 |
exc,
|
|
@@ -582,7 +645,7 @@ class SSciPipelineAgent:
|
|
| 582 |
time.sleep(self._retry_delay(attempt))
|
| 583 |
|
| 584 |
raise DeepSeekAPIError(
|
| 585 |
-
|
| 586 |
f"{self.deepseek_max_retries} attempts: {last_error}"
|
| 587 |
)
|
| 588 |
|
|
@@ -591,19 +654,32 @@ class SSciPipelineAgent:
|
|
| 591 |
system_prompt,
|
| 592 |
user_prompt,
|
| 593 |
max_tokens=8000,
|
| 594 |
-
model_name=
|
|
|
|
| 595 |
thinking=None,
|
| 596 |
reasoning_effort=None,
|
| 597 |
temp=0.3,
|
|
|
|
| 598 |
):
|
| 599 |
-
|
| 600 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
)
|
| 602 |
tokens_est = self._count_tokens(str(user_prompt))
|
| 603 |
|
| 604 |
logging.info(
|
| 605 |
-
"
|
| 606 |
-
"
|
|
|
|
| 607 |
requested_model,
|
| 608 |
requested_thinking,
|
| 609 |
max_tokens,
|
|
@@ -611,21 +687,18 @@ class SSciPipelineAgent:
|
|
| 611 |
)
|
| 612 |
|
| 613 |
last_error = None
|
| 614 |
-
|
| 615 |
for attempt, current_model, current_thinking in self._attempt_plan(
|
| 616 |
-
requested_model,
|
|
|
|
|
|
|
| 617 |
):
|
| 618 |
with self.lock:
|
| 619 |
self.ds_calls += 1
|
| 620 |
|
| 621 |
-
if
|
| 622 |
-
current_model != requested_model
|
| 623 |
-
or current_thinking != requested_thinking
|
| 624 |
-
):
|
| 625 |
logging.warning(
|
| 626 |
-
"
|
| 627 |
current_model,
|
| 628 |
-
current_thinking,
|
| 629 |
)
|
| 630 |
|
| 631 |
payload = self._build_deepseek_payload(
|
|
@@ -636,7 +709,7 @@ class SSciPipelineAgent:
|
|
| 636 |
max_tokens=max_tokens,
|
| 637 |
temp=temp,
|
| 638 |
stream=True,
|
| 639 |
-
reasoning_effort=
|
| 640 |
)
|
| 641 |
|
| 642 |
emitted_content = False
|
|
@@ -679,7 +752,7 @@ class SSciPipelineAgent:
|
|
| 679 |
if not reasoning_open:
|
| 680 |
reasoning_open = True
|
| 681 |
logging.info(
|
| 682 |
-
"
|
| 683 |
)
|
| 684 |
if self.deepseek_show_reasoning:
|
| 685 |
yield "\n<think>\n"
|
|
@@ -691,7 +764,7 @@ class SSciPipelineAgent:
|
|
| 691 |
|
| 692 |
if reasoning_chunks % 25 == 0:
|
| 693 |
logging.info(
|
| 694 |
-
"
|
| 695 |
"%.1fs, %s chunks",
|
| 696 |
time.time() - start_time,
|
| 697 |
reasoning_chunks,
|
|
@@ -707,10 +780,7 @@ class SSciPipelineAgent:
|
|
| 707 |
emitted_content = True
|
| 708 |
yield str(content)
|
| 709 |
|
| 710 |
-
if
|
| 711 |
-
reasoning_open
|
| 712 |
-
and self.deepseek_show_reasoning
|
| 713 |
-
):
|
| 714 |
yield "\n</think>\n"
|
| 715 |
|
| 716 |
if not emitted_content:
|
|
@@ -719,7 +789,7 @@ class SSciPipelineAgent:
|
|
| 719 |
)
|
| 720 |
|
| 721 |
logging.info(
|
| 722 |
-
"
|
| 723 |
time.time() - start_time,
|
| 724 |
)
|
| 725 |
return
|
|
@@ -740,7 +810,7 @@ class SSciPipelineAgent:
|
|
| 740 |
) as exc:
|
| 741 |
last_error = exc
|
| 742 |
logging.error(
|
| 743 |
-
"
|
| 744 |
attempt + 1,
|
| 745 |
self.deepseek_max_retries,
|
| 746 |
exc,
|
|
@@ -758,7 +828,7 @@ class SSciPipelineAgent:
|
|
| 758 |
time.sleep(self._retry_delay(attempt))
|
| 759 |
|
| 760 |
raise DeepSeekAPIError(
|
| 761 |
-
|
| 762 |
f"{self.deepseek_max_retries} attempts: {last_error}"
|
| 763 |
)
|
| 764 |
|
|
@@ -774,7 +844,14 @@ class SSciPipelineAgent:
|
|
| 774 |
for attempt in range(2):
|
| 775 |
try:
|
| 776 |
logging.info("📄 [本地解析] 正在榨取用户上传的核心文献...")
|
| 777 |
-
response = self.call_deepseek(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 778 |
papers = self._extract_json_from_text(response)
|
| 779 |
if not papers:
|
| 780 |
raise ValueError("Invalid JSON")
|
|
@@ -829,26 +906,74 @@ class SSciPipelineAgent:
|
|
| 829 |
"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])
|
| 830 |
return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)
|
| 831 |
|
| 832 |
-
def generate_anchors(
|
| 833 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 834 |
format_mandate = """\n\n[CRITICAL FORMAT MANDATE]
|
| 835 |
-
You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings
|
| 836 |
---ABSTRACT---
|
| 837 |
(Write the comprehensive abstract here)
|
| 838 |
---CONCLUSION---
|
| 839 |
(Write the expected conclusion here)"""
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 852 |
return final_abstract, final_conclusion
|
| 853 |
|
| 854 |
# ... 保留上面的 synthesize_literature 和 generate_anchors 函数不变 ...
|
|
@@ -860,22 +985,62 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 860 |
user_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace(
|
| 861 |
"{topic}", topic).replace("{user_injection}", user_injection).replace(
|
| 862 |
"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])
|
| 863 |
-
return self.stream_deepseek(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 864 |
|
| 865 |
-
#
|
| 866 |
-
def stream_generate_anchors(
|
| 867 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 868 |
format_mandate = """\n\n[CRITICAL FORMAT MANDATE]
|
| 869 |
-
You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings
|
| 870 |
---ABSTRACT---
|
| 871 |
(Write the comprehensive abstract here)
|
| 872 |
---CONCLUSION---
|
| 873 |
(Write the expected conclusion here)"""
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
|
| 880 |
# =====================================================================
|
| 881 |
# [核心架构升级] 双轨制大纲路由,取代自由生成的结构断层风险
|
|
@@ -886,7 +1051,7 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 886 |
|
| 887 |
sys_prompt = "You are a senior academic editor. Polish the provided section titles to be more professional but DO NOT change the structure."
|
| 888 |
structure_str = " || ".join([s["section"] for s in sections])
|
| 889 |
-
response = self.call_deepseek(sys_prompt, f"Topic: {topic}. Structure: {structure_str}. Output refined titles only, separated by ' || '.",
|
| 890 |
|
| 891 |
refined_titles = [t.strip() for t in response.split("||")]
|
| 892 |
|
|
@@ -910,7 +1075,7 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 910 |
sec_title = sec.get("section", "")
|
| 911 |
if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result", "finding", "setting"]):
|
| 912 |
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."
|
| 913 |
-
query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2,
|
| 914 |
if query:
|
| 915 |
queries_to_fetch.add(query)
|
| 916 |
|
|
@@ -949,7 +1114,12 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 949 |
Return ONLY a valid JSON array of strings."""
|
| 950 |
user_prompt = f"Topic: {topic}\nKeywords: {keywords}"
|
| 951 |
for attempt in range(3):
|
| 952 |
-
queries = self._extract_json_from_text(self.call_deepseek(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 953 |
if queries and isinstance(queries, list) and len(queries) > 0:
|
| 954 |
final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]
|
| 955 |
if final_queries:
|
|
@@ -1105,7 +1275,7 @@ Return ONLY a valid JSON array of strings."""
|
|
| 1105 |
3. Output simple, space-separated keyword combinations under 5 terms.
|
| 1106 |
Return ONLY a JSON array of strings."""
|
| 1107 |
user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nUsed Queries: {list(all_used_terms)}\nGenerate 3 NEW, BROADER English search queries."
|
| 1108 |
-
response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5,
|
| 1109 |
queries = self._extract_json_from_text(response)
|
| 1110 |
if isinstance(queries, list):
|
| 1111 |
search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]
|
|
|
|
| 77 |
self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]
|
| 78 |
|
| 79 |
self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]
|
| 80 |
+
configured_models = APP_CONFIG.get("deepseek_models") or {}
|
| 81 |
+
self.deepseek_models = {
|
| 82 |
+
str(role).strip().lower(): str(model or "").strip()
|
| 83 |
+
for role, model in configured_models.items()
|
| 84 |
+
}
|
| 85 |
+
required_roles = {
|
| 86 |
+
"reasoning",
|
| 87 |
+
"writing",
|
| 88 |
+
"translation",
|
| 89 |
+
"fast",
|
| 90 |
+
"fallback",
|
| 91 |
+
}
|
| 92 |
+
missing_roles = [
|
| 93 |
+
role for role in required_roles
|
| 94 |
+
if not self.deepseek_models.get(role)
|
| 95 |
+
]
|
| 96 |
+
if missing_roles:
|
| 97 |
+
raise DeepSeekRequestError(
|
| 98 |
+
"Missing DeepSeek model role configuration: "
|
| 99 |
+
+ ", ".join(sorted(missing_roles))
|
| 100 |
+
)
|
| 101 |
+
self.deepseek_task_settings = APP_CONFIG.get(
|
| 102 |
+
"deepseek_task_settings",
|
| 103 |
+
{},
|
| 104 |
)
|
|
|
|
|
|
|
|
|
|
| 105 |
self.deepseek_max_retries = max(
|
| 106 |
+
1,
|
| 107 |
+
int(APP_CONFIG.get("deepseek_max_retries", 3)),
|
| 108 |
)
|
| 109 |
self.deepseek_show_reasoning = bool(
|
| 110 |
APP_CONFIG.get("deepseek_show_reasoning", False)
|
|
|
|
| 184 |
if not text.strip():
|
| 185 |
return ""
|
| 186 |
sys_prompt = f"Translate the following text into {target_lang}. Preserve formatting and [CITE-XX] tags exactly. Output ONLY the translation."
|
| 187 |
+
return self.call_deepseek(
|
| 188 |
+
sys_prompt,
|
| 189 |
+
text,
|
| 190 |
+
max_tokens=max_tokens,
|
| 191 |
+
temp=0.2,
|
| 192 |
+
model_role="translation",
|
| 193 |
+
thinking=False,
|
| 194 |
+
allow_fallback=False,
|
| 195 |
+
)
|
| 196 |
|
| 197 |
@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)))
|
| 198 |
def _requests_get_with_retry(self, url, headers=None, params=None, timeout=None):
|
|
|
|
| 317 |
return self._truncate_context(full, max_tokens)
|
| 318 |
return full
|
| 319 |
|
| 320 |
+
def model_for(self, model_role="reasoning"):
|
| 321 |
+
role = str(model_role or "reasoning").strip().lower()
|
| 322 |
+
model = self.deepseek_models.get(role)
|
| 323 |
+
if not model:
|
| 324 |
+
raise DeepSeekRequestError(
|
| 325 |
+
f"Unknown or unconfigured DeepSeek model role: {role!r}."
|
| 326 |
+
)
|
| 327 |
+
return model
|
| 328 |
|
| 329 |
+
def _task_settings(self, model_role):
|
| 330 |
+
role = str(model_role or "reasoning").strip().lower()
|
| 331 |
+
raw = self.deepseek_task_settings.get(role) or {}
|
| 332 |
+
effort = str(raw.get("reasoning_effort", "high")).strip().lower()
|
| 333 |
+
if effort not in {"low", "high", "max"}:
|
| 334 |
+
effort = "high"
|
| 335 |
+
return {
|
| 336 |
+
"thinking": bool(raw.get("thinking", role == "reasoning")),
|
| 337 |
+
"reasoning_effort": effort,
|
| 338 |
+
"allow_fallback": bool(raw.get("allow_fallback", False)),
|
| 339 |
}
|
| 340 |
+
|
| 341 |
+
def _resolve_deepseek_request(
|
| 342 |
+
self,
|
| 343 |
+
model_name=None,
|
| 344 |
+
model_role="reasoning",
|
| 345 |
+
thinking=None,
|
| 346 |
+
reasoning_effort=None,
|
| 347 |
+
allow_fallback=None,
|
| 348 |
+
):
|
| 349 |
+
role = str(model_role or "reasoning").strip().lower()
|
| 350 |
+
requested_name = str(model_name or "").strip()
|
| 351 |
+
|
| 352 |
+
settings = self._task_settings(role)
|
| 353 |
+
model = requested_name or self.model_for(role)
|
| 354 |
+
if not model:
|
| 355 |
raise DeepSeekRequestError(
|
| 356 |
+
f"No DeepSeek model configured for role {role!r}."
|
|
|
|
| 357 |
)
|
|
|
|
| 358 |
if thinking is None:
|
| 359 |
+
thinking = settings["thinking"]
|
| 360 |
+
if reasoning_effort is None:
|
| 361 |
+
reasoning_effort = settings["reasoning_effort"]
|
| 362 |
+
effort = str(reasoning_effort).strip().lower()
|
| 363 |
+
if effort not in {"low", "high", "max"}:
|
| 364 |
+
effort = "high"
|
| 365 |
+
if allow_fallback is None:
|
| 366 |
+
allow_fallback = settings["allow_fallback"]
|
| 367 |
+
|
| 368 |
+
return (
|
| 369 |
+
model,
|
| 370 |
+
bool(thinking),
|
| 371 |
+
effort,
|
| 372 |
+
bool(allow_fallback),
|
| 373 |
+
role,
|
| 374 |
+
)
|
| 375 |
|
| 376 |
def _build_deepseek_payload(
|
| 377 |
self,
|
|
|
|
| 385 |
stream,
|
| 386 |
reasoning_effort,
|
| 387 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
payload = {
|
| 389 |
"model": model_name,
|
| 390 |
"messages": [
|
|
|
|
| 399 |
}
|
| 400 |
|
| 401 |
if thinking:
|
| 402 |
+
payload["reasoning_effort"] = reasoning_effort
|
| 403 |
else:
|
| 404 |
payload["temperature"] = max(
|
| 405 |
+
0.0,
|
| 406 |
+
min(float(temp), 2.0),
|
| 407 |
)
|
| 408 |
|
| 409 |
return payload
|
|
|
|
| 414 |
"Authorization": f"Bearer {api_key}",
|
| 415 |
"Content-Type": "application/json",
|
| 416 |
"Accept": "application/json",
|
| 417 |
+
"User-Agent": "SmartPaper/DeepSeek",
|
| 418 |
}
|
| 419 |
|
| 420 |
@staticmethod
|
|
|
|
| 470 |
if raw_line is None:
|
| 471 |
return None
|
| 472 |
if isinstance(raw_line, bytes):
|
| 473 |
+
line = raw_line.decode(
|
| 474 |
+
"utf-8",
|
| 475 |
+
errors="replace",
|
| 476 |
+
).strip()
|
| 477 |
else:
|
| 478 |
line = str(raw_line).strip()
|
| 479 |
|
|
|
|
| 490 |
return json.loads(data)
|
| 491 |
except json.JSONDecodeError:
|
| 492 |
logging.warning(
|
| 493 |
+
"Ignored malformed DeepSeek SSE chunk: %s",
|
| 494 |
data[:160],
|
| 495 |
)
|
| 496 |
return None
|
| 497 |
|
| 498 |
+
def _attempt_plan(
|
| 499 |
+
self,
|
| 500 |
+
requested_model,
|
| 501 |
+
requested_thinking,
|
| 502 |
+
allow_fallback,
|
| 503 |
+
):
|
| 504 |
total = self.deepseek_max_retries
|
| 505 |
+
fallback_model = self.deepseek_models.get("fallback", "")
|
| 506 |
for attempt in range(total):
|
| 507 |
model = requested_model
|
| 508 |
thinking = requested_thinking
|
| 509 |
+
if (
|
| 510 |
+
allow_fallback
|
| 511 |
+
and attempt == total - 1
|
| 512 |
+
and fallback_model
|
| 513 |
+
and fallback_model != requested_model
|
| 514 |
+
):
|
| 515 |
+
model = fallback_model
|
| 516 |
yield attempt, model, thinking
|
| 517 |
|
| 518 |
def call_deepseek(
|
|
|
|
| 521 |
user_prompt,
|
| 522 |
max_tokens=8000,
|
| 523 |
temp=0.3,
|
| 524 |
+
model_name=None,
|
| 525 |
+
model_role="reasoning",
|
| 526 |
thinking=None,
|
| 527 |
reasoning_effort=None,
|
| 528 |
+
allow_fallback=None,
|
| 529 |
):
|
| 530 |
+
(
|
| 531 |
+
requested_model,
|
| 532 |
+
requested_thinking,
|
| 533 |
+
resolved_effort,
|
| 534 |
+
resolved_fallback,
|
| 535 |
+
resolved_role,
|
| 536 |
+
) = self._resolve_deepseek_request(
|
| 537 |
+
model_name=model_name,
|
| 538 |
+
model_role=model_role,
|
| 539 |
+
thinking=thinking,
|
| 540 |
+
reasoning_effort=reasoning_effort,
|
| 541 |
+
allow_fallback=allow_fallback,
|
| 542 |
)
|
| 543 |
tokens_est = self._count_tokens(str(user_prompt))
|
| 544 |
|
| 545 |
logging.info(
|
| 546 |
+
"DeepSeek static request | role=%s | model=%s | "
|
| 547 |
+
"thinking=%s | max_tokens=%s | input_est=%s",
|
| 548 |
+
resolved_role,
|
| 549 |
requested_model,
|
| 550 |
requested_thinking,
|
| 551 |
max_tokens,
|
|
|
|
| 553 |
)
|
| 554 |
|
| 555 |
last_error = None
|
|
|
|
| 556 |
for attempt, current_model, current_thinking in self._attempt_plan(
|
| 557 |
+
requested_model,
|
| 558 |
+
requested_thinking,
|
| 559 |
+
resolved_fallback,
|
| 560 |
):
|
| 561 |
with self.lock:
|
| 562 |
self.ds_calls += 1
|
| 563 |
|
| 564 |
+
if current_model != requested_model:
|
|
|
|
|
|
|
|
|
|
| 565 |
logging.warning(
|
| 566 |
+
"Non-critical final fallback: model=%s",
|
| 567 |
current_model,
|
|
|
|
| 568 |
)
|
| 569 |
|
| 570 |
payload = self._build_deepseek_payload(
|
|
|
|
| 575 |
max_tokens=max_tokens,
|
| 576 |
temp=temp,
|
| 577 |
stream=False,
|
| 578 |
+
reasoning_effort=resolved_effort,
|
| 579 |
)
|
| 580 |
start_time = time.time()
|
| 581 |
|
|
|
|
| 613 |
f"finish_reason={finish_reason!r}"
|
| 614 |
)
|
| 615 |
|
|
|
|
| 616 |
logging.info(
|
| 617 |
+
"DeepSeek static response | seconds=%.2f | chars=%s",
|
| 618 |
+
time.time() - start_time,
|
| 619 |
len(content),
|
| 620 |
)
|
| 621 |
return content
|
|
|
|
| 635 |
last_error = exc
|
| 636 |
is_last = attempt == self.deepseek_max_retries - 1
|
| 637 |
logging.error(
|
| 638 |
+
"DeepSeek attempt %s/%s failed: %s",
|
| 639 |
attempt + 1,
|
| 640 |
self.deepseek_max_retries,
|
| 641 |
exc,
|
|
|
|
| 645 |
time.sleep(self._retry_delay(attempt))
|
| 646 |
|
| 647 |
raise DeepSeekAPIError(
|
| 648 |
+
"DeepSeek API failed after "
|
| 649 |
f"{self.deepseek_max_retries} attempts: {last_error}"
|
| 650 |
)
|
| 651 |
|
|
|
|
| 654 |
system_prompt,
|
| 655 |
user_prompt,
|
| 656 |
max_tokens=8000,
|
| 657 |
+
model_name=None,
|
| 658 |
+
model_role="reasoning",
|
| 659 |
thinking=None,
|
| 660 |
reasoning_effort=None,
|
| 661 |
temp=0.3,
|
| 662 |
+
allow_fallback=None,
|
| 663 |
):
|
| 664 |
+
(
|
| 665 |
+
requested_model,
|
| 666 |
+
requested_thinking,
|
| 667 |
+
resolved_effort,
|
| 668 |
+
resolved_fallback,
|
| 669 |
+
resolved_role,
|
| 670 |
+
) = self._resolve_deepseek_request(
|
| 671 |
+
model_name=model_name,
|
| 672 |
+
model_role=model_role,
|
| 673 |
+
thinking=thinking,
|
| 674 |
+
reasoning_effort=reasoning_effort,
|
| 675 |
+
allow_fallback=allow_fallback,
|
| 676 |
)
|
| 677 |
tokens_est = self._count_tokens(str(user_prompt))
|
| 678 |
|
| 679 |
logging.info(
|
| 680 |
+
"DeepSeek stream request | role=%s | model=%s | "
|
| 681 |
+
"thinking=%s | max_tokens=%s | input_est=%s",
|
| 682 |
+
resolved_role,
|
| 683 |
requested_model,
|
| 684 |
requested_thinking,
|
| 685 |
max_tokens,
|
|
|
|
| 687 |
)
|
| 688 |
|
| 689 |
last_error = None
|
|
|
|
| 690 |
for attempt, current_model, current_thinking in self._attempt_plan(
|
| 691 |
+
requested_model,
|
| 692 |
+
requested_thinking,
|
| 693 |
+
resolved_fallback,
|
| 694 |
):
|
| 695 |
with self.lock:
|
| 696 |
self.ds_calls += 1
|
| 697 |
|
| 698 |
+
if current_model != requested_model:
|
|
|
|
|
|
|
|
|
|
| 699 |
logging.warning(
|
| 700 |
+
"Non-critical final fallback: model=%s",
|
| 701 |
current_model,
|
|
|
|
| 702 |
)
|
| 703 |
|
| 704 |
payload = self._build_deepseek_payload(
|
|
|
|
| 709 |
max_tokens=max_tokens,
|
| 710 |
temp=temp,
|
| 711 |
stream=True,
|
| 712 |
+
reasoning_effort=resolved_effort,
|
| 713 |
)
|
| 714 |
|
| 715 |
emitted_content = False
|
|
|
|
| 752 |
if not reasoning_open:
|
| 753 |
reasoning_open = True
|
| 754 |
logging.info(
|
| 755 |
+
"DeepSeek thinking started."
|
| 756 |
)
|
| 757 |
if self.deepseek_show_reasoning:
|
| 758 |
yield "\n<think>\n"
|
|
|
|
| 764 |
|
| 765 |
if reasoning_chunks % 25 == 0:
|
| 766 |
logging.info(
|
| 767 |
+
"DeepSeek thinking heartbeat: "
|
| 768 |
"%.1fs, %s chunks",
|
| 769 |
time.time() - start_time,
|
| 770 |
reasoning_chunks,
|
|
|
|
| 780 |
emitted_content = True
|
| 781 |
yield str(content)
|
| 782 |
|
| 783 |
+
if reasoning_open and self.deepseek_show_reasoning:
|
|
|
|
|
|
|
|
|
|
| 784 |
yield "\n</think>\n"
|
| 785 |
|
| 786 |
if not emitted_content:
|
|
|
|
| 789 |
)
|
| 790 |
|
| 791 |
logging.info(
|
| 792 |
+
"DeepSeek stream complete | seconds=%.1f",
|
| 793 |
time.time() - start_time,
|
| 794 |
)
|
| 795 |
return
|
|
|
|
| 810 |
) as exc:
|
| 811 |
last_error = exc
|
| 812 |
logging.error(
|
| 813 |
+
"DeepSeek stream attempt %s/%s failed: %s",
|
| 814 |
attempt + 1,
|
| 815 |
self.deepseek_max_retries,
|
| 816 |
exc,
|
|
|
|
| 828 |
time.sleep(self._retry_delay(attempt))
|
| 829 |
|
| 830 |
raise DeepSeekAPIError(
|
| 831 |
+
"DeepSeek streaming failed after "
|
| 832 |
f"{self.deepseek_max_retries} attempts: {last_error}"
|
| 833 |
)
|
| 834 |
|
|
|
|
| 844 |
for attempt in range(2):
|
| 845 |
try:
|
| 846 |
logging.info("📄 [本地解析] 正在榨取用户上传的核心文献...")
|
| 847 |
+
response = self.call_deepseek(
|
| 848 |
+
sys_prompt,
|
| 849 |
+
user_prompt,
|
| 850 |
+
temp=0.1,
|
| 851 |
+
model_role="reasoning",
|
| 852 |
+
thinking=True,
|
| 853 |
+
allow_fallback=False,
|
| 854 |
+
)
|
| 855 |
papers = self._extract_json_from_text(response)
|
| 856 |
if not papers:
|
| 857 |
raise ValueError("Invalid JSON")
|
|
|
|
| 906 |
"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])
|
| 907 |
return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)
|
| 908 |
|
| 909 |
+
def generate_anchors(
|
| 910 |
+
self,
|
| 911 |
+
topic,
|
| 912 |
+
keywords,
|
| 913 |
+
synthesis_result,
|
| 914 |
+
refs_text,
|
| 915 |
+
data_evidence="",
|
| 916 |
+
mode="amj",
|
| 917 |
+
):
|
| 918 |
+
sys_prompt = (
|
| 919 |
+
"You are a senior scholar conceptualizing a high-impact "
|
| 920 |
+
"empirical paper."
|
| 921 |
+
)
|
| 922 |
format_mandate = """\n\n[CRITICAL FORMAT MANDATE]
|
| 923 |
+
You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings before them:
|
| 924 |
---ABSTRACT---
|
| 925 |
(Write the comprehensive abstract here)
|
| 926 |
---CONCLUSION---
|
| 927 |
(Write the expected conclusion here)"""
|
| 928 |
+
evidence_block = (
|
| 929 |
+
f"\nResearch Mode: {mode}\n"
|
| 930 |
+
"The following evidence packet is the single source of truth "
|
| 931 |
+
"for setting, sample, data sources, method, findings, and all "
|
| 932 |
+
"numerical details. Do not invent or alter them.\n"
|
| 933 |
+
f"<RESEARCH_EVIDENCE>\n{data_evidence[:12000]}\n"
|
| 934 |
+
"</RESEARCH_EVIDENCE>\n"
|
| 935 |
+
if data_evidence
|
| 936 |
+
else ""
|
| 937 |
+
)
|
| 938 |
+
base_directive = APP_CONFIG.get(
|
| 939 |
+
"anchor_generation_directive",
|
| 940 |
+
"",
|
| 941 |
+
)
|
| 942 |
+
user_prompt = (
|
| 943 |
+
f"Topic: {topic}\nKeywords: {keywords}\n"
|
| 944 |
+
f"Literature Synthesis:\n{synthesis_result}\n"
|
| 945 |
+
f"Citation Context:\n{refs_text[:3000]}\n"
|
| 946 |
+
f"{evidence_block}{base_directive}{format_mandate}"
|
| 947 |
+
)
|
| 948 |
+
response = self.call_deepseek(
|
| 949 |
+
sys_prompt,
|
| 950 |
+
user_prompt,
|
| 951 |
+
max_tokens=8000,
|
| 952 |
+
temp=0.3,
|
| 953 |
+
model_role="reasoning",
|
| 954 |
+
thinking=True,
|
| 955 |
+
allow_fallback=False,
|
| 956 |
+
)
|
| 957 |
+
abstract_match = re.search(
|
| 958 |
+
r"-+\s*ABSTRACT\s*-+\s*(.*?)(?=\s*-+\s*CONCLUSION\s*-+|$)",
|
| 959 |
+
response,
|
| 960 |
+
re.DOTALL | re.IGNORECASE,
|
| 961 |
+
)
|
| 962 |
+
conclusion_match = re.search(
|
| 963 |
+
r"-+\s*CONCLUSION\s*-+\s*(.*?)$",
|
| 964 |
+
response,
|
| 965 |
+
re.DOTALL | re.IGNORECASE,
|
| 966 |
+
)
|
| 967 |
+
final_abstract = (
|
| 968 |
+
abstract_match.group(1).strip()
|
| 969 |
+
if abstract_match
|
| 970 |
+
else response.strip()
|
| 971 |
+
)
|
| 972 |
+
final_conclusion = (
|
| 973 |
+
conclusion_match.group(1).strip()
|
| 974 |
+
if conclusion_match
|
| 975 |
+
else ""
|
| 976 |
+
)
|
| 977 |
return final_abstract, final_conclusion
|
| 978 |
|
| 979 |
# ... 保留上面的 synthesize_literature 和 generate_anchors 函数不变 ...
|
|
|
|
| 985 |
user_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace(
|
| 986 |
"{topic}", topic).replace("{user_injection}", user_injection).replace(
|
| 987 |
"{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])
|
| 988 |
+
return self.stream_deepseek(
|
| 989 |
+
sys_prompt,
|
| 990 |
+
user_prompt,
|
| 991 |
+
model_role="reasoning",
|
| 992 |
+
thinking=True,
|
| 993 |
+
allow_fallback=False,
|
| 994 |
+
)
|
| 995 |
|
| 996 |
+
# Generate abstract and conclusion anchors from literature plus evidence.
|
| 997 |
+
def stream_generate_anchors(
|
| 998 |
+
self,
|
| 999 |
+
topic,
|
| 1000 |
+
keywords,
|
| 1001 |
+
synthesis_result,
|
| 1002 |
+
refs_text,
|
| 1003 |
+
data_evidence="",
|
| 1004 |
+
mode="amj",
|
| 1005 |
+
):
|
| 1006 |
+
sys_prompt = (
|
| 1007 |
+
"You are a senior scholar conceptualizing a high-impact "
|
| 1008 |
+
"empirical paper."
|
| 1009 |
+
)
|
| 1010 |
format_mandate = """\n\n[CRITICAL FORMAT MANDATE]
|
| 1011 |
+
You MUST output your response EXACTLY using the following two delimiters. Do not add Markdown headings before them:
|
| 1012 |
---ABSTRACT---
|
| 1013 |
(Write the comprehensive abstract here)
|
| 1014 |
---CONCLUSION---
|
| 1015 |
(Write the expected conclusion here)"""
|
| 1016 |
+
evidence_block = (
|
| 1017 |
+
f"\nResearch Mode: {mode}\n"
|
| 1018 |
+
"The following evidence packet is the single source of truth "
|
| 1019 |
+
"for setting, sample, data sources, method, findings, and all "
|
| 1020 |
+
"numerical details. Do not invent or alter them.\n"
|
| 1021 |
+
f"<RESEARCH_EVIDENCE>\n{data_evidence[:12000]}\n"
|
| 1022 |
+
"</RESEARCH_EVIDENCE>\n"
|
| 1023 |
+
if data_evidence
|
| 1024 |
+
else ""
|
| 1025 |
+
)
|
| 1026 |
+
base_directive = APP_CONFIG.get(
|
| 1027 |
+
"anchor_generation_directive",
|
| 1028 |
+
"",
|
| 1029 |
+
)
|
| 1030 |
+
user_prompt = (
|
| 1031 |
+
f"Topic: {topic}\nKeywords: {keywords}\n"
|
| 1032 |
+
f"Literature Synthesis:\n{synthesis_result}\n"
|
| 1033 |
+
f"Citation Context:\n{refs_text[:3000]}\n"
|
| 1034 |
+
f"{evidence_block}{base_directive}{format_mandate}"
|
| 1035 |
+
)
|
| 1036 |
+
return self.stream_deepseek(
|
| 1037 |
+
sys_prompt,
|
| 1038 |
+
user_prompt,
|
| 1039 |
+
max_tokens=8000,
|
| 1040 |
+
model_role="reasoning",
|
| 1041 |
+
thinking=True,
|
| 1042 |
+
allow_fallback=False,
|
| 1043 |
+
)
|
| 1044 |
|
| 1045 |
# =====================================================================
|
| 1046 |
# [核心架构升级] 双轨制大纲路由,取代自由生成的结构断层风险
|
|
|
|
| 1051 |
|
| 1052 |
sys_prompt = "You are a senior academic editor. Polish the provided section titles to be more professional but DO NOT change the structure."
|
| 1053 |
structure_str = " || ".join([s["section"] for s in sections])
|
| 1054 |
+
response = self.call_deepseek(sys_prompt, f"Topic: {topic}. Structure: {structure_str}. Output refined titles only, separated by ' || '.", model_role="fast")
|
| 1055 |
|
| 1056 |
refined_titles = [t.strip() for t in response.split("||")]
|
| 1057 |
|
|
|
|
| 1075 |
sec_title = sec.get("section", "")
|
| 1076 |
if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result", "finding", "setting"]):
|
| 1077 |
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."
|
| 1078 |
+
query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2, model_role="fast").strip(' "\'')
|
| 1079 |
if query:
|
| 1080 |
queries_to_fetch.add(query)
|
| 1081 |
|
|
|
|
| 1114 |
Return ONLY a valid JSON array of strings."""
|
| 1115 |
user_prompt = f"Topic: {topic}\nKeywords: {keywords}"
|
| 1116 |
for attempt in range(3):
|
| 1117 |
+
queries = self._extract_json_from_text(self.call_deepseek(
|
| 1118 |
+
sys_prompt,
|
| 1119 |
+
user_prompt,
|
| 1120 |
+
temp=0.1 + attempt * 0.1,
|
| 1121 |
+
model_role="fast",
|
| 1122 |
+
))
|
| 1123 |
if queries and isinstance(queries, list) and len(queries) > 0:
|
| 1124 |
final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]
|
| 1125 |
if final_queries:
|
|
|
|
| 1275 |
3. Output simple, space-separated keyword combinations under 5 terms.
|
| 1276 |
Return ONLY a JSON array of strings."""
|
| 1277 |
user_prompt = f"Topic: {topic}\nKeywords: {keywords}\nUsed Queries: {list(all_used_terms)}\nGenerate 3 NEW, BROADER English search queries."
|
| 1278 |
+
response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5, model_role="fast")
|
| 1279 |
queries = self._extract_json_from_text(response)
|
| 1280 |
if isinstance(queries, list):
|
| 1281 |
search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]
|
core/qualitative_engine.py
CHANGED
|
@@ -1,62 +1,206 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
| 3 |
import logging
|
| 4 |
import re
|
|
|
|
| 5 |
import streamlit as st
|
| 6 |
|
|
|
|
| 7 |
class QualitativeEngine:
|
| 8 |
def __init__(self, agent):
|
| 9 |
self.agent = agent
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
if raw_interviews and len(raw_interviews) > 100:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
else:
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
data = self.agent._extract_json_from_text(response)
|
| 39 |
-
|
| 40 |
-
if not data:
|
| 41 |
-
logging.error("
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
def get_qualitative_engine(agent):
|
| 62 |
-
return QualitativeEngine(agent)
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Qualitative evidence preparation for SmartPaper's ASQ track."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
import logging
|
| 7 |
import re
|
| 8 |
+
|
| 9 |
import streamlit as st
|
| 10 |
|
| 11 |
+
|
| 12 |
class QualitativeEngine:
|
| 13 |
def __init__(self, agent):
|
| 14 |
self.agent = agent
|
| 15 |
|
| 16 |
+
@staticmethod
|
| 17 |
+
def _clean_cell(value, default="Not specified"):
|
| 18 |
+
cleaned = str(value or default).replace("\n", " ").strip()
|
| 19 |
+
return cleaned or default
|
| 20 |
+
|
| 21 |
+
def _build_request(self, topic, keywords, raw_interviews):
|
| 22 |
+
schema = """Return ONLY one valid JSON object with this schema:
|
| 23 |
+
{
|
| 24 |
+
"study_facts": {
|
| 25 |
+
"research_setting": "string",
|
| 26 |
+
"data_sources": ["string"],
|
| 27 |
+
"participant_count": integer or null,
|
| 28 |
+
"interview_count": integer or null,
|
| 29 |
+
"analysis_method": "string"
|
| 30 |
+
},
|
| 31 |
+
"evidence": [
|
| 32 |
+
{"theme": "2nd-order theme", "concept": "1st-order concept", "quote": "verbatim quote"}
|
| 33 |
+
]
|
| 34 |
+
}
|
| 35 |
+
"""
|
| 36 |
if raw_interviews and len(raw_interviews) > 100:
|
| 37 |
+
return f"""Topic: {topic}
|
| 38 |
+
Keywords: {keywords}
|
| 39 |
+
Analyze the supplied interview or field material.
|
| 40 |
+
|
| 41 |
+
Rules:
|
| 42 |
+
1. Use only setting, sample, source, and count information supported by the supplied material. Use null or "Not specified" when absent.
|
| 43 |
+
2. Extract up to 15 representative quotations verbatim; do not rewrite quotations.
|
| 44 |
+
3. Build a coherent Gioia-style coding structure.
|
| 45 |
+
4. The study_facts object will become the single source of truth for the entire manuscript.
|
| 46 |
+
|
| 47 |
+
{schema}
|
| 48 |
+
<QUALITATIVE_MATERIAL>
|
| 49 |
+
{raw_interviews[:30000]}
|
| 50 |
+
</QUALITATIVE_MATERIAL>
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
return f"""Topic: {topic}
|
| 54 |
+
Keywords: {keywords}
|
| 55 |
+
Construct one internally coherent qualitative study design and evidence packet for a complete ASQ-style manuscript when no interview material is supplied.
|
| 56 |
+
|
| 57 |
+
Rules:
|
| 58 |
+
1. Choose one research setting and keep it fixed.
|
| 59 |
+
2. Choose one participant count, interview count, data-source set, and analysis method; do not create conflicting counts.
|
| 60 |
+
3. Produce exactly 12 natural representative quotations organized into a Gioia-style coding structure.
|
| 61 |
+
4. The study_facts object will become the single source of truth for the entire manuscript.
|
| 62 |
+
5. Avoid decorative language, generic AI phrasing, and repetitive quotation patterns.
|
| 63 |
+
|
| 64 |
+
{schema}
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def resolve_qualitative_data(self, topic, keywords, raw_interviews=""):
|
| 68 |
+
has_user_data = bool(raw_interviews and len(raw_interviews) > 100)
|
| 69 |
+
prompt = self._build_request(topic, keywords, raw_interviews)
|
| 70 |
+
model_label = self.agent.model_for("reasoning")
|
| 71 |
+
|
| 72 |
+
if has_user_data:
|
| 73 |
+
status_label = (
|
| 74 |
+
f"🧠 正在使用 {model_label} 分析访谈材料并冻结研究事实…"
|
| 75 |
+
)
|
| 76 |
+
complete_label = "✅ 访谈材料、研究事实与编码结构已完成"
|
| 77 |
else:
|
| 78 |
+
status_label = (
|
| 79 |
+
f"🧠 正在使用 {model_label} 构建一致的定性研究证据包…"
|
| 80 |
+
)
|
| 81 |
+
complete_label = "✅ 定性研究事实与编码结构已完成"
|
| 82 |
+
|
| 83 |
+
with st.status(status_label, expanded=True) as status:
|
| 84 |
+
placeholder = st.empty()
|
| 85 |
+
response = placeholder.write_stream(
|
| 86 |
+
self.agent.stream_deepseek(
|
| 87 |
+
"You are a rigorous qualitative research analyst.",
|
| 88 |
+
prompt,
|
| 89 |
+
model_role="reasoning",
|
| 90 |
+
thinking=True,
|
| 91 |
+
allow_fallback=False,
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
status.update(
|
| 95 |
+
label=complete_label,
|
| 96 |
+
state="complete",
|
| 97 |
+
expanded=False,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
response = re.sub(
|
| 101 |
+
r"<think>.*?</think>",
|
| 102 |
+
"",
|
| 103 |
+
response,
|
| 104 |
+
flags=re.DOTALL,
|
| 105 |
+
).strip()
|
| 106 |
data = self.agent._extract_json_from_text(response)
|
| 107 |
+
|
| 108 |
+
if not isinstance(data, dict):
|
| 109 |
+
logging.error("Qualitative JSON parsing failed; using safe fallback.")
|
| 110 |
+
data = {
|
| 111 |
+
"study_facts": {
|
| 112 |
+
"research_setting": "Not specified",
|
| 113 |
+
"data_sources": ["Interview or field material"],
|
| 114 |
+
"participant_count": None,
|
| 115 |
+
"interview_count": None,
|
| 116 |
+
"analysis_method": "Gioia-style inductive coding",
|
| 117 |
+
},
|
| 118 |
+
"evidence": [
|
| 119 |
+
{
|
| 120 |
+
"theme": "Sensemaking",
|
| 121 |
+
"concept": "Initial uncertainty",
|
| 122 |
+
"quote": (
|
| 123 |
+
"We did not yet have a shared understanding "
|
| 124 |
+
"of how to respond."
|
| 125 |
+
),
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
facts = data.get("study_facts") or {}
|
| 131 |
+
evidence = data.get("evidence") or data.get("quotes") or []
|
| 132 |
+
if not isinstance(evidence, list):
|
| 133 |
+
evidence = []
|
| 134 |
+
|
| 135 |
+
data_sources = facts.get("data_sources") or ["Not specified"]
|
| 136 |
+
if not isinstance(data_sources, list):
|
| 137 |
+
data_sources = [data_sources]
|
| 138 |
+
|
| 139 |
+
setting = self._clean_cell(facts.get("research_setting"))
|
| 140 |
+
sources = ", ".join(self._clean_cell(item) for item in data_sources)
|
| 141 |
+
participants = facts.get("participant_count")
|
| 142 |
+
interviews = facts.get("interview_count")
|
| 143 |
+
method = self._clean_cell(
|
| 144 |
+
facts.get("analysis_method"),
|
| 145 |
+
"Gioia-style inductive coding",
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
md = (
|
| 149 |
+
"### Qualitative Study Design Summary\n"
|
| 150 |
+
"| Field | Frozen value |\n"
|
| 151 |
+
"| :--- | :--- |\n"
|
| 152 |
+
f"| Research setting | {setting} |\n"
|
| 153 |
+
f"| Data sources | {sources} |\n"
|
| 154 |
+
f"| Participants | {participants if participants is not None else 'Not specified'} |\n"
|
| 155 |
+
f"| Interviews | {interviews if interviews is not None else 'Not specified'} |\n"
|
| 156 |
+
f"| Analysis method | {method} |\n\n"
|
| 157 |
+
"[CONSISTENCY MANDATE]\n"
|
| 158 |
+
"Use the study-design summary above as the single source of truth. "
|
| 159 |
+
"Do not change the setting, sample, interview count, data sources, "
|
| 160 |
+
"or analysis method in any section.\n\n"
|
| 161 |
+
"### Table: Qualitative Coding Structure (Data Evidence)\n"
|
| 162 |
+
"| 2nd-order Theme | 1st-order Concept | Representative Quote |\n"
|
| 163 |
+
"| :--- | :--- | :--- |\n"
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
clean_evidence = []
|
| 167 |
+
for index, item in enumerate(evidence[:15]):
|
| 168 |
+
if not isinstance(item, dict):
|
| 169 |
+
continue
|
| 170 |
+
quote = self._clean_cell(item.get("quote"), "").replace('"', "'")
|
| 171 |
+
concept = self._clean_cell(item.get("concept"), "Analysis")
|
| 172 |
+
theme = self._clean_cell(item.get("theme"), "Observation")
|
| 173 |
+
if not quote:
|
| 174 |
+
continue
|
| 175 |
+
tag = f"QUOTE-{index + 1:02d}"
|
| 176 |
+
md += f'| {theme} | {concept} | "{quote}" [{tag}] |\n'
|
| 177 |
+
clean_evidence.append(
|
| 178 |
+
{
|
| 179 |
+
"theme": theme,
|
| 180 |
+
"concept": concept,
|
| 181 |
+
"quote": quote,
|
| 182 |
+
"tag": tag,
|
| 183 |
+
}
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
metadata = {
|
| 187 |
+
"mode": "qualitative",
|
| 188 |
+
"source_type": (
|
| 189 |
+
"user_provided" if has_user_data else "system_generated"
|
| 190 |
+
),
|
| 191 |
+
"disclosure_required": not has_user_data,
|
| 192 |
+
"study_facts": {
|
| 193 |
+
"research_setting": setting,
|
| 194 |
+
"data_sources": data_sources,
|
| 195 |
+
"participant_count": participants,
|
| 196 |
+
"interview_count": interviews,
|
| 197 |
+
"analysis_method": method,
|
| 198 |
+
},
|
| 199 |
+
"evidence_count": len(clean_evidence),
|
| 200 |
+
}
|
| 201 |
+
status_message = "✅ 定性研究事实、摘要锚点输入和Gioia编码证据已准备完成。"
|
| 202 |
+
return md, status_message, metadata
|
| 203 |
+
|
| 204 |
|
| 205 |
def get_qualitative_engine(agent):
|
| 206 |
+
return QualitativeEngine(agent)
|
core/quantitative_engine.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Quantitative data preparation for SmartPaper's AMJ track."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
from i18n import tr
|
| 10 |
+
from utils.file_parser import extract_data_from_files
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class QuantitativeEngine:
|
| 14 |
+
"""Keep quantitative preparation isolated from the Streamlit UI."""
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
def generate_psd_corr_matrix(n_constructs, max_corr=0.5):
|
| 18 |
+
if n_constructs == 1:
|
| 19 |
+
return np.array([[1.0]])
|
| 20 |
+
base_corr = np.random.uniform(0.2, max_corr - 0.1)
|
| 21 |
+
matrix = np.random.uniform(
|
| 22 |
+
base_corr - 0.1,
|
| 23 |
+
base_corr + 0.1,
|
| 24 |
+
(n_constructs, n_constructs),
|
| 25 |
+
)
|
| 26 |
+
matrix = (matrix + matrix.T) / 2
|
| 27 |
+
np.fill_diagonal(matrix, 1.0)
|
| 28 |
+
min_eig = np.min(np.linalg.eigvals(matrix))
|
| 29 |
+
if min_eig < 0:
|
| 30 |
+
matrix -= (min_eig - 0.01) * np.eye(n_constructs)
|
| 31 |
+
diagonal = np.sqrt(np.diag(matrix))
|
| 32 |
+
return matrix / np.outer(diagonal, diagonal)
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def calculate_validity_metrics(df, constructs_info, true_loadings):
|
| 36 |
+
metrics = []
|
| 37 |
+
for construct in constructs_info:
|
| 38 |
+
construct_name = construct["name"]
|
| 39 |
+
items = construct["items"]
|
| 40 |
+
sub_df = df[items]
|
| 41 |
+
var_total = sub_df.sum(axis=1).var(ddof=1)
|
| 42 |
+
sum_var = sub_df.var(ddof=1).sum()
|
| 43 |
+
n_items = len(items)
|
| 44 |
+
alpha = (
|
| 45 |
+
0.0
|
| 46 |
+
if var_total <= 0
|
| 47 |
+
else (n_items / (n_items - 1))
|
| 48 |
+
* (1 - sum_var / var_total)
|
| 49 |
+
)
|
| 50 |
+
loadings = np.array(true_loadings[construct_name])
|
| 51 |
+
sum_loadings_sq = np.sum(loadings) ** 2
|
| 52 |
+
sum_sq_loadings = np.sum(loadings**2)
|
| 53 |
+
sum_error = np.sum(1 - loadings**2)
|
| 54 |
+
cr = sum_loadings_sq / (sum_loadings_sq + sum_error)
|
| 55 |
+
ave = sum_sq_loadings / len(loadings)
|
| 56 |
+
metrics.append(
|
| 57 |
+
{
|
| 58 |
+
"Construct": construct_name,
|
| 59 |
+
"Items": n_items,
|
| 60 |
+
"Cronbach's α": round(alpha, 3),
|
| 61 |
+
"CR": round(cr, 3),
|
| 62 |
+
"AVE": round(ave, 3),
|
| 63 |
+
}
|
| 64 |
+
)
|
| 65 |
+
return pd.DataFrame(metrics)
|
| 66 |
+
|
| 67 |
+
def generate_empirical_data_robust(
|
| 68 |
+
self,
|
| 69 |
+
construct_names=None,
|
| 70 |
+
n=300,
|
| 71 |
+
scale_points=7,
|
| 72 |
+
):
|
| 73 |
+
if not construct_names or len(construct_names) < 2:
|
| 74 |
+
construct_names = [
|
| 75 |
+
"Independent_Var",
|
| 76 |
+
"Mediator_Var",
|
| 77 |
+
"Dependent_Var",
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
n_constructs = len(construct_names)
|
| 81 |
+
corr = self.generate_psd_corr_matrix(n_constructs, max_corr=0.55)
|
| 82 |
+
latent_scores = np.random.multivariate_normal(
|
| 83 |
+
mean=[0] * n_constructs,
|
| 84 |
+
cov=corr,
|
| 85 |
+
size=n,
|
| 86 |
+
)
|
| 87 |
+
data = {}
|
| 88 |
+
true_loadings = {}
|
| 89 |
+
constructs_info = []
|
| 90 |
+
target_mean = scale_points / 2.0 + 0.5
|
| 91 |
+
target_std = scale_points / 5.0
|
| 92 |
+
|
| 93 |
+
for index, construct_name in enumerate(construct_names):
|
| 94 |
+
true_score = latent_scores[:, index]
|
| 95 |
+
n_items = np.random.randint(3, 6)
|
| 96 |
+
loadings = np.random.uniform(0.72, 0.88, n_items)
|
| 97 |
+
true_loadings[construct_name] = loadings
|
| 98 |
+
item_names = []
|
| 99 |
+
for item_index, loading in enumerate(loadings):
|
| 100 |
+
error = np.random.normal(
|
| 101 |
+
0,
|
| 102 |
+
np.sqrt(1 - loading**2),
|
| 103 |
+
n,
|
| 104 |
+
)
|
| 105 |
+
item_score = loading * true_score + error
|
| 106 |
+
raw_scaled = item_score * target_std + target_mean
|
| 107 |
+
item_int = np.clip(
|
| 108 |
+
np.round(raw_scaled),
|
| 109 |
+
1,
|
| 110 |
+
scale_points,
|
| 111 |
+
).astype(int)
|
| 112 |
+
column_name = f"{construct_name}_{item_index + 1}"
|
| 113 |
+
data[column_name] = item_int
|
| 114 |
+
item_names.append(column_name)
|
| 115 |
+
constructs_info.append(
|
| 116 |
+
{"name": construct_name, "items": item_names}
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
df = pd.DataFrame(data)
|
| 120 |
+
validity_df = self.calculate_validity_metrics(
|
| 121 |
+
df,
|
| 122 |
+
constructs_info,
|
| 123 |
+
true_loadings,
|
| 124 |
+
)
|
| 125 |
+
mean_scores = pd.DataFrame(
|
| 126 |
+
{
|
| 127 |
+
construct["name"]: df[construct["items"]].mean(axis=1)
|
| 128 |
+
for construct in constructs_info
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
fl_matrix = mean_scores.corr().astype(object)
|
| 132 |
+
|
| 133 |
+
for _, row in validity_df.iterrows():
|
| 134 |
+
construct_name = row["Construct"]
|
| 135 |
+
sqrt_ave = np.sqrt(row["AVE"])
|
| 136 |
+
fl_matrix.loc[construct_name, construct_name] = (
|
| 137 |
+
f"({sqrt_ave:.3f})"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
for row_index in range(len(fl_matrix.columns)):
|
| 141 |
+
for column_index in range(row_index + 1, len(fl_matrix.columns)):
|
| 142 |
+
fl_matrix.iloc[row_index, column_index] = ""
|
| 143 |
+
|
| 144 |
+
desc_stats = mean_scores.mean().to_frame("Mean").join(
|
| 145 |
+
mean_scores.std().to_frame("SD")
|
| 146 |
+
)
|
| 147 |
+
return df, validity_df, desc_stats.join(fl_matrix)
|
| 148 |
+
|
| 149 |
+
def resolve_empirical_data(self, uploaded_files=None, language="zh"):
|
| 150 |
+
if uploaded_files:
|
| 151 |
+
user_md = extract_data_from_files(uploaded_files)
|
| 152 |
+
if user_md:
|
| 153 |
+
metadata = {
|
| 154 |
+
"mode": "quantitative",
|
| 155 |
+
"source_type": "user_provided",
|
| 156 |
+
"disclosure_required": False,
|
| 157 |
+
}
|
| 158 |
+
return None, user_md, tr(language, "actual_stats_parsed"), metadata
|
| 159 |
+
|
| 160 |
+
df, validity_df, fl_matrix_df = self.generate_empirical_data_robust()
|
| 161 |
+
generated_prompt = f"""### Table 1: Reliability and Convergent Validity
|
| 162 |
+
{validity_df.to_markdown(index=False)}
|
| 163 |
+
### Table 2: Descriptive Statistics and Discriminant Validity (Fornell-Larcker Criterion)
|
| 164 |
+
*Note: Diagonal elements in parentheses are the square roots of AVE.*
|
| 165 |
+
{fl_matrix_df.to_markdown()}
|
| 166 |
+
[STRICT EMPIRICAL INSTRUCTION]
|
| 167 |
+
1. ZERO HALLUCINATION: Report the exact metrics provided above.
|
| 168 |
+
2. VALIDITY DEFENSE: State convergent validity only when the displayed AVE and CR values support it.
|
| 169 |
+
3. DISCRIMINANT DEFENSE: State discriminant validity only when the displayed diagonal and correlation values support it.
|
| 170 |
+
4. CONSISTENCY: Use these tables as the single source of numerical truth throughout the paper.
|
| 171 |
+
"""
|
| 172 |
+
metadata = {
|
| 173 |
+
"mode": "quantitative",
|
| 174 |
+
"source_type": "system_generated",
|
| 175 |
+
"disclosure_required": True,
|
| 176 |
+
"sample_size": int(len(df)),
|
| 177 |
+
"scale_points": 7,
|
| 178 |
+
"method": (
|
| 179 |
+
"Positive-semidefinite latent correlation generation, "
|
| 180 |
+
"indicator loadings, discretization, and derived "
|
| 181 |
+
"reliability/validity summaries."
|
| 182 |
+
),
|
| 183 |
+
}
|
| 184 |
+
return (
|
| 185 |
+
df,
|
| 186 |
+
generated_prompt,
|
| 187 |
+
tr(language, "synthetic_stats_generated"),
|
| 188 |
+
metadata,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_quantitative_engine():
|
| 193 |
+
return QuantitativeEngine()
|