Spaces:
Sleeping
Sleeping
# integration_example.py | |
# 这个文件展示如何将你的MsPatient类集成到Streamlit应用中 | |
import streamlit as st | |
import json | |
import pandas as pd | |
from datetime import datetime | |
import time | |
from pathlib import Path | |
# 导入你的AnnaAgent类 - 请根据实际路径调整 | |
try: | |
from ms_patient import MsPatient # 假设你的类在anna_agent.py文件中 | |
ANNA_AGENT_AVAILABLE = True | |
except ImportError: | |
ANNA_AGENT_AVAILABLE = False | |
st.warning("⚠️ 未找到AnnaAgent类,使用模拟模式") | |
def load_dataset(uploaded_file): | |
""" | |
加载数据集文件 | |
支持JSON和JSONL格式 | |
""" | |
try: | |
if uploaded_file.name.endswith('.json'): | |
data = json.load(uploaded_file) | |
elif uploaded_file.name.endswith('.jsonl'): | |
data = [] | |
for line in uploaded_file: | |
data.append(json.loads(line.decode('utf-8'))) | |
else: | |
raise ValueError("不支持的文件格式") | |
return data | |
except Exception as e: | |
st.error(f"数据集加载失败: {str(e)}") | |
return None | |
def validate_patient_data(patient_data): | |
""" | |
验证患者数据格式是否正确 | |
""" | |
required_keys = ['id', 'portrait', 'report'] | |
for key in required_keys: | |
if key not in patient_data: | |
return False, f"缺少必需字段: {key}" | |
# 验证portrait字段 | |
portrait_required = ['age', 'gender', 'occupation', 'marital_status'] | |
for key in portrait_required: | |
if key not in patient_data['portrait']: | |
return False, f"portrait中缺少字段: {key}" | |
return True, "数据格式正确" | |
def initialize_patient_agent(patient_data, language="Chinese"): | |
""" | |
初始化患者智能体 | |
""" | |
try: | |
if not ANNA_AGENT_AVAILABLE: | |
return None, "AnnaAgent类不可用" | |
# 验证数据格式 | |
is_valid, message = validate_patient_data(patient_data) | |
if not is_valid: | |
return None, message | |
# 初始化智能体 | |
agent = MsPatient( | |
portrait=patient_data["portrait"], | |
report=patient_data["report"], | |
previous_conversations=patient_data.get("conversation", []), | |
language=language | |
) | |
return agent, "初始化成功" | |
except Exception as e: | |
return None, f"初始化失败: {str(e)}" | |
def simulate_response(user_input, patient_data=None): | |
""" | |
模拟智能体回复(当AnnaAgent不可用时使用) | |
""" | |
responses = [ | |
f"我理解您提到的'{user_input}'。这确实是一个需要深入探讨的话题。", | |
f"谢谢您的耐心。关于您说的'{user_input}',我想分享一下我的感受...", | |
f"您的话让我思考了很多。'{user_input}'这个观点很有意思。", | |
"我需要一些时间来消化您刚才说的话。这对我来说很重要。", | |
"我觉得我们之间的对话很有帮助。您能再详细说说吗?" | |
] | |
import random | |
return random.choice(responses) | |
def export_chat_history(messages, patient_id): | |
""" | |
导出聊天记录 | |
""" | |
chat_history = { | |
"patient_id": patient_id, | |
"timestamp": datetime.now().isoformat(), | |
"session_info": { | |
"total_messages": len(messages), | |
"counselor_messages": len([m for m in messages if m["role"] == "user"]), | |
"patient_responses": len([m for m in messages if m["role"] == "assistant"]) | |
}, | |
"messages": messages | |
} | |
return json.dumps(chat_history, ensure_ascii=False, indent=2) | |
def get_patient_summary(patient_data): | |
""" | |
生成患者信息摘要 | |
""" | |
if not patient_data or 'portrait' not in patient_data: | |
return "无患者信息" | |
portrait = patient_data['portrait'] | |
summary = f""" | |
**患者ID**: {patient_data.get('id', 'N/A')} | |
**基本信息**: {portrait.get('age', 'N/A')}岁 {portrait.get('gender', 'N/A')}性 | |
**职业**: {portrait.get('occupation', 'N/A')} | |
**婚姻状态**: {portrait.get('marital_status', 'N/A')} | |
**主要症状**: {portrait.get('symptom', 'N/A')} | |
""" | |
if 'report' in patient_data: | |
report = patient_data['report'] | |
summary += f""" | |
**主诉**: {report.get('chief_complaint', 'N/A')} | |
""" | |
return summary | |
# 示例配置文件内容 | |
CONFIG_EXAMPLE = { | |
"openai": { | |
"api_key": "your-api-key-here", | |
"base_url": "https://api.openai.com/v1", | |
"model_name": "gpt-3.5-turbo" | |
}, | |
"ui_settings": { | |
"language": "Chinese", # or "English" | |
"theme": "default", | |
"max_messages": 100 | |
}, | |
"patient_defaults": { | |
"language": "Chinese", | |
"enable_memory": True, | |
"enable_emotion_modulation": True | |
} | |
} | |
def save_config(config, path="config.json"): | |
"""保存配置文件""" | |
with open(path, 'w', encoding='utf-8') as f: | |
json.dump(config, f, ensure_ascii=False, indent=2) | |
def load_config(path="config.json"): | |
"""加载配置文件""" | |
try: | |
with open(path, 'r', encoding='utf-8') as f: | |
return json.load(f) | |
except FileNotFoundError: | |
return CONFIG_EXAMPLE | |
# 使用示例: | |
if __name__ == "__main__": | |
print("这是AnnaAgent Streamlit集成的辅助文件") | |
print("请运行:streamlit run your_streamlit_app.py") |