Commit 2b249c5a authored by haoyanbin's avatar haoyanbin

1

parent 0f897af2
...@@ -11,12 +11,11 @@ def create_app(test_config=None): ...@@ -11,12 +11,11 @@ def create_app(test_config=None):
DATABASE=os.path.join(app.instance_path, 'apps.sqlite'), DATABASE=os.path.join(app.instance_path, 'apps.sqlite'),
) )
from app.controller import search from app.controller import search,importdata,neodata,auth
from app.controller import importdata
from app.controller import auth
app.register_blueprint(auth.bp)
app.register_blueprint(importdata.bp)
app.register_blueprint(search.bp) app.register_blueprint(search.bp)
app.register_blueprint(importdata.bp)
app.register_blueprint(neodata.bp)
app.register_blueprint(auth.bp)
if test_config is None: if test_config is None:
# load the instance config, if it exists, when not testing # load the instance config, if it exists, when not testing
......
...@@ -3,16 +3,12 @@ import os ...@@ -3,16 +3,12 @@ import os
import random import random
import re import re
import time import time
from flask import Blueprint, json from flask import Blueprint, json
import requests import requests
from py2neo import Graph, Node, Relationship, NodeMatcher # from clickhouse_driver import Client
from clickhouse_driver import Client from app.model.base import dbconn, dbconn2
from app.model.base import dbconn, dbconn2, graph
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
# from database.neo import graph
bp = Blueprint('importdata', __name__, url_prefix='/importdata') bp = Blueprint('importdata', __name__, url_prefix='/importdata')
...@@ -247,126 +243,41 @@ def data_keyword_clinical(): ...@@ -247,126 +243,41 @@ def data_keyword_clinical():
return '2' return '2'
@bp.route('/neo_treatment_medicinal')
def neo_treatment_medicinal():
node_matcher = NodeMatcher(graph)
sql_str = 'SELECT tm.medicinal_id, tm.treatment_id, me.name ' \
' FROM treatment_medicinal as tm ' \
' left join medicinal as me on tm.medicinal_id = me.id ' \
' where tm.id > 0'
rows = dbconn.query(
sql=sql_str
)
for val in rows:
node_treatment = node_matcher.match('治疗方案', id=val['treatment_id'], type=2).first()
if node_treatment is None:
continue
node_medicinal = node_matcher.match('药品', id=val['medicinal_id'], type=2).first()
if node_medicinal is None:
node_medicinal = Node('药品', id=val['medicinal_id'], name=val['name'], type=2)
link3 = Relationship(node_treatment, '适用药品', node_medicinal)
graph.create(link3)
return '1'
@bp.route('/neo_illness_treatment')
def neo_illness_treatment():
node_matcher = NodeMatcher(graph)
sql_str = 'SELECT il.cate_id, il.treatment_id, tr.name, tr.medicinal_data ' \
' FROM illness_treatment as il ' \
' left join treatment as tr on il.treatment_id = tr.id ' \
' where il.id > 0'
rows = dbconn.query(
sql=sql_str
)
for val in rows:
node_cate3 = node_matcher.match('疾病(三)', id=val['cate_id']).first()
if node_cate3 is None:
continue
node_symptoms = node_matcher.match('治疗方案', id=val['treatment_id'], type=2).first()
if node_symptoms is None:
node_symptoms = Node('治疗方案', id=val['treatment_id'], name=val['name'], medicinal_data=val['medicinal_data'],
type=2)
link3 = Relationship(node_cate3, '治疗', node_symptoms)
graph.create(link3)
return '1'
@bp.route('/neo_illness_symptoms')
def neo_illness_symptoms():
node_matcher = NodeMatcher(graph)
sql_str = 'SELECT il.cate_id, il.symptoms_id, sy.name ' \
' FROM illness_symptoms as il ' \
' left join symptoms as sy on il.symptoms_id = sy.id ' \
' where il.id > 0'
rows = dbconn.query(
sql=sql_str
)
for val in rows:
node_cate3 = node_matcher.match('疾病(三)', id=val['cate_id']).first()
if node_cate3 is None:
continue
node_symptoms = node_matcher.match('病症', id=val['symptoms_id'], type=2).first()
if node_symptoms is None:
node_symptoms = Node('病症', id=val['symptoms_id'], name=val['name'], type=2)
link3 = Relationship(node_cate3, '病症', node_symptoms)
link2 = Relationship(node_symptoms, '疾病', node_cate3)
graph.create(link2)
graph.create(link3)
return '1'
@bp.route('/data_trmed') @bp.route('/data_trmed')
def data_trmed(): def data_trmed():
data = dbconn.query( data = dbconn.query(
sql='SELECT id, cate_id, `illness_name`,drug_name FROM illness_durg where id > 0' sql='SELECT id, `name`, `medicinal_data` FROM treatment where id > 0'
) )
for val in data: for val in data:
tid = get_treatment(val['illness_name'], val['drug_name']) res = val['medicinal_data'].split('、')
data3 = { drug_keyword = ''
'cate_id': val['cate_id'],
'treatment_id': tid
}
dbconn.insert(table='illness_treatment', data=data3)
res = val['drug_name'].split('、')
for val2 in res: for val2 in res:
mid = get_medicinal(val2) if val2 == "":
continue
drug = dbconn.query(
sql='SELECT id, `name` FROM drug where id > 0 and `name` like \'%' + val2 + '%\''
)
get_treatment_medicinal(tid, mid) if len(drug) > 0:
# data2 = {
# 'treatment_id': tid, for val4 in drug:
# 'medicinal_id': mid data3 = {
# } 'treatment_id': val['id'],
# dbconn.insert(table='treatment_medicinal', data=data2) 'drug_id': val4['id']
}
dbconn.insert(table='treatment_drug', data=data3)
drug_keyword += val4['name'] + ','
drug_keyword = drug_keyword.strip(',')
data_end = {'drug_data': drug_keyword}
cond = {'id': val['id']}
dbconn.update(table='treatment', data=data_end, condition=cond)
return '1' return '1'
...@@ -655,209 +566,6 @@ def test2(): ...@@ -655,209 +566,6 @@ def test2():
return "1" return "1"
@bp.route('/neo_biochemical')
def neo_biochemical():
node_matcher = NodeMatcher(graph)
rows = dbconn.query(
sql='SELECT id, abbreviation, `name`, _range, lab_category_id, biochemical_id FROM lab_category_biochemical where id > 0'
)
for val in rows:
node_cate3 = node_matcher.match('疾病(三)', id=val['lab_category_id']).first()
if node_cate3 is None:
continue
if val['_range'] == 'high':
cn_standard = '高'
else:
cn_standard = '低'
name = val['name'] + '(' + cn_standard + ')'
node_biochemical = node_matcher.match('检查项', id=val['biochemical_id']).first()
if node_biochemical is None:
node_biochemical = Node("检查项", id=val['biochemical_id'], name=name, cn_name=val['name'],
abbreviation=val['abbreviation'], standard=val['_range'],
category_id=val['lab_category_id'])
link3 = Relationship(node_cate3, '检查', node_biochemical)
graph.create(link3)
return '1'
@bp.route('/neo_prestext')
def neo_prestext():
node_matcher = NodeMatcher(graph)
pres = dbconn.query(
sql='SELECT langtext, prescription_id FROM lab_category_prescription where id > 0 group by prescription_id'
)
for val in pres:
node_pres = node_matcher.match('治疗原则', id=val['prescription_id']).first()
if node_pres is None:
continue
text = json.loads(val['langtext'])
node_text = Node('')
link3 = Relationship(node_pres, '治疗', node_text)
graph.create(link3)
return '1'
@bp.route('/neo_pres')
def neo_pres():
node_matcher = NodeMatcher(graph)
pres = dbconn.query(
sql='SELECT id, `name`, lab_category_id, langtext, prescription_id FROM lab_category_prescription where id > 0'
)
for val in pres:
node_cate3 = node_matcher.match('疾病(三)', id=val['lab_category_id']).first()
if node_cate3 is None:
continue
node_pres = node_matcher.match('治疗原则', id=val['prescription_id']).first()
if node_pres is None:
node_pres = Node("治疗原则", id=val['prescription_id'], name=val['name'], category_id=val['lab_category_id'])
link3 = Relationship(node_cate3, '治疗', node_pres)
graph.create(link3)
return '1'
@bp.route('/neo_cate2')
def neo_cate2():
node_matcher = NodeMatcher(graph)
category3 = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 3'
)
for val3 in category3:
# node_cate3 = Node("疾病(三)", id=val3['id'], name=val3['name'], parent_id=val3['parent_id'])
node_cate3 = node_matcher.match('疾病(三)', id=val3['id']).first()
if node_cate3 is None:
node_cate3 = Node("疾病(三)", id=val3['id'], name=val3['name'], parent_id=val3['parent_id'])
# description = replace_self(val3['description'])
# if description is not None:
# node_description = Node("描述", name=description)
# link3 = Relationship(node_cate3, '描述', node_description)
# graph.create(link3)
#
# examintions = replace_self(val3['examintions'])
# if examintions is not None:
# node_examintions = Node("建议检测项目", name=examintions)
# link4 = Relationship(node_cate3, '建议检测项目', node_examintions)
# graph.create(link4)
#
# remarks = replace_self(val3['remarks'])
# if remarks is not None:
# node_remarks = Node("医嘱", name=remarks)
# link5 = Relationship(node_cate3, '医嘱', node_remarks)
# graph.create(link5)
prognosis = replace_self(val3['prognosis'])
if prognosis is not None:
node_prognosis = Node("预后", name=prognosis)
link6 = Relationship(node_cate3, '预后', node_prognosis)
graph.create(link6)
adjuvanttherapy = replace_self(val3['adjuvanttherapy'])
if adjuvanttherapy is not None:
dict_adj = json.loads(adjuvanttherapy)
str_adj = ''
for adj in dict_adj:
str_adj += adj['servicename'] + '。'
node_adjuvanttherapy = Node("辅助疗法", name=str_adj)
link7 = Relationship(node_cate3, '辅助疗法', node_adjuvanttherapy)
graph.create(link7)
return '1'
@bp.route('/neo_cate')
def neo_cate():
node_matcher = NodeMatcher(graph)
# sql='SELECT d.id, d.drug_name,a.res FROM drug as d left join api as a on d.drug_name = a.param where d.id > 943'
category = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 1'
)
category2 = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 2'
)
category3 = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 3'
)
for val in category:
node_cate = Node("疾病(一)", id=val['id'], name=val['name'], parent_id=val['parent_id'])
for val2 in category2:
if val2['parent_id'] == val['id']:
node_cate2 = Node("疾病(二)", id=val2['id'], name=val2['name'], parent_id=val2['parent_id'])
link1 = Relationship(node_cate, '分类', node_cate2)
graph.create(link1)
for val3 in category3:
if val3['parent_id'] == val2['id']:
node_cate3 = Node("疾病(三)", id=val3['id'], name=val3['name'], parent_id=val3['parent_id'])
link2 = Relationship(node_cate2, '分类', node_cate3)
graph.create(link2)
description = replace_self(val3['description'])
if description is not None:
node_description = Node("描述", name=description)
link3 = Relationship(node_cate3, '描述', node_description)
graph.create(link3)
examintions = replace_self(val3['examintions'])
if examintions is not None:
node_examintions = Node("建议检测项目", name=examintions)
link4 = Relationship(node_cate3, '建议检测项目', node_examintions)
graph.create(link4)
remarks = replace_self(val3['remarks'])
if remarks is not None:
node_remarks = Node("医嘱", name=remarks)
link5 = Relationship(node_cate3, '医嘱', node_remarks)
graph.create(link5)
prognosis = replace_self(val3['prognosis'])
if prognosis is not None:
node_prognosis = Node("预后", name=prognosis)
link6 = Relationship(node_cate3, '预后', node_prognosis)
graph.create(link6)
adjuvanttherapy = replace_self(val3['adjuvanttherapy'])
if prognosis is not None:
node_adjuvanttherapy = Node("辅助疗法", name=adjuvanttherapy)
link7 = Relationship(node_cate3, '辅助疗法', node_adjuvanttherapy)
graph.create(link7)
return "1"
@bp.route('/data_presdrug') @bp.route('/data_presdrug')
def data_presdrug(): def data_presdrug():
pres = dbconn.query( pres = dbconn.query(
...@@ -929,137 +637,21 @@ def data_clinicalid(): ...@@ -929,137 +637,21 @@ def data_clinicalid():
return '1' return '1'
@bp.route('/neo_clinical')
def neo_clinical():
node_matcher = NodeMatcher(graph)
# clinical_id = dbconn.query(
# sql='SELECT id, `name`, `value`, `qz`, lab_category_id FROM lab_clinical where id > 0'
# )
# sql='SELECT d.id, d.drug_name,a.res FROM drug as d left join api as a on d.drug_name = a.param where d.id > 943'
clinical = dbconn.query(
sql='SELECT id, `name`, `value`, `qz`, lab_category_id, clinical_id FROM lab_clinical where id > 0'
)
category = dbconn.query(
sql='SELECT id, parent_id, `name` FROM lab_category where id > 0 and children = 3'
)
for val in clinical:
# clinical_id = get_clinical(val['name'])
node_clinical = node_matcher.match('病症', id=val['clinical_id']).first()
if node_clinical is None:
node_clinical = Node("病症", id=val['clinical_id'], name=val['name'])
for val2 in category:
if val2['id'] == val['lab_category_id']:
node_cate = node_matcher.match('疾病(三)', id=val2['id']).first()
if node_cate is None:
node_cate = Node("疾病(三)", id=val2['id'], name=val2['name'], parent_id=val2['parent_id'])
# node_clinical = Node("病症", id=val['id'], name=val['name'], value=val['value'], qz=val['qz'], category_id=val['lab_category_id'])
link2 = Relationship(node_clinical, '疾病', node_cate)
link3 = Relationship(node_cate, '病症', node_clinical)
graph.create(link2)
graph.create(link3)
return '1'
@bp.route('/neo_drug')
def neo_drug():
node_matcher = NodeMatcher(graph)
# sql='SELECT d.id, d.drug_name,a.res FROM drug as d left join api as a on d.drug_name = a.param where d.id > 943'
drug = dbconn.query(
sql='SELECT d.id, d.drug_name FROM drug as d where d.id > 0 '
)
# print(drug)
drug_disease = dbconn.query(
sql='SELECT d.drug_id, d.disease_id, d.usage, d.pet_species FROM drug_disease as d where d.id > 0'
)
disease = dbconn.query(
sql='SELECT d.id, d.disease_name FROM disease as d where d.id > 0'
)
disease_data = {}
for val in disease:
disease_data[val['id']] = val['disease_name']
for val2 in drug:
node_drug = Node("药品", id=val2['id'], name=val2['drug_name'])
for val3 in drug_disease:
if val2['id'] == val3['drug_id']:
node_disease = node_matcher.match('适应症', id=val3['disease_id']).first()
if node_disease is None:
node_disease = Node("适应症", id=val3['disease_id'], name=disease_data[val3['disease_id']])
node_pet_species = Node("品种", drug_id=val3['drug_id'], disease_id=val3['disease_id'],
name=val3['pet_species'])
# link1 = Relationship(node_drug, '品种', node_pet_species)
link2 = Relationship(node_disease, '品种', node_pet_species)
node_usage = Node("用法用量", drug_id=val3['drug_id'], disease_id=val3['disease_id'], name=val3['usage'])
link3 = Relationship(node_pet_species, '用法用量', node_usage)
link4 = Relationship(node_drug, '适应症', node_disease)
link1 = Relationship(node_disease, '用药', node_drug)
graph.create(link1)
graph.create(link2)
graph.create(link3)
graph.create(link4)
# node_indication = Node("适应症", name=indication)
# node_useto = Node("用途", name=useto)
# node_usage = Node("用法用量", name=usage)
# node_basis = Node("成分", name=basis)
# node1_unreactions = Node("不良反应", name=unreactions)
#
# link1 = Relationship(node_gen_name, '适应症', node_indication)
# graph.create(link1)
#
# link2 = Relationship(node_gen_name, '用途', node_useto)
# graph.create(link2)
#
# link3 = Relationship(node_gen_name, '用法用量', node_usage)
# graph.create(link3)
#
# link4 = Relationship(node_gen_name, '成分', node_basis)
# graph.create(link4)
#
# link5 = Relationship(node_gen_name, '不良反应', node1_unreactions)
# graph.create(link5)
return "1"
@bp.route('/c') @bp.route('/c')
def test(): def test():
# 建立与ClickHouse数据库的连接 # 建立与ClickHouse数据库的连接
conn = Client( # conn = Client(
host='cc-2zejbg2y0c0m15o20o.ads.rds.aliyuncs.com', # host='cc-2zejbg2y0c0m15o20o.ads.rds.aliyuncs.com',
port='3306', # port='3306',
user='root_house', # user='root_house',
password='dbc_root888', # password='dbc_root888',
database='dbc_drug' # database='dbc_drug'
) # )
# sqlStr = 'select * from drug_dh limit 10' # # sqlStr = 'select * from drug_dh limit 10'
sqlStr = 'select drug_name,eng_name,drug_info,uad,useto,note,preparation,adrs,cate,spec,withdrawal_time from vp_codex' # sqlStr = 'select drug_name,eng_name,drug_info,uad,useto,note,preparation,adrs,cate,spec,withdrawal_time from vp_codex'
result = conn.execute(sqlStr) # result = conn.execute(sqlStr)
# print(result) # print(result)
...@@ -1081,41 +673,41 @@ def test(): ...@@ -1081,41 +673,41 @@ def test():
# graph.create(node_1) # graph.create(node_1)
# graph.create(node_2) # graph.create(node_2)
for row in result: # for row in result:
# id, dh_name, dh_info, state, file, state_info, createtime = row # # id, dh_name, dh_info, state, file, state_info, createtime = row
# print(id, dh_name, dh_info, state, file, state_info, createtime) # # print(id, dh_name, dh_info, state, file, state_info, createtime)
# gen_name,eng_name,indication,useto,note,usage,basis,spec,unreactions = row # # gen_name,eng_name,indication,useto,note,usage,basis,spec,unreactions = row
# # #
# cond_b = { # # cond_b = {
# 'gen_name': gen_name, # # 'gen_name': gen_name,
# 'eng_name': eng_name, # # 'eng_name': eng_name,
# 'indication': indication, # # 'indication': indication,
# 'useto': useto, # # 'useto': useto,
# 'note': note, # # 'note': note,
# 'usage': usage, # # 'usage': usage,
# 'basis': basis, # # 'basis': basis,
# 'spec': spec, # # 'spec': spec,
# 'unreactions': unreactions # # 'unreactions': unreactions
# } # # }
# # #
# dbconn.insert(table='drug_stock', data=cond_b) # # dbconn.insert(table='drug_stock', data=cond_b)
drug_name, eng_name, drug_info, uad, useto, note, preparation, adrs, cate, spec, withdrawal_time = row # drug_name, eng_name, drug_info, uad, useto, note, preparation, adrs, cate, spec, withdrawal_time = row
cond_b = { # cond_b = {
'drug_name': drug_name, # 'drug_name': drug_name,
'eng_name': eng_name, # 'eng_name': eng_name,
'drug_info': drug_info, # 'drug_info': drug_info,
'uad': uad, # 'uad': uad,
'useto': useto, # 'useto': useto,
'note': note, # 'note': note,
'preparation': preparation, # 'preparation': preparation,
'adrs': adrs, # 'adrs': adrs,
'cate': cate, # 'cate': cate,
'spec': spec, # 'spec': spec,
'withdrawal_time': withdrawal_time # 'withdrawal_time': withdrawal_time
} # }
dbconn.insert(table='vp_codex', data=cond_b) # dbconn.insert(table='vp_codex', data=cond_b)
# node_gen_name = Node("药品", name=gen_name, goods_name=goods_name) # node_gen_name = Node("药品", name=gen_name, goods_name=goods_name)
# node_indication = Node("适应症", name=indication) # node_indication = Node("适应症", name=indication)
......
# encoding: utf-8
from flask import Blueprint, json
from app.model.base import dbconn, graph_driver
bp = Blueprint('neodata', __name__, url_prefix='/neodata')
@bp.route('/t2', methods=['POST', 'GET'])
def t2():
# graph_sql3 = "match (a:`症状`)-[]->(m:`症状`) where a.name='鼻分泌物多浓' return m,a"
# graph_sql4 = "match (a:`用途`) return a"
graph_driver.execute_query(
"MERGE (a:Person {name: $name}) "
"MERGE (friend:Person {name: $friend_name}) "
"MERGE (a)-[:KNOWS]->(friend)",
name="aaa", friend_name="bbb",
)
# graph_sql5 = "g.V().label().dedup()"
# with graph_driver.session() as session:
# graph_data3 = session.run(graph_sql3)
# for record in graph_data3:
# print(record.data()[0])
# graph_data4 = graph.run(graph_sql4).data()
# graph_data5 = graph.run(graph_sql5).data()
# node_useto = Node("用途", name="测试111")
# graph.create(node_useto)
# node_matcher = NodeMatcher(graph)
# node_treatment = node_matcher.match('用途', name='测试111').first()
# if node_treatment is None:
# node_treatment = Node('用途', name='测试111')
# graph.create(node_treatment)
#
# node_medicinal = node_matcher.match('药品', name='测试222').first()
# if node_medicinal is None:
# node_medicinal = Node('药品', name='测试222')
# graph.create(node_medicinal)
#
# link3 = Relationship(node_treatment, '适用药品', node_medicinal)
#
# graph.create(link3)
# graph.create(node_cate2)
# link1 = Relationship(node_cate, '分类', node_cate2)
medicinal = {}
# for val2 in graph_data3:
# print(val2)
# illness_data[key1]['treatment'] = medicinal
# result.append(illness_data[key1])
return json.dumps(medicinal)
@bp.route('/neo_symptoms')
def neo_symptoms():
rows = dbconn.query(
sql='SELECT isy.cate_id, s.id, s.`name` FROM illness_symptoms as isy left join symptoms as s on isy.symptoms_id = s.id where isy.id > 0'
)
for val in rows:
sql2 = """MERGE (a:疾病 {id: $ida, children:3, type:1})
MERGE (b:病症 {id: $idb, name: $name, type:1})
MERGE (a)-[:病症]->(b)
MERGE (b)-[:疾病]->(a)"""
graph_driver.execute_query(sql2, ida=val['cate_id'], idb=val['id'], name=val['name'])
return '1'
@bp.route('/neo_treatment')
def neo_treatment():
rows = dbconn.query(
sql='SELECT it.cate_id, t.id, t.`name`, t.medicinal_data FROM illness_treatment as it left join treatment as t on it.treatment_id = t.id where it.id > 0'
)
for val in rows:
sql2 = """MERGE (a:疾病 {id: $ida, children:3, type:1})
MERGE (b:治疗方案 {id: $idb, name: $name, medicinal_data: $medicinal_data, type:1})
MERGE (a)-[:治疗]->(b)"""
graph_driver.execute_query(sql2, ida=val['cate_id'], idb=val['id'], name=val['name'], medicinal_data=val['medicinal_data'])
return '1'
@bp.route('/neo_treatment_drug')
def neo_treatment_drug():
rows = dbconn.query(
sql='SELECT tdr.treatment_id, tdr.drug_id FROM treatment_drug as tdr where id > 0'
)
for val in rows:
sql2 = """MERGE (a:治疗方案 {id: $ida, type:1})
MERGE (b:药品 {id: $idb, type:1})
MERGE (a)-[:用药]->(b)"""
graph_driver.execute_query(sql2, ida=val['treatment_id'], idb=val['drug_id'])
return '1'
@bp.route('/neo_treatment_medicinal')
def neo_treatment_medicinal():
sql_str = 'SELECT tm.medicinal_id, tm.treatment_id, me.name FROM treatment_medicinal as tm left join medicinal as me on tm.medicinal_id = me.id where tm.id > 0'
rows = dbconn.query(
sql=sql_str
)
for val in rows:
sql2 = """MERGE (a:治疗方案 {id: $ida, type:1})
MERGE (b:治疗方案 {id: $idb, name: $name, type:1})
MERGE (a)-[:治疗]->(b)"""
graph_driver.execute_query(sql2, ida=val['treatment_id'], idb=val['medicinal_id'], name=val['name'])
return '1'
@bp.route('/neo_biochemical')
def neo_biochemical():
rows = dbconn.query(
sql='SELECT id, abbreviation, `name`, _range, lab_category_id, biochemical_id FROM lab_category_biochemical where id > 0'
)
for val in rows:
if val['_range'] == 'high':
cn_standard = '高'
else:
cn_standard = '低'
name = val['name'] + '(' + cn_standard + ')'
sql2 = """MERGE (a:疾病 {id: $ida, children:3, type:1})
MERGE (b:检查项 {id: $idb, name: $name, cn_name: $cn_name, abbreviation:$abbreviation, standard:$standard, category_id:$category_id, type:1})
MERGE (a)-[:检查]->(b)"""
graph_driver.execute_query(sql2, ida=val['lab_category_id'], idb=val['biochemical_id'], name=name, cn_name=val['name'],
abbreviation=val['abbreviation'], standard=val['_range'],
category_id=val['lab_category_id'])
return '1'
@bp.route('/neo_prestext')
def neo_prestext():
# node_matcher = NodeMatcher(graph)
# pres = dbconn.query(
# sql='SELECT langtext, prescription_id FROM lab_category_prescription where id > 0 group by prescription_id'
# )
# for val in pres:
# sql2 = """MERGE (a:疾病 {id: $ida, children:3, type:1})
# MERGE (b:治疗原则 {id: $idb, name: $name, cn_name: $cn_name, abbreviation:$abbreviation, standard:$standard, category_id:$category_id, type:1})
# MERGE (a)-[:治疗]->(b)"""
# graph_driver.execute_query(sql2, ida=val['lab_category_id'], idb=val['biochemical_id'], name=name, cn_name=val['name'],
# abbreviation=val['abbreviation'], standard=val['_range'],
# category_id=val['lab_category_id'])
# node_pres = node_matcher.match('治疗原则', id=val['prescription_id']).first()
# if node_pres is None:
# continue
# text = json.loads(val['langtext'])
# node_text = Node('')
# link3 = Relationship(node_pres, '治疗', node_text)
# graph.create(link3)
return '1'
@bp.route('/neo_pres')
def neo_pres():
pres = dbconn.query(
sql='SELECT id, `name`, lab_category_id, langtext, prescription_id FROM lab_category_prescription where id > 0'
)
for val in pres:
sql2 = """MERGE (a:疾病 {id: $ida, children:3, type:1})
MERGE (b:治疗原则 {id: $idb, name: $name, category_id:$category_id, type:1})
MERGE (a)-[:治疗]->(b)"""
graph_driver.execute_query(sql2, ida=val['lab_category_id'], idb=val['prescription_id'], name=val['name'], category_id=val['lab_category_id'])
return '1'
@bp.route('/neo_cate2')
def neo_cate2():
# node_matcher = NodeMatcher(graph)
# category3 = dbconn.query(
# sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 3'
# )
# for val3 in category3:
# # node_cate3 = Node("疾病(三)", id=val3['id'], name=val3['name'], parent_id=val3['parent_id'])
# node_cate3 = node_matcher.match('疾病(三)', id=val3['id']).first()
# if node_cate3 is None:
# node_cate3 = Node("疾病(三)", id=val3['id'], name=val3['name'], parent_id=val3['parent_id'])
# description = replace_self(val3['description'])
# if description is not None:
# node_description = Node("描述", name=description)
# link3 = Relationship(node_cate3, '描述', node_description)
# graph.create(link3)
#
# examintions = replace_self(val3['examintions'])
# if examintions is not None:
# node_examintions = Node("建议检测项目", name=examintions)
# link4 = Relationship(node_cate3, '建议检测项目', node_examintions)
# graph.create(link4)
#
# remarks = replace_self(val3['remarks'])
# if remarks is not None:
# node_remarks = Node("医嘱", name=remarks)
# link5 = Relationship(node_cate3, '医嘱', node_remarks)
# graph.create(link5)
# prognosis = replace_self(val3['prognosis'])
# if prognosis is not None:
# node_prognosis = Node("预后", name=prognosis)
# link6 = Relationship(node_cate3, '预后', node_prognosis)
# graph.create(link6)
# adjuvanttherapy = replace_self(val3['adjuvanttherapy'])
# if adjuvanttherapy is not None:
# dict_adj = json.loads(adjuvanttherapy)
# str_adj = ''
# for adj in dict_adj:
# str_adj += adj['servicename'] + '。'
# node_adjuvanttherapy = Node("辅助疗法", name=str_adj)
# link7 = Relationship(node_cate3, '辅助疗法', node_adjuvanttherapy)
# graph.create(link7)
return '1'
@bp.route('/neo_cate')
def neo_cate():
category = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 1'
)
category2 = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 2'
)
category3 = dbconn.query(
sql='SELECT id, parent_id, `name`, description, examintions, remarks, prognosis, adjuvanttherapy FROM lab_category where id > 0 and children = 3'
)
for val in category:
sql1 = 'MERGE (a:疾病 {id: $id, name: $name, parent_id: $parent_id, children:1, type:1}) '
graph_driver.execute_query(sql1, id=val['id'], name=val['name'], parent_id=val['parent_id'])
for val2 in category2:
if val2['parent_id'] == val['id']:
sql2 = """MERGE (a:疾病 {id: $ida, name: $namea, parent_id: $parent_ida, children:1, type:1})
MERGE (b:疾病 {id: $idb, name: $nameb, parent_id: $parent_idb, children:2, type:1})
MERGE (a)-[:分类]->(b)"""
graph_driver.execute_query(sql2,ida=val['id'], namea=val['name'], parent_ida=val['parent_id'],
idb=val2['id'], nameb=val2['name'], parent_idb=val2['parent_id'])
for val3 in category3:
if val3['parent_id'] == val2['id']:
sql2 = """MERGE (a:疾病 {id: $ida, name: $namea, parent_id: $parent_ida, children:2, type:1})
MERGE (b:疾病 {id: $idb, name: $nameb, parent_id: $parent_idb, description:$description
, examintions:$examintions, remarks:$remarks, prognosis:$prognosis
, adjuvanttherapy:$adjuvanttherapy, children:3, type:1})
MERGE (a)-[:分类]->(b)"""
graph_driver.execute_query(sql2,ida=val2['id'], namea=val2['name'], parent_ida=val2['parent_id'],
idb=val3['id'], nameb=val3['name'], parent_idb=val3['parent_id'],
description=replace_self(val3['description']),examintions=replace_self(val3['examintions']),
remarks=replace_self(val3['remarks']),prognosis=replace_self(val3['prognosis']),
adjuvanttherapy=replace_self(val3['adjuvanttherapy']))
return "1"
@bp.route('/neo_clinical')
def neo_clinical():
node_matcher = NodeMatcher(graph)
# clinical_id = dbconn.query(
# sql='SELECT id, `name`, `value`, `qz`, lab_category_id FROM lab_clinical where id > 0'
# )
# sql='SELECT d.id, d.drug_name,a.res FROM drug as d left join api as a on d.drug_name = a.param where d.id > 943'
clinical = dbconn.query(
sql='SELECT id, `name`, `value`, `qz`, lab_category_id, clinical_id FROM lab_clinical where id > 0'
)
category = dbconn.query(
sql='SELECT id, parent_id, `name` FROM lab_category where id > 0 and children = 3'
)
for val in clinical:
# clinical_id = get_clinical(val['name'])
node_clinical = node_matcher.match('病症', id=val['clinical_id']).first()
if node_clinical is None:
node_clinical = Node("病症", id=val['clinical_id'], name=val['name'])
for val2 in category:
if val2['id'] == val['lab_category_id']:
node_cate = node_matcher.match('疾病(三)', id=val2['id']).first()
if node_cate is None:
node_cate = Node("疾病(三)", id=val2['id'], name=val2['name'], parent_id=val2['parent_id'])
# node_clinical = Node("病症", id=val['id'], name=val['name'], value=val['value'], qz=val['qz'], category_id=val['lab_category_id'])
link2 = Relationship(node_clinical, '疾病', node_cate)
link3 = Relationship(node_cate, '病症', node_clinical)
graph.create(link2)
graph.create(link3)
return '1'
@bp.route('/neo_drug')
def neo_drug():
drug = dbconn.query(
sql='SELECT d.id, d.name FROM drug as d where d.id > 0 '
)
drug_disease = dbconn.query(
sql='SELECT d.drug_id, d.disease_id, d.usage, d.pet_species FROM drug_disease as d where d.id > 0'
)
disease = dbconn.query(
sql='SELECT d.id, d.name FROM disease as d where d.id > 0'
)
disease_data = {}
for val in disease:
disease_data[val['id']] = val['name']
for val2 in drug:
sql1 = 'MERGE (a:药品 {id: $id, name: $name, type:1})'
graph_driver.execute_query(sql1, id=val2['id'], name=val2['name'])
for val3 in drug_disease:
if val2['id'] == val3['drug_id']:
sql2 = """MERGE (a:药品 {id: $ida, type:1})
MERGE (b:适应症 {id: $idb, name: $name, type:1})
MERGE (a)-[:适应症]->(b)
MERGE (b)-[:用药]->(a)"""
graph_driver.execute_query(sql2, ida=val2['id'], idb=val3['disease_id'], name=disease_data[val3['disease_id']])
# node_disease = node_matcher.match('适应症', id=val3['disease_id']).first()
# if node_disease is None:
# node_disease = Node("适应症", id=val3['disease_id'], name=disease_data[val3['disease_id']])
# node_pet_species = Node("品种", drug_id=val3['drug_id'], disease_id=val3['disease_id'],
# name=val3['pet_species'])
# # link1 = Relationship(node_drug, '品种', node_pet_species)
# link2 = Relationship(node_disease, '品种', node_pet_species)
# node_usage = Node("用法用量", drug_id=val3['drug_id'], disease_id=val3['disease_id'], name=val3['usage'])
# link3 = Relationship(node_pet_species, '用法用量', node_usage)
# link4 = Relationship(node_drug, '适应症', node_disease)
# link1 = Relationship(node_disease, '用药', node_drug)
# graph.create(link1)
# graph.create(link2)
# graph.create(link3)
# graph.create(link4)
# node_indication = Node("适应症", name=indication)
# node_useto = Node("用途", name=useto)
# node_usage = Node("用法用量", name=usage)
# node_basis = Node("成分", name=basis)
# node1_unreactions = Node("不良反应", name=unreactions)
#
# link1 = Relationship(node_gen_name, '适应症', node_indication)
# graph.create(link1)
#
# link2 = Relationship(node_gen_name, '用途', node_useto)
# graph.create(link2)
#
# link3 = Relationship(node_gen_name, '用法用量', node_usage)
# graph.create(link3)
#
# link4 = Relationship(node_gen_name, '成分', node_basis)
# graph.create(link4)
#
# link5 = Relationship(node_gen_name, '不良反应', node1_unreactions)
# graph.create(link5)
return "1"
def replace_self(str):
return str.replace(" ", "").replace("\t", "").replace("\n", "")
import re import re
from flask import Blueprint, request, json from flask import Blueprint, request, json
from pyecharts import options as opts # from pyecharts import options as opts
from pyecharts.charts import Graph as pg # from pyecharts.charts import Graph as pg
from app.model.base import dbconn, graph from app.model.base import dbconn, graph_driver
bp = Blueprint('search', __name__, url_prefix='/search') bp = Blueprint('search', __name__, url_prefix='/search')
...@@ -34,28 +34,31 @@ def illness_search(): ...@@ -34,28 +34,31 @@ def illness_search():
for val1 in vocab_data: for val1 in vocab_data:
search_data.append(keyword_clinical[val1]) search_data.append(keyword_clinical[val1])
# strData = jieba.cut(data['search_str'], cut_all=False) # # strData = jieba.cut(data['search_str'], cut_all=False)
# graph_sql = "match (n:`疾病(三)`) " # # graph_sql = "match (n:`疾病(三)`) "
# # #
# for search_str in search_data: # # for search_str in search_data:
# if search_str == '': # # if search_str == '':
# continue # # continue
# graph_sql += " with n match (n:`疾病(三)`)-[*1]->(a) where a.name='" + search_str + "' " # # graph_sql += " with n match (n:`疾病(三)`)-[*1]->(a) where a.name='" + search_str + "' "
# # #
# graph_sql += " return n" # # graph_sql += " return n"
# # #
# graph_data = graph.run(graph_sql).data() # # graph_data = graph.run(graph_sql).data()
if len(search_data) == 0:
return ''
illness_data = {} illness_data = {}
for search_str in search_data: for search_str in search_data:
if search_str == '': if search_str == '':
continue continue
graph_sql = "match (n:`疾病(三)`)-[*1]->(a:`病症`) where a.name='" + search_str + "' return n" graph_sql = "match (n:`疾病`)-[*1]->(a:`病症`) where a.name='" + search_str + "' return n"
graph_data = graph.run(graph_sql).data() records, _, _ = graph_driver.query(graph_sql)
for val2 in graph_data: for val2 in records:
if val2['n']['name'] in illness_data.keys(): if val2['n']['name'] in illness_data.keys():
illness_data[val2['n']['name']]['num'] += 1 illness_data[val2['n']['name']]['num'] += 1
else: else:
...@@ -68,16 +71,16 @@ def illness_search(): ...@@ -68,16 +71,16 @@ def illness_search():
list_illness_data = list(illness_data) list_illness_data = list(illness_data)
for key1 in list_illness_data: for key1 in list_illness_data:
graph_sql2 = "match (a:`疾病(三)`)-[]->(m:`治疗方案`)-[]->(n:`药品`) where a.name='" + key1 + "' return m,n" graph_sql2 = "match (a:`疾病`)-[]->(m:`治疗方案`)-[]->(n:`药品`) where a.name='" + key1 + "' return m,n"
graph_data2 = graph.run(graph_sql2).data() records2, _, _ = graph_driver.query(graph_sql2)
graph_sql3 = "match (a:`疾病(三)`)-[]->(m:`治疗方案`) where a.name='" + key1 + "' return m,n" # graph_sql3 = "match (a:`疾病`)-[]->(m:`治疗方案`) where a.name='" + key1 + "' return m,n"
graph_data3 = graph.run(graph_sql3).data() # graph_data3 = graph.run(graph_sql3).data()
medicinal = {} medicinal = {}
for val2 in graph_data2: for val2 in records2:
if val2['m']['name'] in medicinal.keys(): if val2['m']['name'] in medicinal.keys():
medicinal[val2['m']['name']].append(val2['n']['name']) medicinal[val2['m']['name']].append(val2['n']['name'])
else: else:
...@@ -90,71 +93,72 @@ def illness_search(): ...@@ -90,71 +93,72 @@ def illness_search():
# print(result) # print(result)
return json.dumps(result) return json.dumps(result)
return "1"
def testaaa(): def testaaa():
illnessDict = {} # 疾病 # illnessDict = {} # 疾病
symptomsDict = {} # 病症 # symptomsDict = {} # 病症
shipsData = {} # 三元组 # shipsData = {} # 三元组
graph_sql = "match (n:`疾病(三)`)-[*1]->(a:`病症`) where a.name='" + search_str + "' return n" # graph_sql = "match (n:`疾病(三)`)-[*1]->(a:`病症`) where a.name='" + search_str + "' return n"
graph_data = graph.run(graph_sql).data() # graph_data = graph.run(graph_sql).data()
while graph_data.forward(): # while graph_data.forward():
for relation in graph_data.current['p']: # for relation in graph_data.current['p']:
print(list(relation.types())) # print(list(relation.types()))
illness_node = relation.start_node # illness_node = relation.start_node
symptoms_node = relation.end_node # symptoms_node = relation.end_node
relation_type = list(relation.types())[0] # relation_type = list(relation.types())[0]
illness_node_label = str(illness_node.labels).strip(":") # illness_node_label = str(illness_node.labels).strip(":")
symptoms_node_label = str(symptoms_node.labels).strip(":") # symptoms_node_label = str(symptoms_node.labels).strip(":")
# 存储三元组关系 # # 存储三元组关系
if illness_node['id'] in shipsData.keys(): # if illness_node['id'] in shipsData.keys():
target_dict = shipsData.get(illness_node['id']) # target_dict = shipsData.get(illness_node['id'])
target_dict.setdefault(symptoms_node['id'], relation_type) # target_dict.setdefault(symptoms_node['id'], relation_type)
else: # else:
target_dict = {symptoms_node['id']: relation_type} # target_dict = {symptoms_node['id']: relation_type}
shipsData[illness_node['id']] = target_dict # shipsData[illness_node['id']] = target_dict
# 存储节点 # # 存储节点
if ("`疾病(三)`" == illness_node_label) and (illness_node['id'] not in illnessDict.keys()): # if ("`疾病(三)`" == illness_node_label) and (illness_node['id'] not in illnessDict.keys()):
illnessDict[illness_node['id']] = illness_node['name'] # illnessDict[illness_node['id']] = illness_node['name']
if ("病症" == symptoms_node_label) and (symptoms_node['id'] not in symptomsDict.keys()): # if ("病症" == symptoms_node_label) and (symptoms_node['id'] not in symptomsDict.keys()):
symptomsDict[symptoms_node['id']] = symptoms_node['name'] # symptomsDict[symptoms_node['id']] = symptoms_node['name']
json_list = [] # json_list = []
for illness_key, value in shipsData.items(): # for illness_key, value in shipsData.items():
for symptoms_key, rel_type in value.items(): # for symptoms_key, rel_type in value.items():
result_dict = { # result_dict = {
'illness': illnessDict[illness_key], # 'illness': illnessDict[illness_key],
'rel_type': rel_type, # 'rel_type': rel_type,
'symptoms': symptomsDict[symptoms_key] # 'symptoms': symptomsDict[symptoms_key]
} # }
json_list.append(result_dict) # json_list.append(result_dict)
print(len(json_list)) # print(len(json_list))
for i in range(len(json_list)): # for i in range(len(json_list)):
print("{}-[{}]->{}".format(json_list[i]['illness'], json_list[i]['rel_type'], json_list[i]['symptoms'])) # print("{}-[{}]->{}".format(json_list[i]['illness'], json_list[i]['rel_type'], json_list[i]['symptoms']))
return json_list # return json_list
data_dict = set() # data_dict = set()
nodes = [] # nodes = []
links = [] # links = []
for i in range(len(json_list)): # for i in range(len(json_list)):
if json_list[i]['illness'] not in data_dict: # if json_list[i]['illness'] not in data_dict:
data_dict.add(json_list[i]['illness']) # data_dict.add(json_list[i]['illness'])
nodes.append({'name': json_list[i]['illness'], "symbolSize": 10, 'draggable': 'true'}) # nodes.append({'name': json_list[i]['illness'], "symbolSize": 10, 'draggable': 'true'})
if json_list[i]['symptoms'] not in data_dict: # if json_list[i]['symptoms'] not in data_dict:
data_dict.add(json_list[i]['symptoms']) # data_dict.add(json_list[i]['symptoms'])
nodes.append({'name': json_list[i]['symptoms'], "symbolSize": 10, 'draggable': 'true'}) # nodes.append({'name': json_list[i]['symptoms'], "symbolSize": 10, 'draggable': 'true'})
links.append({'source': json_list[i]['illness'], 'target': json_list[i]['symptoms']}) # links.append({'source': json_list[i]['illness'], 'target': json_list[i]['symptoms']})
pg_graph = pg(init_opts=opts.InitOpts(width='1000px', height='800px')) # pg_graph = pg(init_opts=opts.InitOpts(width='1000px', height='800px'))
pg_graph.add("", nodes, links, repulsion=8000, edge_symbol=['', 'arrow']) # pg_graph.add("", nodes, links, repulsion=8000, edge_symbol=['', 'arrow'])
pg_graph.set_global_opts(title_opts=opts.TitleOpts(title="病症对应的疾病")) # pg_graph.set_global_opts(title_opts=opts.TitleOpts(title="病症对应的疾病"))
# print('/'.join(strData)+"") # print('/'.join(strData)+"")
...@@ -164,5 +168,6 @@ def testaaa(): ...@@ -164,5 +168,6 @@ def testaaa():
# ) # )
# print(drug) # print(drug)
# return render_template('index.html') # return render_template('index.html')
return pg_graph.render_notebook() # return pg_graph.render_notebook()
# return json.dumps(list(strData)) # return json.dumps(list(strData))
return "1"
\ No newline at end of file
from lib.libmysql import MYSQL, connect_db from lib.libmysql import MYSQL
from py2neo import Graph, Node, Relationship, NodeMatcher from lib.neo import NEO
dbconn = MYSQL( dbconn = MYSQL(
dbhost='39.96.85.45', dbhost='39.96.85.45',
...@@ -20,4 +20,14 @@ dbconn2 = MYSQL( ...@@ -20,4 +20,14 @@ dbconn2 = MYSQL(
) )
graph = Graph("bolt://gds-2zeyv40mi12s6mjc149870pub.graphdb.rds.aliyuncs.com:3734", auth=("dbc_tair", "dbc_tair888888")) # graph = Graph("", auth=("neo4j", "11111111"))
# graph = Graph("bolt://gds-2zeyv40mi12s6mjc149870pub.graphdb.rds.aliyuncs.com:3734", auth=("dbc_tair", "dbc_tair888888"))
# print(graph)
# graph_driver = GraphDatabase.driver("bolt://gds-2zeyv40mi12s6mjc149870pub.graphdb.rds.aliyuncs.com:3734",auth=("dbc_tair", "dbc_tair888888"),encrypted=False)
graph_driver = NEO(
dbhost='gds-2zeyv40mi12s6mjc149870pub.graphdb.rds.aliyuncs.com',
dbuser='dbc_tair',
dbpwd='dbc_tair888888'
)
# encoding: utf-8
from neo4j import GraphDatabase
class NEO:
def __init__(self, dbhost, dbuser, dbpwd, dbport=3734):
self.dbhost = dbhost
self.dbport = dbport
self.dbuser = dbuser
self.dbpwd = dbpwd
self.connection = self.session()
def session(self):
connection = GraphDatabase.driver(
uri="bolt://"+self.dbhost+":"+str(self.dbport),
auth=(self.dbuser,self.dbpwd),
encrypted=False
)
return connection
def execute_query(self, sql, **kwargs):
return self.connection.execute_query(sql, **kwargs)
def insert(self, sql, **kwargs):
return self.connection.execute_query(sql, **kwargs)
def query(self, sql, parameters={}):
return self.connection.execute_query(sql, parameters_=parameters)
def close(self):
if getattr(self, 'connection', 0):
return self.connection.close()
def __del__(self):
self.close()
beautifulsoup4==4.12.3 beautifulsoup4==4.12.3
clickhouse_driver==0.2.7 clickhouse-driver==0.2.7
Flask==3.0.3 Flask==3.0.3
py2neo==2021.2.4 py2neo==2021.2.3
pyecharts==2.0.5 pyecharts==2.0.5
PyMySQL==1.1.0 PyMySQL==1.1.0
Requests==2.31.0 Requests==2.31.0
neo4j~=5.20.0
pip~=24.0
wheel~=0.43.0
openssl~=3.2.1
jinja2~=3.1.3
setuptools~=69.2.0
\ No newline at end of file
...@@ -3,4 +3,5 @@ from app import create_app ...@@ -3,4 +3,5 @@ from app import create_app
app = create_app() app = create_app()
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=5080, debug=True) # app.run(host='0.0.0.0', port=5080, debug=True)
app.run(port=5080, debug=True)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment