Code
Code
py
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()
@app.route('/')
def index():
return render_template('login.html')
return redirect(url_for('login'))
return render_template('register.html')
conn = sqlite3.connect('instance/users.db')
c = conn.cursor()
c.execute('SELECT * FROM users WHERE username=?', (username,))
user = c.fetchone()
conn.close()
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
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>
"""
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>
"""
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()
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)