# -*- coding: utf-8 -*- import json import logging import re import streamlit as st class QualitativeEngine: def __init__(self, agent): self.agent = agent def 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'.*?', '', 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 = data else: 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_msg def get_qualitative_engine(agent): return QualitativeEngine(agent)