Skip to content

Commit 2321886

Browse files
committed
Clearing Local Storage
1 parent dccc4bc commit 2321886

26 files changed

+52897
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2021 Maja Benkus
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

Medical Chatbot [END 2 END] [NLP]/Meddy.ipynb

+4,265
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# MEDICAL CHATBOT
2+
3+
4+
## Requirements
5+
6+
Python 3.5 or newer.
7+
8+
Dependencies:
9+
10+
- Flask
11+
- PyTorch
12+
- NLTK
13+
- NumPy
14+
- Scikit-learn
15+
- Pandas
16+
- matplotlib
17+
18+
## Install requirements
19+
20+
Before running the application you need to install the dependencies. We recommend to use the virtual environment
21+
[virtualenv](https://pypi.org/project/virtualenv/) for this.
22+
23+
Linux:
24+
25+
```
26+
python3 -m venv venv
27+
venv/bin/activate
28+
pip install flask torch nltk numpy sklearn pandas matplotlib
29+
```
30+
Windows:
31+
32+
```
33+
py -3 -m venv venv
34+
venv\Scripts\activate
35+
pip install flask torch nltk numpy==1.19.3 sklearn pandas matplotlib
36+
```
37+
38+
39+
40+
In order for _nltk_ tokenization to work, the _'punkt'_ package must be downloaded. To do this, simply enter the Python shell and run the following:
41+
42+
```python
43+
import nltk
44+
nltk.download('punkt')
45+
```
46+
47+
This will install all the required dependencies needed to run the application successfully.
48+
49+
## Run
50+
51+
To run MedicalChatbot, `cd` into MedicalChatbot repo on your computer and run `python -m flask run`. This will run the Flask
52+
server in development mode on localhost, port 5000.
53+
54+
`* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)`
Binary file not shown.
Binary file not shown.
Binary file not shown.
+131
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import json
2+
import torch
3+
import nltk
4+
import pickle
5+
import random
6+
from datetime import datetime
7+
import numpy as np
8+
import pandas as pd
9+
10+
from nnet import NeuralNet
11+
from nltk_utils import bag_of_words
12+
from flask import Flask, render_template, url_for, request, jsonify
13+
14+
random.seed(datetime.now())
15+
16+
device = torch.device('cpu')
17+
FILE = "models/data.pth"
18+
model_data = torch.load(FILE)
19+
20+
input_size = model_data['input_size']
21+
hidden_size = model_data['hidden_size']
22+
output_size = model_data['output_size']
23+
all_words = model_data['all_words']
24+
tags = model_data['tags']
25+
model_state = model_data['model_state']
26+
27+
nlp_model = NeuralNet(input_size, hidden_size, output_size).to(device)
28+
nlp_model.load_state_dict(model_state)
29+
nlp_model.eval()
30+
31+
diseases_description = pd.read_csv("data/symptom_Description.csv")
32+
diseases_description['Disease'] = diseases_description['Disease'].apply(lambda x: x.lower().strip(" "))
33+
34+
disease_precaution = pd.read_csv("data/symptom_precaution.csv")
35+
disease_precaution['Disease'] = disease_precaution['Disease'].apply(lambda x: x.lower().strip(" "))
36+
37+
symptom_severity = pd.read_csv("data/Symptom-severity.csv")
38+
symptom_severity = symptom_severity.applymap(lambda s: s.lower().strip(" ").replace(" ", "") if type(s) == str else s)
39+
40+
41+
with open('data/list_of_symptoms.pickle', 'rb') as data_file:
42+
symptoms_list = pickle.load(data_file)
43+
44+
with open('models/fitted_model.pickle', 'rb') as modelFile:
45+
prediction_model = pickle.load(modelFile)
46+
47+
user_symptoms = set()
48+
49+
app = Flask(__name__)
50+
51+
def get_symptom(sentence):
52+
sentence = nltk.word_tokenize(sentence)
53+
X = bag_of_words(sentence, all_words)
54+
X = X.reshape(1, X.shape[0])
55+
X = torch.from_numpy(X)
56+
57+
output = nlp_model(X)
58+
_, predicted = torch.max(output, dim=1)
59+
tag = tags[predicted.item()]
60+
61+
probs = torch.softmax(output, dim=1)
62+
prob = probs[0][predicted.item()]
63+
prob = prob.item()
64+
65+
return tag, prob
66+
67+
@app.route('/')
68+
def index():
69+
data = []
70+
user_symptoms.clear()
71+
file = open("static/assets/files/ds_symptoms.txt", "r")
72+
all_symptoms = file.readlines()
73+
for s in all_symptoms:
74+
data.append(s.replace("'", "").replace("_", " ").replace(",\n", ""))
75+
data = json.dumps(data)
76+
77+
return render_template('index.html', data=data)
78+
79+
80+
@app.route('/symptom', methods=['GET', 'POST'])
81+
def predict_symptom():
82+
print("Request json:", request.json)
83+
sentence = request.json['sentence']
84+
if sentence.replace(".", "").replace("!","").lower().strip() == "done":
85+
86+
if not user_symptoms:
87+
response_sentence = random.choice(
88+
["I can't know what disease you may have if you don't enter any symptoms :)",
89+
"Meddy can't know the disease if there are no symptoms...",
90+
"You first have to enter some symptoms!"])
91+
else:
92+
x_test = []
93+
94+
for each in symptoms_list:
95+
if each in user_symptoms:
96+
x_test.append(1)
97+
else:
98+
x_test.append(0)
99+
100+
x_test = np.asarray(x_test)
101+
disease = prediction_model.predict(x_test.reshape(1,-1))[0]
102+
print(disease)
103+
104+
description = diseases_description.loc[diseases_description['Disease'] == disease.strip(" ").lower(), 'Description'].iloc[0]
105+
precaution = disease_precaution[disease_precaution['Disease'] == disease.strip(" ").lower()]
106+
precautions = 'Precautions: ' + precaution.Precaution_1.iloc[0] + ", " + precaution.Precaution_2.iloc[0] + ", " + precaution.Precaution_3.iloc[0] + ", " + precaution.Precaution_4.iloc[0]
107+
response_sentence = "It looks to me like you have " + disease + ". <br><br> <i>Description: " + description + "</i>" + "<br><br><b>"+ precautions + "</b>"
108+
109+
severity = []
110+
111+
for each in user_symptoms:
112+
severity.append(symptom_severity.loc[symptom_severity['Symptom'] == each.lower().strip(" ").replace(" ", ""), 'weight'].iloc[0])
113+
114+
if np.mean(severity) > 4 or np.max(severity) > 5:
115+
response_sentence = response_sentence + "<br><br>Considering your symptoms are severe, and Meddy isn't a real doctor, you should consider talking to one. :)"
116+
117+
user_symptoms.clear()
118+
severity.clear()
119+
120+
else:
121+
symptom, prob = get_symptom(sentence)
122+
print("Symptom:", symptom, ", prob:", prob)
123+
if prob > .5:
124+
response_sentence = f"Hmm, I'm {(prob * 100):.2f}% sure this is " + symptom + "."
125+
user_symptoms.add(symptom)
126+
else:
127+
response_sentence = "I'm sorry, but I don't understand you."
128+
129+
print("User symptoms:", user_symptoms)
130+
131+
return jsonify(response_sentence.replace("_", " "))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
Symptom,weight
2+
itching,1
3+
skin_rash,3
4+
nodal_skin_eruptions,4
5+
continuous_sneezing,4
6+
shivering,5
7+
chills,3
8+
joint_pain,3
9+
stomach_pain,5
10+
acidity,3
11+
ulcers_on_tongue,4
12+
muscle_wasting,3
13+
vomiting,5
14+
burning_micturition,6
15+
spotting_urination,6
16+
fatigue,4
17+
weight_gain,3
18+
anxiety,4
19+
cold_hands_and_feets,5
20+
mood_swings,3
21+
weight_loss,3
22+
restlessness,5
23+
lethargy,2
24+
patches_in_throat,6
25+
irregular_sugar_level,5
26+
cough,4
27+
high_fever,7
28+
sunken_eyes,3
29+
breathlessness,4
30+
sweating,3
31+
dehydration,4
32+
indigestion,5
33+
headache,3
34+
yellowish_skin,3
35+
dark_urine,4
36+
nausea,5
37+
loss_of_appetite,4
38+
pain_behind_the_eyes,4
39+
back_pain,3
40+
constipation,4
41+
abdominal_pain,4
42+
diarrhoea,6
43+
mild_fever,5
44+
yellow_urine,4
45+
yellowing_of_eyes,4
46+
acute_liver_failure,6
47+
fluid_overload,6
48+
swelling_of_stomach,7
49+
swelled_lymph_nodes,6
50+
malaise,6
51+
blurred_and_distorted_vision,5
52+
phlegm,5
53+
throat_irritation,4
54+
redness_of_eyes,5
55+
sinus_pressure,4
56+
runny_nose,5
57+
congestion,5
58+
chest_pain,7
59+
weakness_in_limbs,7
60+
fast_heart_rate,5
61+
pain_during_bowel_movements,5
62+
pain_in_anal_region,6
63+
bloody_stool,5
64+
irritation_in_anus,6
65+
neck_pain,5
66+
dizziness,4
67+
cramps,4
68+
bruising,4
69+
obesity,4
70+
swollen_legs,5
71+
swollen_blood_vessels,5
72+
puffy_face_and_eyes,5
73+
enlarged_thyroid,6
74+
brittle_nails,5
75+
swollen_extremeties,5
76+
excessive_hunger,4
77+
extra_marital_contacts,5
78+
drying_and_tingling_lips,4
79+
slurred_speech,4
80+
knee_pain,3
81+
hip_joint_pain,2
82+
muscle_weakness,2
83+
stiff_neck,4
84+
swelling_joints,5
85+
movement_stiffness,5
86+
spinning_movements,6
87+
loss_of_balance,4
88+
unsteadiness,4
89+
weakness_of_one_body_side,4
90+
loss_of_smell,3
91+
bladder_discomfort,4
92+
foul_smell_ofurine,5
93+
continuous_feel_of_urine,6
94+
passage_of_gases,5
95+
internal_itching,4
96+
toxic_look_(typhos),5
97+
depression,3
98+
irritability,2
99+
muscle_pain,2
100+
altered_sensorium,2
101+
red_spots_over_body,3
102+
belly_pain,4
103+
abnormal_menstruation,6
104+
dischromic_patches,6
105+
watering_from_eyes,4
106+
increased_appetite,5
107+
polyuria,4
108+
family_history,5
109+
mucoid_sputum,4
110+
rusty_sputum,4
111+
lack_of_concentration,3
112+
visual_disturbances,3
113+
receiving_blood_transfusion,5
114+
receiving_unsterile_injections,2
115+
coma,7
116+
stomach_bleeding,6
117+
distention_of_abdomen,4
118+
history_of_alcohol_consumption,5
119+
fluid_overload,4
120+
blood_in_sputum,5
121+
prominent_veins_on_calf,6
122+
palpitations,4
123+
painful_walking,2
124+
pus_filled_pimples,2
125+
blackheads,2
126+
scurring,2
127+
skin_peeling,3
128+
silver_like_dusting,2
129+
small_dents_in_nails,2
130+
inflammatory_nails,2
131+
blister,4
132+
red_sore_around_nose,2
133+
yellow_crust_ooze,3
134+
prognosis,5

0 commit comments

Comments
 (0)