「Django康养智慧中医」中医问诊系统:3.问诊模块
原创不易,请珍惜劳动成果,万分感谢!

「Django康养智慧中医」项目全部的文章汇总

内容简介

本章介绍Django搭建中医问诊系统问诊管理模块的内容

创建用户应用模块

进入文件根目录执行命令创建应用

cd TCM_Web
python manage.py startapp interrogation

将创建好的应用文件夹移动到目录的apps下即可

配置用户应用模块

在settings.py文件中修改

INSTALLED_APPS = [...# 添加文章应用'interrogation',

编写应用中的文件实现数据内容定义

不需要修改该的文件

  1. admin.py 这个我们使用xadmin代替的原有版本的admin,因此这个文件不需要修改该
  2. apps.py 应用的配置文件,不需要动
  3. test.py 测试执行脚本,不需要动

model.py

# coding:utf-8
__author__ = 'Mr.数据杨'
__explain__ = '定义interrogation应用的models,用于创建数据库表单'from django.db import models
from django.utils import timezone
from user.models import *

1.问诊答题数据定义

"""定义用户答题数据结果"""
class UserAnswer(models.Model):user_name = models.ForeignKey(InterrogationUser, related_name='UserAnswerUserName', on_delete=models.CASCADE,verbose_name='用户姓名', help_text="用户姓名")user_sex = models.ForeignKey(UserSexType, default=1, related_name='UserAnswerUserSex', on_delete=models.CASCADE,verbose_name='用户性别', help_text="用户性别")user_tel = models.CharField(max_length=20, verbose_name='电话', help_text="联系方式")user_answer = models.TextField(verbose_name='答题结果', help_text="答题结果")answer_date = models.DateTimeField(default=timezone.now, verbose_name='答题日期', help_text="用户答题日期")answer_time_num = models.IntegerField(verbose_name="更新时间戳", default="1")class Meta:ordering = ['id']verbose_name = '用户答题数据结果'verbose_name_plural = verbose_namedef __str__(self):return self.user_tel

2.问诊答题选项定义

"""定义问诊template页面答题下来选项表单内容"""
class ChooseAnswer(models.Model):SELVALUE = (  # 前面是展示在前端界面的内容,后面的'first'是真正存在数据库中的('从不 / 没有', '0'), ('很少 / 有点', '3'), ('有时 / 有些', '4'), ('总是 / 严重', '5'),)select_value = models.CharField(max_length=10, choices=SELVALUE)

3.男女问题编号对应分组

"""定义诊断症状问题男女分组"""
class DiagSymptomGroupSex(models.Model):symptom_code = models.CharField(max_length=20, verbose_name='问题编号', help_text="问诊问题编号")gender_code = models.ForeignKey(UserSexType, default=1, related_name='DiagSymptomGroupSexUserSex',on_delete=models.CASCADE,verbose_name='性别', help_text="性别")class Meta:ordering = ['id']verbose_name = '问诊男女问题对照明细'verbose_name_plural = verbose_namedef __str__(self):return self.symptom_code

4.问诊问题分组定义

"""定义诊断问题分组类别"""
class DiagSymptomGroup(models.Model):group_code = models.CharField(max_length=20, verbose_name='问题分组类别编号', help_text="问题分组类别编号")group_name = models.CharField(max_length=20, verbose_name='问题分组类别名称', help_text="问题分组类别名称")class Meta:ordering = ['id']verbose_name = '诊断问题分组类别'verbose_name_plural = verbose_namedef __str__(self):return self.group_name

5.问诊问题明细定义

"""定义问诊问题明细"""
class DiagSymptomData(models.Model):data_code = models.CharField(max_length=20, verbose_name='问题编号', help_text="问题编号")data_name = models.CharField(max_length=20, verbose_name='病症名称', help_text="病症名称")remark = models.CharField(max_length=50, blank=True, null=True, verbose_name='备注标记',help_text="备注标记")old_question = models.CharField(max_length=255, blank=True, null=True, verbose_name='专业版问题',help_text="问题内容专业版")group_code = models.ForeignKey(DiagSymptomGroup, related_name='DiagSymptomDataGroupCode',on_delete=models.CASCADE,verbose_name='问题分组编号', help_text="问题分组编号")new_question = models.CharField(max_length=255, blank=True, null=True, verbose_name='白话版问题',help_text="问题内容白话版")class Meta:ordering = ['id']verbose_name = '问诊问题明细'verbose_name_plural = verbose_namedef __str__(self):return self.data_name

6.中医证型定义

"""定义证型数据明细"""
class DiagSyndromeType(models.Model):type_name = models.CharField(max_length=50, verbose_name='症型名称', help_text="症型名称")type_alias_name = models.CharField(max_length=200, blank=True, null=True, verbose_name='症型别名',help_text="症型别名")matched_element = models.CharField(max_length=50, verbose_name='证素组成',help_text="证素组成")matched_element_count = models.IntegerField(verbose_name='证素数量', help_text="证素数量")auxiliary_element = models.CharField(max_length=50, blank=True, null=True,verbose_name='辅助证素', help_text="辅助证素")treat_methods = models.CharField(max_length=100, verbose_name='治疗方案', help_text="治疗方案")prescriptions = models.CharField( max_length=50, verbose_name='处方名称', help_text="处方名称")class Meta:ordering = ['id']verbose_name = '证型数据明细'verbose_name_plural = verbose_namedef __str__(self):return self.type_name

7.中医处方定义

"""定义中药处方数据明细"""
class PresFormulaInfo(models.Model):formula_name = models.CharField( max_length=20, verbose_name='处方名称', help_text="处方名称")formula_composition = models.TextField(blank=True, null=True, verbose_name='中药组成', help_text="中药组成")formula_usage = models.CharField(db_column='Usage', max_length=100, verbose_name='使用方法', help_text="使用方法")class Meta:ordering = ['id']verbose_name = '中药处方数据明细'verbose_name_plural = verbose_namedef __str__(self):return self.formula_name

8.人体体质类别定义

"""定义人体体质明细"""
class HumanBodyType(models.Model):body_name = models.CharField( max_length=20, verbose_name='体质名称', help_text="体质名称")body_principle = models.CharField(max_length=20, verbose_name='原理', help_text="原理")body_diet = models.CharField(max_length=20, verbose_name='饮食', help_text="饮食")body_mental = models.CharField( max_length=20, verbose_name='心里', help_text="心里")body_living = models.CharField(max_length=20, verbose_name='生活', help_text="生活'")body_drug = models.CharField(max_length=20, verbose_name='药品', help_text="药品")body_season = models.CharField(max_length=50, verbose_name='季节', help_text="季节")body_meridian = models.CharField(max_length=50, verbose_name='穴位', help_text="穴位")body_activity = models.CharField( max_length=250, verbose_name='活动', help_text="活动")class Meta:ordering = ['id']verbose_name = '人体体质明细'verbose_name_plural = verbose_namedef __str__(self):return self.body_name

9.证素证候对照明细定义

"""定义证素证候对照明细"""
class InquiryView(models.Model):gender_code = models.ForeignKey(UserSexType, related_name='InquiryViewGenderCode', on_delete=models.CASCADE,verbose_name='用户性别', help_text="用户性别")group_code = models.ForeignKey(DiagSymptomGroup, related_name='InquiryViewGroupCode', on_delete=models.CASCADE,verbose_name='用户性别', help_text="用户性别")content = models.TextField(db_column='Content', verbose_name='明细', help_text="明细")class Meta:ordering = ['id']verbose_name = '证素证候对照明细'verbose_name_plural = verbose_namedef __str__(self):return self.group_code

10.推荐水果定义


"""定义推荐水果明细"""
class RecommendFruit(models.Model):name = models.CharField(db_column='Name', max_length=50, verbose_name='水果名称', help_text="水果名称")location = models.CharField(db_column='Location', max_length=50, blank=True, null=True, verbose_name='归经',help_text="归经")nature = models.CharField(db_column='Nature', max_length=50, blank=True, null=True, verbose_name='证素性质',help_text="证素性质")pattern = models.CharField(db_column='Pattern', max_length=50, blank=True, null=True, verbose_name='证候表现',help_text="证候表现")disease = models.CharField(db_column='Disease', max_length=50, blank=True, null=True, verbose_name='症状表现',help_text="症状表现")remarks = models.CharField(db_column='Remarks', max_length=100, blank=True, null=True, verbose_name='备注',help_text="备注")class Meta:ordering = ['id']verbose_name = '推荐水果明细'verbose_name_plural = verbose_namedef __str__(self):return self.name

11.推荐五谷定义


"""定义推荐五谷明细"""
class RecommendGrain(models.Model):name = models.CharField(db_column='Name', max_length=50, verbose_name='五谷名称', help_text="五谷名称")treatment = models.CharField(db_column='Treatment', max_length=100, verbose_name='治疗', help_text="治疗")location = models.CharField(db_column='Location', max_length=50, blank=True, null=True, verbose_name='归经',help_text="归经")nature = models.CharField(db_column='Nature', max_length=50, blank=True, null=True, verbose_name='证素性质',help_text="证素性质")pattern = models.CharField(db_column='Pattern', max_length=50, blank=True, null=True, verbose_name='证候表现',help_text="证候表现")disease = models.CharField(db_column='Disease', max_length=50, blank=True, null=True, verbose_name='症状表现',help_text="症状表现")usage = models.CharField(db_column='Usage', max_length=100, blank=True, null=True, verbose_name='食用方法',help_text="食用方法")remarks = models.CharField(db_column='Remarks', max_length=100, blank=True, null=True, verbose_name='备注',help_text="备注")class Meta:ordering = ['id']verbose_name = '推荐五谷明细'verbose_name_plural = verbose_namedef __str__(self):return self.name

12.推荐茶饮定义

"""定义推荐茶饮明细"""
class RecommendTea(models.Model):name = models.CharField(db_column='Name', max_length=50, verbose_name='茶饮名称', help_text="茶饮名称")treatment = models.CharField(db_column='Treatment', max_length=100, verbose_name='功效', help_text="功效")gender = models.CharField(db_column='Gender', max_length=2, blank=True, null=True, verbose_name='适合性别',help_text="适合性别")location = models.CharField(db_column='Location', max_length=50, blank=True, null=True, verbose_name='归经',help_text="归经")nature = models.CharField(db_column='Nature', max_length=50, blank=True, null=True, verbose_name='证素性质',help_text="证素性质")pattern = models.CharField(db_column='Pattern', max_length=50, blank=True, null=True, verbose_name='证候表现',help_text="证候表现")disease = models.CharField(db_column='Disease', max_length=50, blank=True, null=True, verbose_name='症状表现',help_text="症状表现")composition = models.CharField(db_column='Composition', max_length=100, verbose_name='组成', help_text="组成")usage = models.CharField(db_column='Usage', max_length=100, verbose_name='食用方法', help_text="食用方法")remarks = models.CharField(db_column='Remarks', max_length=100, blank=True, null=True, verbose_name='备注',help_text="备注")class Meta:ordering = ['id']verbose_name = '推荐茶饮明细'verbose_name_plural = verbose_namedef __str__(self):return self.name

13. 推荐蔬菜定义

"""定义推荐蔬菜数据信息"""
class RecommendVegetable(models.Model):name = models.CharField(db_column='Name', max_length=50, verbose_name='蔬菜名称', help_text="蔬菜名称")location = models.CharField(db_column='Location', max_length=50, blank=True, null=True, verbose_name='归经',help_text="归经")nature = models.CharField(db_column='Nature', max_length=50, blank=True, null=True, verbose_name='证素性质',help_text="证素性质")pattern = models.CharField(db_column='Pattern', max_length=50, blank=True, null=True, verbose_name='证候表现',help_text="证候表现")disease = models.CharField(db_column='Disease', max_length=50, blank=True, null=True, verbose_name='症状表现',help_text="症状表现")remarks = models.CharField(db_column='Remarks', max_length=100, blank=True, null=True, verbose_name='备注',help_text="备注")class Meta:ordering = ['id']verbose_name = '推荐蔬菜明细'verbose_name_plural = verbose_namedef __str__(self):return self.name

adminx.py

# coding:utf-8
__author__ = 'Mr.数据杨'
__explain__ = '定义Interogation应用的Xadmin'import xadmin
from .models import *

1.用户答题数据的管理功能

"""Xadmin用户答题数据结果"""
class UserAnswerAdmin(object):list_display = ['user_name', 'user_sex', 'user_tel', 'answer_date']readonly_fields = ['user_name', 'user_sex', 'user_tel', 'user_answer', 'answer_date','answer_time_num']show_bookmarks = False
xadmin.site.register(UserAnswer, UserAnswerAdmin)

2.问诊男女问题明细对照管理

"""Xadmin问诊男女问题对照明细"""
class DiagSymptomGroupSexAdmin(object):list_display = ['symptom_code', 'gender_code']show_bookmarks = False
xadmin.site.register(DiagSymptomGroupSex, DiagSymptomGroupSexAdmin)

3.问诊问题分组管理

"""Xadmin问诊问题分组类别"""
class DiagSymptomGroupAdmin(object):list_display = ['group_code', 'group_name']show_bookmarks = False
xadmin.site.register(DiagSymptomGroup, DiagSymptomGroupAdmin)

4.问诊问题明细管理

"""Xadmin问诊问题明细"""
class DiagSymptomDataAdmin(object):list_display = ['group_code','data_code', 'data_name', 'new_question']show_bookmarks = False
xadmin.site.register(DiagSymptomData, DiagSymptomDataAdmin)

5.中医证型数据管理

"""Xadmin证型数据明细"""
class DiagSyndromeTypeAdmin(object):list_display = ['type_name', 'type_alias_name', 'matched_element', 'treat_methods', 'prescriptions']show_bookmarks = False
xadmin.site.register(DiagSyndromeType, DiagSyndromeTypeAdmin)

6.中医中药方剂管理

"""Xadmin中药处方明细"""
class PresFormulaInfoAdmin(object):list_display = ['formula_name', 'formula_composition', 'formula_usage']show_bookmarks = False
xadmin.site.register(PresFormulaInfo, PresFormulaInfoAdmin)

7.人体体质管理

"""Xadmin人体体质明细"""
class HumanBodyTypeAdmin(object):list_display = ['body_name', 'body_principle', 'body_diet']show_bookmarks = False
xadmin.site.register(HumanBodyType, HumanBodyTypeAdmin)

8.证素证候对照管理

"""Xadmin证素证候对照明细"""
class InquiryViewAdmin(object):list_display = ['gender_code', 'group_code', 'content']show_bookmarks = False
xadmin.site.register(InquiryView, InquiryViewAdmin)

9.水果推荐管理

"""Xadmin推荐水果明细"""
class RecommendFruitAdmin(object):list_display = ['name', 'location', 'remarks']show_bookmarks = False
xadmin.site.register(RecommendFruit, RecommendFruitAdmin)

10.五谷推荐管理

"""Xadmin推荐五谷明细"""
class RecommendrainAdmin(object):list_display = ['name', 'location', 'remarks']show_bookmarks = False
xadmin.site.register(RecommendGrain, RecommendrainAdmin)

11.茶饮推荐管理

"""Xadmin推荐茶饮明细"""
class RecommendTeaAdmin(object):list_display = ['name', 'location', 'remarks']show_bookmarks = False
xadmin.site.register(RecommendTea, RecommendTeaAdmin)

12.蔬菜推荐管理

"""Xadmin推荐蔬菜明细"""
class RecommendVegetableAdmin(object):list_display = ['name', 'location', 'remarks']show_bookmarks = False
xadmin.site.register(RecommendVegetable, RecommendVegetableAdmin)

13.执行命令行生成数据库表单

以后每次改动model文件都需要执行一次

python manage.py makemigrations  # 迁移到我们数据库
python manage.py migrate # 同步到数据库

14.查看mysql数据仓库会生成对应的表单

form.py

这个地方内容要和models.py里定义的内容一致

#coding:utf-8
__author__ = 'Mr.数据杨'
__explain__ = 'form表单'from django import forms"""定义问诊template页面答题下来选项表单内容"""
class SelectTestForm(forms.Form):SELVALUE = (('从不 / 没有', '0'),  # 前面是展示在前端界面的内容,后面的'first'是真正存在数据库中的('很少 / 有点', '3'),('有时 / 有些', '4'),('总是 / 严重', '5'),)sel_value0202 = forms.CharField(max_length=10,widget=forms.widgets.Select(choices=SELVALUE))sel_value1030 = forms.CharField(max_length=10, widget=forms.widgets.Select(choices=SELVALUE))

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
from django.views.generic.base import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decoratorimport operator
import re
import os
import time
import pandas as pdfrom .models import *
from .forms import SelectTestForm
from user.models import *
from .models import UserAnswer# from sklearn.externals import joblib
import joblib
from keras.models import load_model
from keras.backend import clear_sessionfrom pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.commons.utils import JsCode# Create your views here.BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MODEL_ROOT = os.path.join(BASE_DIR, 'interrogation\\models\\')
STATIC_ROOT = os.path.join(BASE_DIR, 'media\\result_pic\\').replace("\\apps", "")

1.用户基础信息调取和提交

"""用户基本信息调取,用户核对每次问诊前用户信息"""
@method_decorator(login_required, name='dispatch')
class UserInfo(View):def get(self, request):user_info = InterrogationUser.objects.filter(user_name=request.user)[0]user_name = user_info.user_nameuser_blood = user_info.user_blooduser_marital = user_info.user_maritaluser_birthday = user_info.user_birthdayuser_info_num = UserAnswer.objects.filter(user_tel=request.user.user_tel).count()return render(request, 'user/userinfo.html', {'user_name': user_name,# 'user_sex': user_sex,'user_birthday': user_birthday,'user_blood': user_blood,'user_marital': user_marital,'user_info_num': user_info_num})def post(self, request):user = request.useruser_name = request.POST.get('user_name')user_birthday = request.POST.get('user_birthday')blood_type = {"0": "未知", "1": "A", "2": "B", "3": "O", "4": "AB"}user_blood = list(blood_type.keys())[list(blood_type.values()).index(request.POST.get('user_blood'))]marital_type = {"1": "未婚", "2": "已婚", "3": "丧偶", "4": "离婚", "9": "其他"}user_marital = list(marital_type.keys())[list(marital_type.values()).index(request.POST.get('user_marital'))]InterrogationUser.objects.filter(user_name=user).update(user_name=user_name,user_birthday=user_birthday,user_blood=user_blood,user_marital=user_marital,)return HttpResponseRedirect(reverse("thequestions"))  # 跳转到首页 user request会被带回到首页

2.问诊问题列表获取和答案提交

"""问诊答题列表(GET)、问诊答题结果提交(POST)"""
@method_decorator(login_required, name='dispatch')
class TheQuestions(View):def get(self, request):group_data = DiagSymptomGroup.objects.all()[1:19]questions_list = DiagSymptomGroupSex.objects.filter(gender_code=request.user.user_sex)questions_list = [i.symptom_code for i in questions_list]question_data = DiagSymptomData.objects.filter(data_code__in=questions_list)select_form = SelectTestForm()return render(request, 'interrogation/thequestions.html',{'select_form': select_form,  # 这里需要把form传到前端,前端就可以借助这个form填充界面'group_data': group_data,'question_data': question_data,})def post(self, request):select_form = SelectTestForm(request.POST)men_list = DiagSymptomGroupSex.objects.filter(gender_code=1)men_list = [i.symptom_code for i in men_list]women_list = DiagSymptomGroupSex.objects.filter(gender_code=2)women_list = [i.symptom_code for i in women_list]if select_form.is_valid():if request.user.user_sex.type_id == 1:# 男性result = []for num in men_list:get_value = request.POST.get('sel_value{}'.format(num), "")  # 这里可以取到下拉表单中的值result.append((num, get_value))UserAnswer_data = UserAnswer()UserAnswer_data.user_tel = request.user.user_telUserAnswer_data.user_answer = str(result)UserAnswer_data.answer_date = timezone.now()UserAnswer_data.answer_time_num = int(time.time())UserAnswer_data.user_name_id = request.user.idUserAnswer_data.user_sex_id = request.user.user_sex.type_idUserAnswer_data.save()if request.user.user_sex.type_id == 2: # 女性result = []for num in women_list:get_value = request.POST.get('sel_value{}'.format(num), "")  # 这里可以取到下拉表单中的值result.append((num, get_value))UserAnswer_data = UserAnswer()UserAnswer_data.user_tel = request.user.user_telUserAnswer_data.user_answer = str(result)UserAnswer_data.answer_date = timezone.now()UserAnswer_data.answer_time_num = int(time.time())UserAnswer_data.user_name_id = request.user.idUserAnswer_data.user_sex_id = request.user.user_sex.type_idUserAnswer_data.save()return HttpResponseRedirect(reverse("interrogation_result_info"))

3.问诊后台主页面

"""问诊结果主页信息(答题记录和最后一次状态描述)"""
class InterrogationResultInfo(View):def get(self, request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]name = data.user_nameage = 2020 - int(data.user_birthday[:4])sex_ = "男" if data.user_sex.type_id == 1 else "女"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)# 构建预测病症结果data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_one = UserAnswer.objects.filter(user_tel=data.user_tel).order_by('-id')[:1][0]result = pd.DataFrame(eval(answer_one.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabels = InquiryView.objects.values("content")# 统计全部的标签内容strs = ""for i in range(len(labels)):s = "".join(re.findall('AttributeList="(.*?)"/', labels[i]["content"]))strs = strs + slabel_list = list(set(strs.split(",")))label_list.remove("")clear_session()model = load_model(MODEL_ROOT + 'final_result\\{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:20]name_list = [(i[0]) for i in sort_list]  # 体质名称men_p = re.compile('月经经闭月经深红经间期出血带下色白气腥阴道出血如崩月经推迟月经紫黯月经量少月经量多')women_p = re.compile('遗精')if sex == "men":name_list = ",".join([x for x in name_list if not men_p.findall(x)])if sex == "women":name_list = ",".join([x for x in name_list if not women_p.findall(x)])return render(request, 'interrogation/interrogation_result_info.html', {  # 这里'sel_test.html'使我们的前端页面'age': age,  # 这里需要把form传到前端,前端就可以借助这个form填充界面'name': name,'sex_': sex_,'answer_list': answer_list,'name_list': name_list})

4.回归辩证数据计算和图表生成

"""回归辩证数据计算和图表生成"""
def HuiGuiBianZheng(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.T"""八纲辨证"""type_list = ["yinxu", "yangxu", "yangkang", "yangfu", "biao", "banbiaobanli", "wangyang", "wangyin"]c_name = ["阴虚", "阳虚", "阳亢", "阳浮", "表", "半表半里", "亡阳", "亡阴"]result_list = []for type_ in type_list:lr = joblib.load(MODEL_ROOT + 'bagang\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_name).add_yaxis("八纲辨证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "bagang.html"))"""病因辩证"""type_list = ["feng", "han", "shu", "shi", "zao", "huore"]c_name = ["风", "寒", "暑", "湿", "燥", "火热"]result_list = []for type_ in type_list:lr = joblib.load(MODEL_ROOT + 'bingyin\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_name).add_yaxis("病因辩证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "bingyin.html"))"""津液辩证"""type_list = ["tan", "yin", "shuiting", "jinkui", "jingkui", "nong"]c_name = ["痰", "饮", "水停", "津亏", "精亏", "脓"]result_list = []for type_ in type_list:lr = joblib.load(MODEL_ROOT + 'jinye\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_name).add_yaxis("津液辩证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "jinye.html"))"""气血辩证"""type_list = ["qixu", "qizhi", "qixian", "qibugu", "qini", "qibi", "qituo", "xuexu", "xueyu", "xuere", "xuehan","dongxue"]c_name = ["气虚", "气滞", "气陷", "气不固", "气逆", "气闭", "气脱", "血虚", "血瘀", "血热", "血寒", "动血"]result_list = []for type_ in type_list:lr = joblib.load(MODEL_ROOT + 'qixue\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_name).add_yaxis("气血辩证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "qixue.html"))"""脏腑辩证"""type_list = ["gan", "dan", "fei", "dachang", "pi", "wei", "shen", "pangguang", "xin", "xiaochang"]c_name = ["肝", "胆", "肺", "大肠", "脾", "胃", "肾", "膀胱", "心", "小肠"]result_list = []for type_ in type_list:lr = joblib.load(MODEL_ROOT + 'zangfu\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_name).add_yaxis("脏腑辩证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "zangfu.html"))"""其他辩证"""type_dict = {"men": ["dongfeng", "shaofu", "xinshen", "du", "jingu", "jingshi", "jingluo", "jifu", "xiongge", "chongji","shiji"],"women": ["dongfeng", "shaofu", "xinshen", "du", "jingu", "jingluo", "jifu", "baogong", "xiongge","chongji", "shiji"]}c_dict = {"men": ["动风", "少腹", "心神", "毒", "筋骨", "精室", "经络", "肌肤", "胸膈", "虫积", "食积"],"women": ["动风", "少腹", "心神", "毒", "筋骨", "经络", "肌肤", "胞宫", "胸膈", "虫积", "食积"]}result_list = []for type_ in type_dict[sex]:lr = joblib.load(MODEL_ROOT + 'qita\\{}_{}_reg.pkl'.format(sex, type_))result_list.append(round(lr.predict(result)[0], 2))c = (Bar(opts.InitOpts(width="650px", height="300px")).add_xaxis(c_dict[sex]).add_yaxis("其他辩证", result_list, category_gap="60%").set_series_opts(itemstyle_opts={"normal": {"color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{offset: 0,color: 'rgba(0, 244, 255, 1)'}, {offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)"""),"barBorderRadius": [30, 30, 30, 30],"shadowColor": "rgb(0, 160, 221)", }}).render(STATIC_ROOT + "qita.html"))return render(request, 'interrogation/interrogation_result_huiguibianzheng.html',{'answer_list': answer_list, "result": "1"})return render(request, 'interrogation/interrogation_result_huiguibianzheng.html', {'answer_list': answer_list})

5.证型数据计算和方剂推荐

"""证型分类计算、处方推荐计算"""
def ZhengXingFenLei(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = DiagSyndromeType.objects.values("type_name")label_list = [i["type_name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'zhengxing\\{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:10]# sort_list = [ (i[0],str(round(i[1],2))+"%") for i in sort_list] # 证型排序后的结果name_list = [(i[0]) for i in sort_list]  # 证候名称name_data = DiagSyndromeType.objects.filter(type_name__in=name_list).values('type_name', 'treat_methods','prescriptions','matched_element')  # 获取对应证型名称的数据# 切分替换数据 返回模板需要的结果name_df = pd.DataFrame(list(name_data))def add_data(text):data = text.split(",")return [PresFormulaInfo.objects.filter(formula_name=i).values('formula_name', 'formula_composition', 'formula_usage') for i indata]name_df["prescriptions"] = name_df.prescriptions.apply(add_data)print(name_df["prescriptions"])for i in range(len(name_df)):temp = {"name": name_df["type_name"][i], "treatmethods": name_df["treat_methods"][i],"matchedelements": name_df["matched_element"][i], "prescriptions": name_df["prescriptions"][i]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_zhengxingfenlei.html',{'answer_list': answer_list, 'name_data_list': name_data_list})

6.体质分类计算

"""体质分类计算"""
def TiZhiFenLei(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = HumanBodyType.objects.values("body_name")label_list = [i["body_name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'tizhi\\{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:3]sort_dict = {}for i in sort_list:  # 体质百分比字典sort_dict[i[0]] = str(round(i[1], 2)) + "%"name_list = [(i[0]) for i in sort_list]  # 体质名称name_data = HumanBodyType.objects.filter(body_name__in=name_list).values('body_name', 'body_principle', 'body_diet','body_mental', 'body_living', 'body_drug','body_season', 'body_meridian','body_activity')  # 获取体质称的数据name_df = pd.DataFrame(list(name_data))for i in range(len(name_df)):temp = {"name": name_df["body_name"][i], "principle": name_df["body_principle"][i],"diet": name_df["body_diet"][i], "mental": name_df["body_mental"][i],"living": name_df["body_living"][i], "drug": name_df["body_drug"][i],"season": name_df["body_season"][i], "meridian": name_df["body_meridian"][i],"activity": name_df["body_activity"][i], "num": sort_dict[name_df["body_name"][i]]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_tizhifenlei.html',{'answer_list': answer_list, 'name_data_list': name_data_list})

7.水果推荐计算

"""养生水果推荐计算"""
def YangShengShuiGuo(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = RecommendFruit.objects.values("name")label_list = [i["name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'tiaoli\\fruit_{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:5]sort_dict = {}for i in sort_list:  # 体质百分比字典sort_dict[i[0]] = str(round(i[1], 2)) + "%"name_list = [(i[0]) for i in sort_list]  # 体质名称name_data = RecommendFruit.objects.filter(name__in=name_list).values('name', 'remarks')  # 获取体质称的数据name_df = pd.DataFrame(list(name_data))for i in range(len(name_df)):temp = {"name": name_df["name"][i], "remakrs": name_df["remarks"][i], "num": sort_dict[name_df["name"][i]]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_yangshengshuiguo.html',{'answer_list': answer_list, 'name_data_list': name_data_list})

8.五谷推荐计算

"""养生五谷杂粮推荐计算"""
def YangShengLiangShi(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = RecommendGrain.objects.values("name")label_list = [i["name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'tiaoli\\grain_{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:5]sort_dict = {}for i in sort_list:  # 体质百分比字典sort_dict[i[0]] = str(round(i[1], 2)) + "%"name_list = [(i[0]) for i in sort_list]  # 体质名称name_data = RecommendGrain.objects.filter(name__in=name_list).values('name', 'treatment', 'usage','remarks')  # 获取体质称的数据name_df = pd.DataFrame(list(name_data))for i in range(len(name_df)):temp = {"name": name_df["name"][i], "treatment": name_df["treatment"][i],"usage": name_df["usage"][i], "remarks": name_df["remarks"][i],"num": sort_dict[name_df["name"][i]]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_yangshengliangshi.html',{'answer_list': answer_list, 'name_data_list': name_data_list})

9.茶饮推荐计算

"""养生茶饮推荐计算"""
def YangShengChaYin(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = RecommendTea.objects.values("name")label_list = [i["name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'tiaoli\\tea_{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:5]sort_dict = {}for i in sort_list:  # 体质百分比字典sort_dict[i[0]] = str(round(i[1], 2)) + "%"name_list = [(i[0]) for i in sort_list]  # 体质名称name_data = RecommendTea.objects.filter(name__in=name_list).values('name', 'treatment', 'usage','composition')  # 获取体质称的数据name_df = pd.DataFrame(list(name_data))for i in range(len(name_df)):temp = {"name": name_df["name"][i], "treatment": name_df["treatment"][i],"usage": name_df["usage"][i], "composition": name_df["composition"][i],"num": sort_dict[name_df["name"][i]]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_yangshengchayin.html',{'answer_list': answer_list, 'name_data_list': name_data_list})

10.蔬菜推荐计算

"""养生蔬菜推荐计算"""
def YangShengShuCai(request):data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)name_df = pd.DataFrame()name_data_list = []if request.GET.get('time'):# 获取答题结果处理成模型需要的数据样式data = InterrogationUser.objects.filter(user_name=request.user.user_name)[0]sex = "men" if data.user_sex.type_id == 1 else "women"answer_list = UserAnswer.objects.filter(user_tel=data.user_tel)answer_time_num = request.GET.get('time')result = UserAnswer.objects.filter(answer_time_num=answer_time_num)[0]result = pd.DataFrame(eval(result.user_answer), columns=["Q", "A"])result.set_index(['Q'], inplace=True)result['A'] = result['A'].replace("", "0")result = result.Tlabel_list = RecommendVegetable.objects.values("name")label_list = [i["name"] for i in label_list]clear_session()model = load_model(MODEL_ROOT + 'tiaoli\\vegetable_{}.h5'.format(sex))pro = model.predict_proba(result)result_ = pd.DataFrame(pro, columns=label_list)dict_ = result_.to_dict('records')[0]sort_list = sorted(dict_.items(), key=operator.itemgetter(1), reverse=True)[:5]sort_dict = {}for i in sort_list:  # 体质百分比字典sort_dict[i[0]] = str(round(i[1], 2)) + "%"name_list = [(i[0]) for i in sort_list]  # 体质名称name_data = RecommendVegetable.objects.filter(name__in=name_list).values('name', 'remarks')  # 获取体质称的数据name_df = pd.DataFrame(list(name_data))for i in range(len(name_df)):temp = {"name": name_df["name"][i], "remarks": name_df["remarks"][i],"num": sort_dict[name_df["name"][i]]}name_data_list.append(temp)return render(request, 'interrogation/interrogation_result_yangshengshucai.html',{'answer_list': answer_list, 'name_data_list': name_data_list})