Diff of /backend/app.py [000000] .. [55b3ec]

Switch to unified view

a b/backend/app.py
1
# Import Libraries
2
import ast
3
import pandas as pd
4
import pickle
5
from flask import Flask,request,jsonify
6
from flask_cors import CORS
7
8
# Create Flask App Object
9
app=Flask(__name__)
10
 # Allow all Domains to Access the API
11
CORS(app)
12
13
# Load the Model and Other Resources
14
with open("Trained_Classifier_Model.pkl","rb") as model_file:
15
    model=pickle.load(model_file)
16
with open("Disease_Label_Encoder.pkl","rb") as le_file:
17
    label_encoder=pickle.load(le_file)
18
with open("Disease_Mapper.pkl","rb") as mapper_file:
19
    mapper=pickle.load(mapper_file)
20
21
# Reading CSV Files
22
columns_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Column_Name_Mapping.csv")
23
description_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Description.csv")
24
precautions_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Precautions.csv")
25
diet_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Diets.csv")
26
medications_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Medications.csv")
27
doctor_df=pd.read_csv("F:\\Major-Project\\health-monitoring-system\\backend\\datasets\\Doctor.csv")
28
29
# Disease Prediction Function
30
def predict_health_status(symptoms):
31
    input_df=pd.DataFrame([[0]*376],columns=list(columns_df["values"]))
32
    for symptom in symptoms:
33
        input_df[symptom]=1
34
    predicted_label=model.predict(input_df)[0]
35
    predicted_disease=mapper[predicted_label]
36
    confidence_score=round(model.predict_proba(input_df)[0][predicted_label],5)
37
     # Check Confidence Score and Send Response Accordingly
38
    if confidence_score>=0.5:
39
        return predicted_disease,confidence_score
40
    else:
41
        return "Sorry, our model couldn't match any disease with these symptoms...",confidence_score
42
43
# Function to Fetch Details for the Predicted Disease
44
def get_disease_details(disease):
45
    # Fetch Associated Details for the Disease
46
    try:
47
        description=description_df[description_df["Disease"]==disease]["Description"].values[0]
48
        precautions=precautions_df[precautions_df["Disease"]==disease]
49
        precaution_list=[]
50
        for i in range(1,5):
51
            precaution_col=f"Precaution_{i}"
52
            precaution_value=precautions[precaution_col].values[0]
53
            precaution_list.append(precaution_value)
54
        diet=ast.literal_eval(diet_df[diet_df["Disease"]==disease]["Diet"].values[0])
55
        medications=ast.literal_eval(medications_df[medications_df["Disease"]==disease]["Medications"].values[0])
56
        consult_doctor=doctor_df[doctor_df["Disease"]==disease]["Consulted Doctor"].values[0]
57
        return{
58
            "description": description,
59
            "precautions": precaution_list,
60
            "diet": diet,
61
            "medications": medications,
62
            "consult": consult_doctor
63
        }
64
    except Exception as e:
65
        raise ValueError(f"Error in Fetching Details for the Disease : {disease}")
66
67
# Flask Route for Prediction
68
@app.route('/predict',methods=['POST'])
69
def predict():
70
    try:
71
        # Get the Data from the Frontend
72
        data=request.get_json()
73
        symptoms=data.get('symptoms',[])
74
        # Get Prediction
75
        predicted_disease,confidence_score=predict_health_status(symptoms)
76
        # If no Match Found (Confidence < 0.5)
77
        if confidence_score<0.5:
78
            return jsonify({
79
                "prediction": predicted_disease,
80
                "confidence_score": confidence_score,
81
                "message": "The Confidence Score of our Model is too low to Provide Prediction"
82
            })
83
        else:
84
            # Get Details for the Predicted Disease
85
            disease_details=get_disease_details(predicted_disease)
86
            # Prepare the Response
87
            response={
88
                "prediction": predicted_disease,
89
                "confidence_score": confidence_score,
90
                **disease_details
91
            }
92
            # Send Back the Response
93
            return jsonify(response)
94
    except ValueError as ve:
95
        return jsonify({'error': str(ve)}),400  # Handle Specific ValueError Exceptions
96
    except Exception as e:
97
        return jsonify({'error': str(e)}),500  # Handle Other General Exceptions
98
99
if __name__=='__main__':
100
    app.run(debug=True)