Skip to content

Repository files navigation

🧠 MindCare — AI 心理健康智能服务平台

多模型引擎驱动的心理学文本分类、情感分析、危机检测与内容推荐平台

Python Go Flask PyTorch


核心能力

能力 引擎 说明
🏷️ 文本分类 RF / FastText / BERT / DeepSeek 15 个心理学维度,4 套模型可选
💭 情感分析 Ekman 6 情感 + VAD 三维 词典匹配 + 加权合成,纯本地
🚨 危机检测 正则 + LLM 双层 50+ 条规则 + DeepSeek 语义兜底
🎯 内容推荐 文章库 + 用户画像 30 篇专业文章,分类匹配
🔗 知识图谱 词典 NER + 图推理 + LLM 51 节点 / 83 关系边
🔐 用户系统 JWT + SQLite/MySQL 四角色 RBAC,全端点鉴权

15 个分类维度:抑郁倾向 焦虑倾向 压力管理 睡眠障碍 亲密关系 原生家庭 自我成长 创伤心理 职场心理 青少年心理 老年心理 积极心理学 成瘾行为 饮食心理 危机干预


快速开始

环境要求

📖 详细说明见 环境安装指南

  • Anaconda / Miniconda(推荐)
  • Python 3.11 / Go 1.21+
  • SQLite(默认,零配置)

1. 一键安装环境

项目提供自动化脚本,根据硬件选择 CPU 或 CUDA 环境:

系统 CPU 环境 CUDA 环境 (NVIDIA GPU)
Windows 双击 setup_env.batsetup_env.bat cpu setup_env.bat cuda
Linux/macOS bash setup_env.shbash setup_env.sh cpu bash setup_env.sh cuda

脚本会自动完成:创建 conda 环境 → 安装 PyTorch → 安装 110+ 依赖包 → 验证安装。

手动安装
# 1. 创建 conda 环境
conda create -n PYTHON_NLP python=3.11 -y
conda activate PYTHON_NLP

# 2. 安装 PyTorch(二选一)
pip install torch torchvision torchaudio                              # CPU 版
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121  # CUDA 12.1 版

# 3. 安装公共依赖
pip install -r requirements_common.txt

2. 下载预训练模型(必需)

BERT 等模块依赖 bert-base-chinese,已随项目附带(04-bert/bert-base-chinese/)。如需重新下载:

pip install huggingface_hub
python -c "
from huggingface_hub import snapshot_download
snapshot_download('google-bert/bert-base-chinese', local_dir='04-bert/bert-base-chinese')
"

3. 启动

conda activate PYTHON_NLP    # 或 PYTHON_CUDA

# 终端1: Python AI 引擎 (端口 5000)
python backend/app.py

# 终端2: Go 网关 (端口 8080,面向浏览器)
cd goserver && go run .

浏览器打开 **http://localhost:8080/app**,默认账号 admin / admin123

训练模型(可选)

已有预训练模型时可直接使用;如需重新训练:

conda activate PYTHON_CUDA     # GPU 训练推荐

# 数据预处理
cd 02-rf && python preprocess_psychology.py    # RF 数据预处理
cd 03-fasttext && python preprocess_psychology.py  # FastText 数据预处理

# 模型训练
cd 02-rf && python train_psychology.py         # 随机森林 (TF-IDF + RF)
cd 03-fasttext && python train_psychology.py   # FastText (4变体自动对比)
cd 04-bert && python train_psychology.py       # BERT (推荐, 支持接续训练)

# 模型优化 (需先训练 BERT)
cd 05-bert-quantization && python quantize_psychology.py  # INT8 量化
cd 06-bert-distill && python distill_psychology.py        # 知识蒸馏 BERT→BiLSTM
cd 07-bert-pruning && python prune_psychology.py          # L1 非结构化剪枝

项目结构

MindCare/
├── goserver/                        # Go 网关 (HTTP 入口)
│   ├── main.go                      #   启动 + 优雅关闭
│   ├── handlers/router.go           #   路由 + Python 反向代理
│   └── middleware/                  #   JWT / 限流 / 日志
├── backend/                         # Python 后端
│   ├── app.py                       #   Flask API 主应用
│   ├── api/                         #   看板 / 咨询师工作台
│   ├── middleware/                  #   JWT / 限流 / 审计日志
│   ├── database/                    #   SQLite/MySQL / MongoDB
│   └── mbti/                        #   MBTI 测评
├── frontend/web/                    # 前端 (HTML + CSS + JS)
├── 01-data/                         # 训练数据 (15 分类, 180k 条)
├── 02-rf/                           # 随机森林基线模型
│   ├── train_psychology.py          #   训练脚本 (TF-IDF + RF)
│   ├── preprocess_psychology.py     #   数据预处理
│   ├── rf_predict_fun.py            #   单条预测 (API 封装)
│   └── rf_predict.py                #   批量验证集评估
├── 03-fasttext/                     # FastText 模型
│   ├── train_psychology.py          #   训练脚本 (4变体自动对比)
│   └── preprocess_psychology.py     #   数据预处理
├── 04-bert/                         # BERT 模型 (共享模块根目录)
│   ├── train_psychology.py          #   训练脚本 (支持接续训练)
│   ├── bert_classifier_model.py     #   BERT 分类模型定义
│   ├── dataloader_utils.py          #   数据加载器
│   ├── model2dev_utils.py           #   模型评估工具
│   └── bert_predict_fun.py          #   单条预测 (API 封装)
├── 05-LLM/                          # DeepSeek 大模型调用
├── 05-bert-quantization/            # 模型量化 (复用 04-bert 模块)
│   └── quantize_psychology.py
├── 06-bert-distill/                 # 知识蒸馏 BERT→BiLSTM (复用 04-bert 模块)
│   ├── distill_psychology.py        #   蒸馏训练脚本
│   └── bilstm_classifer_model.py    #   BiLSTM 学生模型
├── 07-bert-pruning/                 # 模型剪枝 (复用 04-bert 模块)
│   └── prune_psychology.py
├── 08-emotion-analysis/             # 情感分析 (词典 + VAD)
├── 09-crisis-detection/             # 危机检测 (正则 + LLM)
├── 10-psy-recommend/                # 内容推荐
├── 11-psy-knowledge-graph/          # 知识图谱
├── deployment/docker/               # Docker 部署配置
└── requirements.txt

