0% found this document useful (0 votes)
14 views8 pages

Code

Uploaded by

Tejas Mhaske
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Code

Uploaded by

Tejas Mhaske
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

app.

py

from flask import Flask, Response, render_template, request, redirect, url_for,


session
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
from flask import Flask, request, jsonify, render_template
import pandas as pd
from difflib import SequenceMatcher
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from sklearn.preprocessing import LabelEncoder
import numpy as np
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, render_template, jsonify

app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///responses.db' # Example
SQLite database URI
db = SQLAlchemy(app)

class Response(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_name = db.Column(db.String(50))
symptom_name = db.Column(db.String(50))
response_message = db.Column(db.Text)

with app.app_context():
db.create_all()

# Function to create database table


def create_table():
conn = sqlite3.connect('instance/users.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL
UNIQUE, password TEXT NOT NULL)''')
conn.commit()
conn.close()
# Create table when the application starts
create_table()

@app.route('/')
def index():
return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])


def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = sqlite3.connect('instance/users.db')
c = conn.cursor()
c.execute('INSERT INTO users (username, password) VALUES (?, ?)',
(username, generate_password_hash(password)))
conn.commit()
conn.close()

return redirect(url_for('login'))

return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])


def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

conn = sqlite3.connect('instance/users.db')
c = conn.cursor()
c.execute('SELECT * FROM users WHERE username=?', (username,))
user = c.fetchone()
conn.close()

if user is None or not check_password_hash(user[2], password):


return 'Invalid username or password. Please try again.'

session['username'] = username
return redirect(url_for('home'))

return render_template('login.html')

@app.route('/home')
def home():
if 'username' in session:
username = session['username']
return render_template('home.html', username=username)
return redirect(url_for('login'))

@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))

@app.route('/chat')
def chatbot_index():
return render_template('chatbot.html')

@app.route('/chat', methods=['POST'])
def chat():
global user_name, symptom_name, related_symptoms, current_symptom_index,
question_counter
data = request.get_json()
message = data['message'].lower()
response = ""
count=0

# Check if the last response contained prescription information


last_response = Response.query.order_by(Response.id.desc()).first()
if last_response and "Precaution" in last_response.response_message:
# Reset conversation state variables
user_name = None
symptom_name = None
related_symptoms = None
current_symptom_index = None
question_counter = 0

if not user_name:
if 'hi' in message or 'hello' in message:
count=+1
response = "Welcome to Medical Chatbot! What's your name?"
else:
response = "Sorry, I didn't get that. Could you please say 'hi' or
'hello' to begin?"
user_name = message.capitalize()
elif not symptom_name:
user_name = message.capitalize()
diseases = [
'itching', 'skin_rash', 'nodal_skin_eruptions',
'continuous_sneezing', 'shivering', 'chills',
'joint_pain','skin_peeling', 'stomach_pain','acidity','diarrhoea']
disease_list = "<ul>"
count=+1
for disease in diseases:
disease_list += f"<li>{disease}</li>"
disease_list += "</ul>"
response = f""""Welcome, {user_name}! Enter your symptom:<br><br>
Here are some common symptoms: <br>{disease_list}"""
symptom_name = message
elif related_symptoms is None:
count=+1
symptom_name = message.capitalize()
response = f"You are experiencing {symptom_name}."
related_symptoms = top_related(symptom_name)
response += f"\nRelated symptoms found: {related_symptoms}. Do you also
suffer from any of these? Say yes or no."
else:
if current_symptom_index is None:
if message.lower() == 'yes':

current_symptom_index = 0
if current_symptom_index < len(related_symptoms):
count+=1
response = f"Do you also suffer from
{related_symptoms[current_symptom_index]}? Say yes or no."
else:
count+1
prediction=predict_condition(symptom_name)
description_dict=getDescription()
ds=""
if prediction in description_dict:
ds=description_dict[prediction]
precaution=getprecautionDict()
pr=""
if prediction in precaution:
pr=precaution[prediction]
response = f"""Okay, thank you for your response:<br><br>
You May Suffer from -{prediction}<br><br>
Description - {ds}<br><br>
Precaution -{pr}<br>
"""

elif message.lower() == 'no':


count=+1
prediction=predict_condition(symptom_name)
description_dict=getDescription()
ds=""
if prediction in description_dict:
ds=description_dict[prediction]

precaution=getprecautionDict()
pr=""
if prediction in precaution:
pr=precaution[prediction]
response = f"""Okay, thank you for your response:<br><br>
You May Suffer from -{prediction}<br><br>
Description - {ds}<br><br>
Precaution - {pr}<br>
"""

else:
response = "Sorry, I didn't get that. Could you please respond
with yes or no?"
else:
if message.lower() == 'yes':
current_symptom_index += 1
if current_symptom_index < len(related_symptoms):
count=+1
response = f"Do you also suffer from
{related_symptoms[current_symptom_index]}? Say yes or no."
else:
count=+1
prediction=predict_condition(symptom_name)
description_dict=getDescription()
precaution=getprecautionDict()
ds=""
if prediction in description_dict:
ds=description_dict[prediction]
pr=""
if prediction in precaution:
pr=precaution[prediction]
response = f"""Okay, thank you for your response:<br><br>
You May Suffer from -{prediction}<br><br>
Description - {ds}<br><br>
Precaution -{pr}<br>
"""

elif message.lower() == 'no':


current_symptom_index += 1
if current_symptom_index < len(related_symptoms):
count=+1
response = f"Do you also suffer from
{related_symptoms[current_symptom_index]}? Say yes or no."
else:
count=+1
prediction=predict_condition(symptom_name)
description_dict=getDescription()
ds=""
if prediction in description_dict:
ds=description_dict[prediction]
precaution=getprecautionDict()
pr=""
if prediction in precaution:
pr=precaution[prediction]
response = f"""Okay, thank you for your response:<br><br>
You May Suffer from -{prediction}<br><br>
Description - {ds}<br><br>
Precaution -{pr}<br>
"""

else:
response = "Sorry, I didn't get that. Could you please respond
with yes or no?"

if count<=8:
response_entry = Response(user_name=user_name,
symptom_name=symptom_name, response_message=response)
db.session.add(response_entry)
db.session.commit()

return jsonify({'message': response})

# Global variables to store user's name and symptom


user_name = None
symptom_name = None
related_symptoms = None
current_symptom_index = None
question_counter = 0
# Load dataset
df = pd.read_csv("data/Training.csv")

# Load model and tokenizer


model = load_model("medical_chatbot_model.h5")
tokenizer = Tokenizer()
tokenizer.num_words = 10000
tokenizer.word_index = {'': 0}
# Extract symptom columns
symptom_columns = df.columns[:-1]
# Function to find similarity between two strings
def similar_text(a, b):
return SequenceMatcher(None, a, b).ratio()
# Function to find similarity between two strings
def similar_text(a, b):
return SequenceMatcher(None, a, b).ratio()
# Function to find top 5 related symptoms
def top_related(symptom):
similarities = [(col, similar_text(symptom, col)) for col in
symptom_columns]
similarities.sort(key=lambda x: x[1], reverse=True)
top_5 = similarities[:5]
top_5_symptoms = [symptom[0] for symptom in top_5] # Extracting only the
symptom names
return top_5_symptoms

# Function to get description of symptom


import csv
def getDescription():
description_list = {}
with open("data/symptom_Description.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
description_list[row[0]] = row[1]
return description_list

# Function to get precautions for symptom


def getprecautionDict():
precaution_dict = {}
with open("data/symptom_precaution.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
precaution_dict[row[0]] = [row[1], row[2], row[3], row[4]]
return precaution_dict

training_data = pd.read_csv("data/Training.csv")
testing_data = pd.read_csv("data/Testing.csv")
symptom_description = pd.read_csv("data/symptom_Description.csv")
symptom_severity = pd.read_csv("data/Symptom_severity.csv")
symptom_precaution = pd.read_csv("data/symptom_precaution.csv")

MAX_SEQUENCE_LENGTH = 50
VOCAB_SIZE = 10000 # Define according to your dataset
EMBEDDING_DIM = 100
NUM_CLASSES = len(training_data['prognosis'].unique())
EPOCHS = 10
BATCH_SIZE = 32
# Get the list of symptom columns
symptom_columns = ['itching', 'skin_rash', 'nodal_skin_eruptions',
'continuous_sneezing', 'shivering', 'chills', 'joint_pain', 'stomach_pain',
'acidity', 'ulcers_on_tongue', 'muscle_wasting', 'vomiting',
'burning_micturition', 'spotting_urination', 'fatigue', 'weight_gain',
'anxiety', 'cold_hands_and_feets', 'mood_swings', 'weight_loss', 'restlessness',
'lethargy', 'patches_in_throat', 'irregular_sugar_level', 'cough', 'high_fever',
'sunken_eyes', 'breathlessness', 'sweating', 'dehydration', 'indigestion',
'headache', 'yellowish_skin', 'dark_urine', 'nausea', 'loss_of_appetite',
'pain_behind_the_eyes', 'back_pain', 'constipation', 'abdominal_pain',
'diarrhoea', 'mild_fever', 'yellow_urine', 'yellowing_of_eyes',
'acute_liver_failure', 'fluid_overload', 'swelling_of_stomach',
'swelled_lymph_nodes', 'malaise', 'blurred_and_distorted_vision', 'phlegm',
'throat_irritation', 'redness_of_eyes', 'sinus_pressure', 'runny_nose',
'congestion', 'chest_pain', 'weakness_in_limbs', 'fast_heart_rate',
'pain_during_bowel_movements', 'pain_in_anal_region', 'bloody_stool',
'irritation_in_anus', 'neck_pain', 'dizziness', 'cramps', 'bruising', 'obesity',
'swollen_legs', 'swollen_blood_vessels', 'puffy_face_and_eyes',
'enlarged_thyroid', 'brittle_nails', 'swollen_extremeties', 'excessive_hunger',
'extra_marital_contacts', 'drying_and_tingling_lips', 'slurred_speech',
'knee_pain', 'hip_joint_pain', 'muscle_weakness', 'stiff_neck',
'swelling_joints', 'movement_stiffness', 'spinning_movements',
'loss_of_balance', 'unsteadiness', 'weakness_of_one_body_side', 'loss_of_smell',
'bladder_discomfort', 'foul_smell_of_urine', 'continuous_feel_of_urine',
'passage_of_gases', 'internal_itching', 'toxic_look_(typhos)', 'depression',
'irritability', 'muscle_pain', 'altered_sensorium', 'red_spots_over_body',
'belly_pain', 'abnormal_menstruation', 'dischromic_patches',
'watering_from_eyes', 'increased_appetite', 'polyuria', 'family_history',
'mucoid_sputum', 'rusty_sputum', 'lack_of_concentration', 'visual_disturbances',
'receiving_blood_transfusion', 'receiving_unsterile_injections', 'coma',
'stomach_bleeding', 'distention_of_abdomen', 'history_of_alcohol_consumption',
'fluid_overload', 'blood_in_sputum', 'prominent_veins_on_calf', 'palpitations',
'painful_walking', 'pus_filled_pimples', 'blackheads', 'scurring',
'skin_peeling', 'silver_like_dusting', 'small_dents_in_nails',
'inflammatory_nails', 'blister', 'red_sore_around_nose', 'yellow_crust_ooze']
# Check if all columns exist in the DataFrame
missing_columns = [col for col in symptom_columns if col not in
training_data.columns]
print("Missing columns:", missing_columns)
# Filter out missing columns from symptom_columns
symptom_columns = [col for col in symptom_columns if col in
training_data.columns]
# Concatenate symptom information into a new column named 'Symptoms'
training_data['Symptoms'] = training_data[symptom_columns].apply(lambda row: '
'.join(row.index[row == 1]), axis=1)
tokenizer = Tokenizer(num_words=VOCAB_SIZE)
tokenizer.fit_on_texts(training_data['Symptoms'].values)

X = tokenizer.texts_to_sequences(training_data['Symptoms'].values)
X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)
y = LabelEncoder().fit_transform(training_data['prognosis'])
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(training_data['prognosis'])

# Function to predict
def predict_condition(symptoms):
# Tokenize and pad user input
sequences = tokenizer.texts_to_sequences([symptoms])
padded_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
# Predict using the trained model
prediction = model.predict(padded_sequences)
# Decode predicted class
predicted_class = np.argmax(prediction)
# Get the corresponding medical condition label
predicted_condition = label_encoder.inverse_transform([predicted_class])[0]
return predicted_condition

if __name__ == '__main__':
app.run(debug=True)

You might also like