-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
871 lines (671 loc) · 34.1 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
from flask import Flask, render_template, request, session, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import pandas as pd
from fuzzywuzzy import process
from sklearn.feature_extraction.text import CountVectorizer
import joblib
import os
from datetime import datetime
import random
from sklearn.preprocessing import LabelEncoder
import re
import numpy as np
import pickle
app = Flask(__name__)
app.secret_key = 'your_secret_key'
last_two_messages=[]
lastt_two_messages=[]
Selected_disease=""
print(Selected_disease)
# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///meditrain.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# Database models
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
age = db.Column(db.Integer, nullable=False)
gender = db.Column(db.String(10), nullable=False)
location = db.Column(db.String(100), nullable=False)
country = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
contact = db.Column(db.String(15), nullable=False)
password = db.Column(db.String(100), nullable=False)
class DocRecord(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
date = db.Column(db.Text, nullable=False)
time = db.Column(db.Text, nullable=False)
symptoms = db.Column(db.Text, nullable=False)
disease = db.Column(db.String(100), nullable=False)
class PatRecord(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
date = db.Column(db.Text, nullable=False)
time = db.Column(db.Text, nullable=False)
symptoms = db.Column(db.Text, nullable=False)
disease = db.Column(db.String(100), nullable=False)
accuracy=db.Column(db.Integer, nullable=False)
# Routes
@app.route('/')
def home():
session.clear()
return render_template('home.html')
@app.route('/lpage')
def lpage():
return render_template('login.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
session['role']=request.form['role']
user = User.query.filter_by(email=email, password=password).first()
if user:
session['pid'] = user.id
session['name'] = user.name
session["age"]=user.age
session["gender"]=user.gender
session["location"]=user.location
session["country"]=user.country
session["email"]=user.email
session["contact"]=user.contact
role=session.get('role')
if role=='Patient':
return redirect(url_for('index'))
elif role=='Doctor':
return redirect(url_for('pindex'))
else:
flash('Invalid email or password', 'danger')
return redirect(url_for('lpage'))
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
try:
user = User(
name=request.form['name'],
age=request.form['age'],
gender=request.form['gender'],
location=request.form['location'],
country=request.form['country'],
email=request.form['email'],
contact=request.form['contact'],
password=request.form['password']
)
db.session.add(user)
db.session.commit()
flash('Registration successful', 'success')
return redirect(url_for('lpage'))
except:
flash('Error during registration', 'danger')
return redirect(url_for('lpage'))
return render_template('register.html')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
@app.route("/chat")
def index():
session['var']=2
user_name = session.get('name', 'Guest')
return render_template('chat.html',user_name=user_name)
@app.route("/get", methods=["GET", "POST"])
def chat():
global last_two_messages
if 'var' not in session:
session['var'] = 2
if session['var'] == 1:
session['var'] = 2 # Proceed to the next step
else:
msg = request.form["msg"]
last_two_messages.append(msg)
aabb=last_two_messages[-2:]
combined_messages = ",".join(aabb)
input = combined_messages
print(input)
return get_Chat1_response(input)
def get_Chat1_response(text):
#Step 1 getting input or symptoms from user
reprompt="By the way, do you have any other symptoms you'd like to mention? Anything else that's been bothering you lately?"
user_input=text
#step 2 user NER to extract the symptoms from user
# Step 2.1: Load symptoms from CSV (make sure it only contains the desired symptoms)
dataset_directory = os.path.join(os.getcwd(), 'static', 'dataset') # Assuming this is relative to the current script
csv_path = os.path.join(dataset_directory, 'unique_symptoms.csv')
df = pd.read_csv(csv_path) # Replace with the path to your CSV file
symptoms_list = df['Symptom'].dropna().tolist() # Extract symptoms into a list
# Step 2.2: Function to generate n-grams (bigrams)
def generate_ngrams(text, n=2):
"""Generate n-grams from text."""
vectorizer = CountVectorizer(ngram_range=(n, n), stop_words='english')
ngrams = vectorizer.fit_transform([text])
ngrams_list = vectorizer.get_feature_names_out()
return ngrams_list
# Step 2.3: Function to extract symptoms using fuzzy matching and n-grams
def extract_symptoms_from_input(user_input):
"""
Function to extract symptoms from user input using fuzzy matching and n-grams.
Returns a string of matched symptoms, separated by commas.
"""
try:
# Normalize input text
user_input = user_input.lower().strip()
# Generate bigrams from the user input
user_input_bigrams = generate_ngrams(user_input)
# List to store matched symptoms
matched_symptoms = []
for symptom in symptoms_list:
# Check if the symptom directly matches any bigram
if symptom.lower() in user_input:
matched_symptoms.append(symptom)
else:
# Use fuzzy matching to allow for misspellings or slight variations
match = process.extractOne(symptom.lower(), user_input_bigrams)
if match and match[1] >= 80: # Adjust threshold as needed
matched_symptoms.append(symptom)
# Post-processing: Optional, for more fine-tuning, e.g., removing irrelevant matches.
# Return the matched symptoms as a single string, joined by commas
return ', '.join(matched_symptoms)
except ValueError as e:
# Handle the error gracefully and return a message or empty string
return ""
# Example usage:
user_input = user_input
extracted_symptoms = extract_symptoms_from_input(user_input)
#Step 3 using disease prediction model (custom build with logistic Regression ) to diagonise the disease using symptoms
# Load the saved Logistic Regression model
model_directory = os.path.join(os.getcwd(), 'static', 'model') # Assuming this is relative to the current script
m1_path = os.path.join(model_directory, 'logistic_regression_model.pkl')
v1_path = os.path.join(model_directory, 'tfidf_vectorizer.pkl')
e1_path = os.path.join(model_directory, 'label_encoder.pkl')
loaded_model = joblib.load(m1_path)
# Load the saved TF-IDF vectorizer
loaded_vectorizer = joblib.load(v1_path)
# Load the saved LabelEncoder (if not already loaded)
label_encoder = joblib.load(e1_path)
# Example of using the loaded model for prediction
sample_input = extracted_symptoms
sample_tfidf = loaded_vectorizer.transform([sample_input]) # Transform input using TF-IDF
# Predict the disease label
predicted_label = loaded_model.predict(sample_tfidf)
# Decode the predicted label to get the actual disease name(s)
predicted_disease = label_encoder.inverse_transform(predicted_label)
# Output the predicted disease as a string
predicted_disease_string = predicted_disease[0] # Since there's only one prediction, we get the first one
#Step 4 using treatment paln model (custom made with logistic Regression ) to suggest a treatmnent plan for the diagnized disease
m2_path = os.path.join(model_directory, 'treatment_prediction_model.joblib')
v2_path = os.path.join(model_directory, 'vectorizer.joblib')
loaded_model = joblib.load(m2_path)
loaded_vectorizer = joblib.load(v2_path)
# Get the disease input as a string
sample_disease = predicted_disease_string
# Transform the input disease using the loaded vectorizer
sample_disease_tfidf = loaded_vectorizer.transform([sample_disease])
# Predict the treatment using the loaded model
predicted_precaution = loaded_model.predict(sample_disease_tfidf)
# Handle multi-output predictions for a single input (list of lists)
predicted_precautions = predicted_precaution[0]
# Output the result with each precaution on a new line
i = 1
precaution_list = [] # List to store the formatted precautions
for precaution in predicted_precautions:
precaution_list.append(f" {i}. {precaution.strip()}")
i += 1
# Combine all precautions into a single string with line breaks
str7 = "\n".join(precaution_list)
final_message = (
f"Hello there, I’m really sorry to hear that you're feeling unwell. After reviewing your symptoms, it seems you may be dealing with '{predicted_disease_string}'.\n"
"I understand this might be worrying, but please know that we can take steps together to help you feel better. 😊💪\n\n"
"Please follow the following steps to feel better and work towards your recovery:\n"
f"{str7}\n\n" # Assuming str7 is already defined with precaution steps
"Remember, recovery takes time, but you're not alone in this journey. Stay positive! 🌟\n\n"
"If you continue to feel worse even after following the prescribed treatment, please don't hesitate to reach out to our medical expert or visit your nearest hospital. Your health is our top priority, and we want to ensure you receive the care you need. Take care, and feel free to contact us if you need further assistance. 🏥💬\n\n"
)
thank="Thank you for trusting us with your health. We are always here for you, anytime you need. Serving you is a privilege to us, and we are just a reach-out away. 🙏💙"
sorry = "Sorry, but based on the information you've provided, I am unable to provide a diagnosis at this time. 😕\n" \
"To ensure that I can give you a more accurate and helpful response, please create a new chat and provide additional details about your symptoms. 💬\n" \
"Your health is important, and I want to make sure I can help as much as possible.💪\n Don't hesitate to include any changes you've noticed in your condition or any other details that might be important. 🩺\n" \
"Thank you for understanding, and I look forward to assisting you further once you've provided more symptoms! 🙏"
if session['var'] == 2:
session['var'] = 3
return reprompt
elif session['var'] == 3:
session['var'] = 4
if not extracted_symptoms.strip():
print("Debug: No symptoms extracted. Returning 'sorry' message.")
return sorry
else:
user = session.get('name', 'Guest')
if user!='Guest':
now = datetime.now()
date = now.strftime("%d-%m-%Y") # Custom date format
time = now.strftime("%H:%M")
sympt = extracted_symptoms.replace("_", " ")
dis=predicted_disease_string
p=session.get('pid')
new_record = DocRecord(
user_id=p,
date=date,
time=time,
symptoms=sympt,
disease=dis
)
db.session.add(new_record)
db.session.commit()
return final_message
elif session['var'] == 4:
session['var'] = 5 # Or reset to 1 depending on your flow
return thank
else:
session['var'] = 2
@app.route("/pchat")
def pindex():
global Selected_disease
session['var1']=2
Selected_disease=random_disease()
user_name = session.get('name', 'Guest')
return render_template('pchat.html',user_name=user_name)
def random_disease():
dataset_directory = os.path.join(os.getcwd(), 'static', 'dataset') # Assuming this is relative to the current script
dcsv_path = os.path.join(dataset_directory, 'disease.csv')
df = pd.read_csv(dcsv_path)
disease_list = df['Disease'].dropna().tolist()
Selected_disease = random.choice(disease_list)
print(f"Selected Disease: {Selected_disease}")
return Selected_disease
@app.route("/pget", methods=["GET", "POST"])
def pchat():
global lastt_two_messages
global Selected_disease
if 'var1' not in session:
session['var1'] = 2
if session['var1']:
msg = request.form["msg"]
print(msg)
lastt_two_messages.append(msg)
aabb=lastt_two_messages[-2:]
combined_messages = ",".join(aabb)
input = combined_messages
print(input)
#Step 1 getting input or symptoms from user
disease=Selected_disease
return get_Chat2_response(input,disease)
def get_Chat2_response(text,disease):
Selected_disease=disease
dataset_directory = os.path.join(os.getcwd(), 'static', 'dataset') # Assuming this is relative to the current script
dcsv_path = os.path.join(dataset_directory, 'disease.csv')
model_directory = os.path.join(os.getcwd(), 'static', 'model') # Assuming this is relative to the current script
m1_path = os.path.join(model_directory, 'logistic_regression222_model.pkl')
v1_path = os.path.join(model_directory, 'tfidf222_vectorizer.pkl')
# Load the saved Logistic Regression model
loaded_model = joblib.load(m1_path)
# Load the saved TF-IDF vectorizer
loaded_vectorizer = joblib.load(v1_path)
# Load the CSV dataset for symptoms and diseases (same as training data)
scsv_path = os.path.join(dataset_directory, 'symptoms.csv')
df = pd.read_csv(scsv_path)
# Check if 'Disease_Label' exists in the DataFrame
if 'Disease_Label' not in df.columns:
# If the 'Disease_Label' doesn't exist, encode the disease labels
label_encoder = LabelEncoder()
df['Disease_Label'] = label_encoder.fit_transform(df['Disease'])
# Function to predict symptoms for a given disease
def get_symptoms_for_disease(disease_name):
# Encode disease name to its label (using LabelEncoder from the training process)
disease_label = label_encoder.transform([disease_name])[0] # Get the encoded label
# Filter dataset to find symptoms for the given disease label
disease_data = df[df['Disease_Label'] == disease_label]
if disease_data.empty:
return f"No data found for disease: {disease_name}"
# Get symptoms associated with the given disease
symptoms = disease_data['Symptoms'].values[0]
symptom_1 = disease_data['symptom 1'].values[0]
return symptoms, symptom_1
# Example of how to use the function
disease_name = Selected_disease # User provides the disease name
result, symptom_1 = get_symptoms_for_disease(disease_name)
# Print the symptoms associated with the disease
patient=result
print(patient)
s=session.get('var1')
print(s)
symot=symptom_1
dis = Selected_disease # Input disease name
# Load the saved model and vectorizer# Assuming this is relative to the current script
m2_path = os.path.join(model_directory, 'enhanced_treatment_prediction_model.joblib')
v2_path = os.path.join(model_directory, 'enhanced_vectorizer.joblib')
loaded_model = joblib.load(m2_path)
loaded_vectorizer = joblib.load(v2_path)
# Transform the input disease using the loaded vectorizer
sample_disease_tfidf = loaded_vectorizer.transform([dis])
# Predict the treatment using the loaded model
predicted_precautions = loaded_model.predict(sample_disease_tfidf)
# Initialize a list to store the predicted precautions
predicted_precaution_list = []
# Extract precautions from the prediction
for precaution_index, precaution in enumerate(predicted_precautions[0], start=1):
# Ensure no leading/trailing spaces and handle cases of empty strings
if precaution.strip():
predicted_precaution_list.append(f"{precaution.strip()}")
# Output the result as a list
print(f"Predicted treatments for '{dis}':", predicted_precaution_list)
user=text
# Step 1: Load symptoms from CSV (make sure it only contains the desired symptoms)
df = pd.read_csv(dcsv_path) # Replace with the path to your CSV file
disease_list = df['Disease'].dropna().tolist() # Extract symptoms into a list
ucsv_path = os.path.join(dataset_directory, 'unique_treatments.csv')
dff = pd.read_csv(ucsv_path) # Replace with the path to your CSV file
treatment_list = dff['Treatment'].dropna().tolist() # Extract symptoms into a list
# Step 2: Function to generate n-grams (bigrams)
def generate_ngrams(text, n=2):
"""Generate n-grams from text."""
vectorizer = CountVectorizer(ngram_range=(n, n), stop_words='english')
ngrams = vectorizer.fit_transform([text])
ngrams_list = vectorizer.get_feature_names_out()
return ngrams_list
# Step 3: Function to extract symptoms using fuzzy matching and n-grams
def extract_disease_from_input(user_input):
# Normalize input text
user_input = user_input.lower().strip()
# Generate bigrams from the user input
user_input_bigrams = generate_ngrams(user_input)
# List to store matched disease
matched_disease = []
for disease in disease_list:
# Check if the disease directly matches any bigram
if disease.lower() in user_input:
matched_disease.append(disease)
else:
# Use fuzzy matching to allow for misspellings or slight variations
match = process.extractOne(disease.lower(), user_input_bigrams)
if match and match[1] >= 95: # Adjust threshold as needed
matched_disease.append(disease)
# Post-processing: Optional, for more fine-tuning, e.g., removing irrelevant matches.
matched_disease = list(set(matched_disease)) # Remove duplicates
# Return the matched disease as a single string, joined by commas
return ', '.join(matched_disease)
def extract_treatment_from_input(user_input):
# Normalize input text
user_input = user_input.lower().strip()
# Generate bigrams from the user input
user_input_bigrams = generate_ngrams(user_input)
# List to store matched treatment
matched_treatments = []
for treatment in treatment_list:
# Check if the treatment directly matches any bigram
if treatment.lower() in user_input:
matched_treatments.append(treatment)
else:
# Use fuzzy matching to allow for misspellings or slight variations
match = process.extractOne(treatment.lower(), user_input_bigrams)
if match and match[1] >= 90: # Adjust threshold as needed
matched_treatments.append(treatment)
# Post-processing: Optional, for more fine-tuning, e.g., removing irrelevant matches.
matched_treatments = list(set(matched_treatments)) # Remove duplicates
# Return the matched symptoms as a single string, joined by commas
return matched_treatments
try:
# Example usage:
user_input = user
extracted_disease = extract_disease_from_input(user_input)
extracted_treatment = extract_treatment_from_input(user_input)
print("Extracted Disease:", extracted_disease)
print("Extracted Treatment:", extracted_treatment)
accuracy_score = 0
treatment_match_count = 0
# Check if the extracted disease matches the selected disease
if Selected_disease == extracted_disease:
accuracy_score += 70 # Award 70 points for correct disease identification
# Check for matching treatments
for predicted_treatment in predicted_precaution_list:
for extracted_treat in extracted_treatment:
if predicted_treatment == extracted_treat:
treatment_match_count += 1
# Award 30 points if at least one treatment matches
if treatment_match_count >= 1:
accuracy_score += 30
else:
accuracy_score = 0 # No points if disease doesn't match
# Output the results
final=(f"Thank you Doctor for diagnosing and suggesting treatments for me. I am happy to share your accuracy.\nYour accuracy is about {accuracy_score}.")
print(final)
except Exception as e:
# Handle exceptions and set accuracy score to 0
print("An error occurred:", str(e))
accuracy_score = 0
final=(f"Thank you Doctor for diagnosing and suggesting treatments for me. I am happy to share your accuracy.\nYour accuracy is about {accuracy_score}.")
print(final)
if session['var1'] == 2:
session['var1'] = 3
print("returning patient")
return patient
elif session['var1'] == 3:
session['var1'] = 4
user = session.get('name', 'Guest')
if user!='Guest':
now = datetime.now()
date = now.strftime("%d-%m-%Y") # Custom date format
time = now.strftime("%H:%M")
sympt = symot
dis=extracted_disease
p=session.get('pid')
ac=accuracy_score
new_record = PatRecord(
user_id=p,
date=date,
time=time,
symptoms=sympt,
disease=dis,
accuracy=ac
)
db.session.add(new_record)
db.session.commit()
return final
else:
session['var1'] = 2
@app.route("/profile")
def profile():
user_name = session.get('name', 'Guest')
print(user_name)
if user_name=='Guest':
flash("You must login to access your Profile","danger")
return redirect(url_for("lpage"))
else:
role=session.get('role')
if role=='Patient':
gen=session.get('gender')
if gen=="Male":
ren="https://www.freeiconspng.com/uploads/male-icon-32.png"
else:
ren="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXSTblEVkkdJh15jlAbC3FpvuzCKb1o-pQQA&s"
pdata = {
"patient_id": session.get('pid'),
"name": session.get('name'),
"age": session.get('age'),
"gender": session.get('gender'),
"country": session.get('country'),
"contact": session.get('contact'),
"email": session.get('email'),
"location": session.get('location'),
"image":ren,
"role":"Doctor",
"url":url_for('index'),
"roleas":role
}
headings=("Date","Time","Symptoms","Diagonised Disesase")
patient_id = session.get('pid')
# Query the records table using SQLAlchemy ORM
records = DocRecord.query.filter_by(user_id=patient_id).all()
rows = [(record.date, record.time, record.symptoms, record.disease) for record in records]
data = tuple((row[0], row[1], row[2], row[3]) for row in rows)
return render_template('profile.html',pdata=pdata,data=data,headings=headings)
elif role=='Doctor':
gen=session.get('gender')
if gen=="Male":
ren="https://www.freeiconspng.com/uploads/male-icon-32.png"
else:
ren="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXSTblEVkkdJh15jlAbC3FpvuzCKb1o-pQQA&s"
pdata = {
"patient_id": session.get('pid'),
"name": session.get('name'),
"age": session.get('age'),
"gender": session.get('gender'),
"country": session.get('country'),
"contact": session.get('contact'),
"email": session.get('email'),
"location": session.get('location'),
"image":ren,
"role":"Patient",
"url":url_for('pindex'),
"roleas":role
}
headings=("Date","Time","Symptoms","Diagonised Disesase","Accuracy Score")
patient_id = session.get('pid')
# Query the records table using SQLAlchemy ORM
records = PatRecord.query.filter_by(user_id=patient_id).all()
rows = [(record.date, record.time, record.symptoms, record.disease,record.accuracy) for record in records]
data = tuple((row[0], row[1], row[2], row[3],row[4]) for row in rows)
return render_template('profile.html',pdata=pdata,data=data,headings=headings)
@app.route('/diabetes')
def diabetes():
return render_template('diabetes.html') # Or any content you want to display
@app.route('/heartdisease')
def heartdisease():
return render_template('heart_disease.html')
@app.route('/alzheimer')
def alzheimer():
return render_template('alzheimer.html')
@app.route('/predict', methods=['POST'])
def predict():
try:
# Load the diabetes classifier model
model_directory = os.path.join(os.getcwd(), 'static', 'model') # Assuming this is relative to the current script
d1_path = os.path.join(model_directory, 'diabetes.pkl')
diabetes_classifier = joblib.load(d1_path)
if request.method == 'POST':
# Get input values from the form
glucose = int(request.form.get('glucose', 0))
bp = int(request.form.get('bloodpressure', 0))
st = int(request.form.get('skinthickness', 0))
insulin = int(request.form.get('insulin', 0))
bmi = float(request.form.get('bmi', 0))
dpf = float(request.form.get('dpf', 0))
age = int(request.form.get('age', 0))
# Prepare data for prediction
data = np.array([[glucose, bp, st, insulin, bmi, dpf, age]])
data=data.reshape(1, -1)
# Make the prediction
my_prediction = diabetes_classifier.predict(data)
# Interpret the prediction
if my_prediction[0] == 0:
output = "No Diabetes"
else:
output = "Diabetes"
# Render the template with the result
return render_template('diabetes.html', prediction_text="Result: {}".format(output))
except FileNotFoundError:
return "Model file not found. Please ensure 'voting_diabetes.pkl' is in the 'model/' directory.", 500
except Exception as e:
return f"An error occurred: {str(e)}", 500
# heart disease
@app.route('/heart_predict', methods=['POST'])
def heart_predict():
model_directory = os.path.join(os.getcwd(), 'static', 'model') # Assuming this is relative to the current script
h1_path = os.path.join(model_directory, 'hdp_model.pkl')
heartmodel = joblib.load(h1_path)
try:
# Debug: Print received form data keys
# print("Form keys received:", request.form.keys())
# Collect form data
age = int(request.form['age'])
sex = int(request.form['sex'])
cp = int(request.form['cp'])
trestbps = int(request.form['trestbps'])
chol = int(request.form['chol'])
fbs = int(request.form['fbs'])
restecg = int(request.form['restecg'])
thalach = int(request.form['thalach'])
exang = int(request.form['exang'])
oldpeak = float(request.form['oldpeak'])
slope = int(request.form['slope'])
ca = int(request.form['ca'])
thal = int(request.form['thal'])
# Prepare the input data for prediction
input_data = np.array([[age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal]])
# Make prediction
prediction = heartmodel.predict(input_data)[0]
# Map prediction to a human-readable result
result = "High risk of heart disease" if prediction == 1 else "Low risk of heart disease"
return render_template('heart_disease.html', prediction=result)
except Exception as e:
return render_template('heart_disease.html', prediction=f"An error occurred: {e}")
# Alzheimer disease
APOE_CATEGORIES = ['APOE Genotype_2,2', 'APOE Genotype_2,3', 'APOE Genotype_2,4',
'APOE Genotype_3,3', 'APOE Genotype_3,4', 'APOE Genotype_4,4']
PTHETHCAT_CATEGORIES = ['PTETHCAT_Hisp/Latino', 'PTETHCAT_Not Hisp/Latino', 'PTETHCAT_Unknown']
IMPUTED_CATEGORIES = ['imputed_genotype_True', 'imputed_genotype_False']
PTRACCAT_CATEGORIES = ['PTRACCAT_Asian', 'PTRACCAT_Black', 'PTRACCAT_White']
PTGENDER_CATEGORIES = ['PTGENDER_Female', 'PTGENDER_Male']
APOE4_CATEGORIES = ['APOE4_0', 'APOE4_1', 'APOE4_2']
ABBREVIATION = {
"AD": "Alzheimer's Disease ",
"LMCI": "Late Mild Cognitive Impairment ",
"CN": "Cognitively Normal"
}
CONDITION_DESCRIPTION = {
"AD": "This indicates that the individual's data aligns with characteristics commonly associated with "
"Alzheimer's disease. Alzheimer's disease is a progressive neurodegenerative disorder that affects "
"memory and cognitive functions.",
"LMCI": "This suggests that the individual is in a stage of mild cognitive impairment that is progressing "
"towards Alzheimer's disease. Mild Cognitive Impairment is a transitional state between normal "
"cognitive changes of aging and more significant cognitive decline.",
"CN": "This suggests that the individual has normal cognitive functioning without significant impairments. "
"This group serves as a control for comparison in Alzheimer's research."
}
# convert selected category into one-hot encoding
def convert_to_one_hot(selected_category, all_categories, user_input):
one_hot = [1 if category == selected_category else 0 for category in all_categories]
user_input.extend(one_hot)
model_directory = os.path.join(os.getcwd(), 'static', 'model') # Assuming this is relative to the current script
a1_path = os.path.join(model_directory, 'alzheimer_model.pkl')
alzheimer_model = joblib.load(a1_path)
def alzheimer_predict(input_data):
predictions = alzheimer_model.predict(input_data)
return predictions
@app.route('/alzheimer_predict', methods=['POST'])
def alzheimer_disease_predict():
# Extract data from the form
age = int(request.form['age'])
education = int(request.form['education'])
mmse = int(request.form['mmse'])
gender = request.form['gender']
ethnicity = request.form['ethnicity']
race_cat = request.form['race']
apoe_allele_type = request.form['apoe_allele']
apoe_genotype = request.form['apoe_genotype']
imputed_genotype = request.form['imputed_genotype']
# Initialize user input list
user_input = [age, education, mmse]
# Convert categorical fields to one-hot encoding
convert_to_one_hot("PTRACCAT_" + race_cat, PTRACCAT_CATEGORIES, user_input)
convert_to_one_hot("APOE Genotype_" + apoe_genotype, APOE_CATEGORIES, user_input)
convert_to_one_hot("PTETHCAT_" + ethnicity, PTHETHCAT_CATEGORIES, user_input)
convert_to_one_hot(apoe_allele_type, APOE4_CATEGORIES, user_input)
convert_to_one_hot("PTGENDER_" + gender, PTGENDER_CATEGORIES, user_input)
convert_to_one_hot("imputed_genotype_" + imputed_genotype, IMPUTED_CATEGORIES, user_input)
# Convert user input into a DataFrame
input_df = pd.DataFrame([user_input])
# Make prediction
predicted_condition = alzheimer_predict(input_df)
# Prepare the result
result = {
"predicted_condition": f"{ABBREVIATION[predicted_condition[0]]} ({predicted_condition[0]}) - {CONDITION_DESCRIPTION[predicted_condition[0]]}"
}
# Return the template with the result
return render_template('alzheimer.html', result=result)
if __name__ == '__main__':
app.run(debug=True,port=9999)