代码架构

05/06/07 目录不重复拷贝共享代码,统一从 04-bert/ 导入:

共享模块 位置 使用者
Config 基类 04-bert/config.py 06/07 继承扩展,05 直接复用
BertClassifier 04-bert/bert_classifier_model.py 05/06/07
build_dataloader 04-bert/dataloader_utils.py 05/06/07
model2dev 04-bert/model2dev_utils.py 05/06/07
predict_fun 04-bert/bert_predict_fun.py backend

06/07 的 config.py 通过 importlib 直接从文件加载 04-bert 基类并追加专属参数(BiLSTM 超参 / 剪枝路径),避免循环导入。


API

Base URL: http://localhost:8080/api/v1

方法 路径 认证 说明
GET /health 健康检查
POST /user/login 登录
POST /user/register 注册
GET /user/profile 用户信息
POST /classify 文本分类 {text, model: rf|bert|llm|auto}
POST /emotion 情感分析 {text}
POST /crisis 危机检测 {text, use_llm}
POST /recommend 内容推荐 {category, top_n}
GET /recommend/detail/:id 文章详情
POST /kg/query 知识图谱 {query_type, text, use_llm}
# 登录获取 token
curl -X POST http://localhost:8080/api/v1/user/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}'

# 文本分类
curl -X POST http://localhost:8080/api/v1/classify \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"text":"最近做什么都提不起兴趣","model":"bert"}'

认证系统

角色 权限
admin 全部功能
therapist 分类/情感/危机/推荐/KG + 咨询师工作台
user 分类/情感/危机/推荐/KG

/health/user/login/user/register 外,所有接口需 Authorization: Bearer <token>。Token 有效期 24h。


数据库

数据库 用途 默认配置
SQLite 用户 + 会话 backend/database/mindcare.db,零配置
MySQL 生产环境替代 SQLite 修改 DB_BACKEND = 'mysql'
MongoDB 文章全文存储(可选,不可用时自动降级) backend/database/mongo_articles.py

部署

本地开发

# Python 后端
python backend/app.py                      # 端口 5000

# Go 网关
cd goserver && go build -o mindcare-server . && ./mindcare-server
# 访问 http://localhost:8080/app

环境变量:PORT(8080) PYTHON_BACKEND(http://127.0.0.1:5000) JWT_SECRET FRONTEND_DIR(../frontend/web)

Docker

模型通过 volume 挂载,不打包进镜像:

# 1. 确保宿主机已下载预训练模型
pip install huggingface_hub
python -c "from huggingface_hub import snapshot_download; snapshot_download('google-bert/bert-base-chinese', local_dir='04-bert/bert-base-chinese')"

# 2. 启动
docker-compose -f deployment/docker/docker-compose.yml up -d

生产环境

  • gunicorn -w 4 -b 127.0.0.1:5000 backend.app:app 替代 Flask 开发服务器
  • Nginx 前置处理 HTTPS + 静态资源
  • Redis 做限流缓存
  • MySQL 替代 SQLite

常见问题

模型加载报错

# 确认 bert-base-chinese 已下载到 04-bert/bert-base-chinese/
ls 04-bert/bert-base-chinese/config.json

中文输出乱码(Windows)

set PYTHONIOENCODING=utf-8

ModuleNotFoundError

pip install -r requirements_common.txt

如何添加新的心理学分类

  1. 编辑 01-data/class.txt 添加类别
  2. 更新 backend/common/psy_utils.py 中类别映射
  3. 更新 05-LLM/大模型生成提示词.txt
  4. 重新训练模型

许可证

仅供学习和研究使用。AI 评估结果不能替代专业医疗诊断。

⚠️ 如有自伤自杀风险,请立即拨打全国心理援助热线 400-161-9995

About

Application Case Integrating Machine Learning and Deep Learning: Psychological Diagnosis Based on Text Analysis

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages