Diff of /app.py [000000] .. [2629da]

Switch to unified view

a b/app.py
1
import pickle
2
from sklearn.preprocessing import LabelEncoder
3
import pandas as pd
4
import streamlit as st
5
import requests
6
from streamlit_lottie import st_lottie
7
from PIL import Image
8
9
10
st.set_page_config(page_title="Preventive Healthcare System ", page_icon="", layout="wide")
11
12
def load_lottie_url(url):
13
    r = requests.get(url)
14
    if r.status_code != 200:
15
        return None
16
    return r.json()
17
18
#Use Local CSS
19
20
21
def local_css(file_name):
22
    with open(file_name) as f:
23
        st.markdown(f"<style>{f.read()}</style>",unsafe_allow_html=True)
24
25
local_css("style/style.css")
26
27
def load_pickle_model(file_path):
28
    try:
29
        with open(file_path, 'rb') as file:
30
            model = pickle.load(file)
31
        print(f"Model loaded successfully from {file_path}")
32
        return model
33
    except FileNotFoundError:
34
        print(f"Error: The file {file_path} was not found.")
35
    except Exception as e:
36
        print(f"An error occurred while loading the model: {e}")
37
38
def get_risk_level(prob):
39
    if prob < 0.3:
40
        return "Low"
41
    elif 0.3 <= prob < 0.7:
42
        return "Moderate"
43
    else:
44
        return "High"
45
46
def generate_feedback(diabetes_prob, heart_disease_prob):
47
    feedback = {}
48
49
    # Risk assessment
50
    feedback['diabetes'] = f"Diabetes Risk: {get_risk_level(diabetes_prob)}. Probability: {diabetes_prob:.2f}"
51
    feedback['heart_disease'] = f"Heart Disease Risk: {get_risk_level(heart_disease_prob)}. Probability: {heart_disease_prob:.2f}"
52
53
    # Suggestions based on risk levels
54
    if get_risk_level(diabetes_prob) == 'High':
55
        feedback['diabetes_advice'] = "You are at a high risk for diabetes. Consider regular checkups, maintaining a balanced diet, and exercising regularly."
56
    elif get_risk_level(diabetes_prob) == 'Moderate':
57
        feedback['diabetes_advice'] = "You have a moderate risk of diabetes. It's recommended to monitor your sugar intake and stay active."
58
59
    if get_risk_level(heart_disease_prob) == 'High':
60
        feedback['heart_disease_advice'] = "You are at a high risk for heart disease. Regular cardiovascular exercise and a heart-healthy diet are recommended."
61
62
    return feedback
63
64
65
# --- Load assets ---
66
lottie_coding = load_lottie_url("https://lottie.host/d03b4e9d-a139-4df4-8f84-fb4c358891e9/gRBlHPnlpx.json")
67
img_contact_form = Image.open("images\\healthcare.webp")
68
# img_lottie_animation = Image.open("images\\pic3.jpeg")
69
70
71
# --- Header section ---
72
with st.container():
73
    st.title("Test How Healthy You Are ! ")
74
    st.title("Let's check with us ")
75
    st.write("")
76
    st.write("")
77
78
# --- What I Do ---
79
with st.container():
80
    st.write("---")
81
    left_column, right_column = st.columns(2)
82
    
83
    with left_column:
84
        st.header("AI Power Predictive healthcare System ")
85
        st.write("##")
86
        st.write("""
87
            An AI-powered solution that proactively identifies individuals at risk
88
of developing chronic diseases such as diabetes, heart disease, or obesity.
89
The system should provide personalized recommendations for preventive
90
care based on genetic, lifestyle, and medical data.
91
        """)
92
        
93
94
    with right_column:
95
        st_lottie(lottie_coding, height=300, key="coding")
96
97
#---services---
98
99
with st.container():
100
    st.write("---")
101
    st.header("Our Services")
102
    st.write("##")
103
    image_column, text_column = st.columns((1, 2))
104
    # image_column,text_column=st.columns((1,2))
105
    with image_column:
106
        st.image(img_contact_form)
107
    with text_column:
108
        st.subheader("We Specialize In Managing Chronic Diseases and Promoting Healthy Lifestyles")
109
        st.write(
110
            """
111
            Our healthcare services focus on helping you manage and prevent chronic diseases while promoting a healthy lifestyle. Our areas of specialization include:
112
            - **Diabetes Management**: Comprehensive care to monitor and control blood sugar levels.
113
            - **Heart Disease Prevention**: Lifestyle recommendations and medical interventions to reduce heart disease risk.
114
            - **Obesity Management**: Personalized plans to achieve and maintain a healthy weight.
115
            - **Lifestyle Modifications**: Guidance on exercise, diet, and wellness to promote overall health and well-being.
116
            """
117
        )
118
119
120
121
    
122
#     with text_column:
123
#         st.subheader("Integrate lottie animations inside your streamlit app")
124
#         st.write(
125
#             """
126
#              jhxsyfdahF
127
#              HDJGhfkhFyyfTF
128
#              IJHDGGFDyJFklgj
129
#              HDYUGFEUHF
130
#              JgdfdHKD
131
#              gwyuqwjkJdgd
132
133
#             """
134
#         )    
135
#         st.markdown("[Watch Video...](https://youtu.be/TXS0itGoINE)")
136
137
# ---container---
138
139
# with st.container():
140
#     st.write("---")
141
#     st.header("Get in Touch with us")
142
#     st.write("#")
143
144
#     contact_form="""
145
146
#     <form action="https://formsubmit.co/nimishajain2206@email.com" method="POST">
147
#     <input type ="hidden " name ="_captcha" value="">
148
#      <input type="text" name="name" palceholder ="Your Name"required>
149
#      <input type="email" name="email" placeholder ="Your Email" required>
150
#      <textarea name ="message " placeholder ="Your message here" required></textarea>
151
#      <button type="submit">Send</button>
152
#     </form>
153
#                  """
154
    
155
#     left_column,right_column=st.columns(2)
156
#     with left_column:
157
#         st.markdown(contact_form,unsafe_allow_html=True)
158
#     with right_column:
159
#         st.empty()
160
    
161
162
lbl_encoders = load_pickle_model('model\\label_encoders.pkl')
163
lr_dt = load_pickle_model('model\\lr_dt.pkl')
164
lr_ht = load_pickle_model('model\\lr_ht.pkl')
165
lr_ob = load_pickle_model('model\\lr_ob.pkl')
166
167
# Define categorical columns
168
categorical_columns = ['General_Health', 'Checkup', 'Exercise', 'Depression', 
169
                       'Arthritis', 'Sex', 'Age_Category', 'Smoking_History']
170
171
# Define the columns
172
columns = ['General_Health', 'Checkup', 'Exercise', 'Depression', 'Arthritis', 
173
           'Sex', 'Age_Category', 'Height_(cm)', 'Weight_(kg)', 'BMI', 
174
           'Smoking_History', 'Alcohol_Consumption', 'Fruit_Consumption', 
175
           'Green_Vegetables_Consumption', 'FriedPotato_Consumption']
176
177
# Create the form in Streamlit
178
st.title("Health Data Prediction Form")
179
180
with st.form(key="input_form"):
181
    # Collect input values from the user
182
    general_health = st.selectbox('General Health', ['Poor', 'Fair', 'Good', 'Very Good', 'Excellent'])
183
    checkup = st.selectbox('Checkup', ['Within the past year', 'Within the past 2 years', '5 or more years ago', 'Never'])
184
    exercise = st.selectbox('Exercise', ['Yes', 'No'])
185
    depression = st.selectbox('Depression', ['Yes', 'No'])
186
    arthritis = st.selectbox('Arthritis', ['Yes', 'No'])
187
    sex = st.selectbox('Sex', ['Male', 'Female'])
188
    age_category = st.selectbox('Age Category', ['18-24', '25-29', '30-34', '35-39', '40-44', '45-49', '50-54', 
189
                                                 '55-59', '60-64', '65-69', '70-74', '75-79', '80 or older'])
190
    height = st.number_input('Height (cm)', min_value=100.0, max_value=250.0, step=1.0)
191
    weight = st.number_input('Weight (kg)', min_value=20.0, max_value=200.0, step=0.1)
192
    bmi = st.number_input('BMI', min_value=10.0, max_value=60.0, step=0.1)
193
    smoking_history = st.selectbox('Smoking History', ['Yes', 'No'])
194
    alcohol_consumption = st.number_input('Alcohol Consumption', min_value=0.0, max_value=100.0, step=0.1)
195
    fruit_consumption = st.number_input('Fruit Consumption (grams/day)', min_value=0.0, max_value=500.0, step=1.0)
196
    green_vegetables_consumption = st.number_input('Green Vegetables Consumption (grams/day)', min_value=0.0, max_value=500.0, step=1.0)
197
    fried_potato_consumption = st.number_input('Fried Potato Consumption (grams/day)', min_value=0.0, max_value=500.0, step=1.0)
198
199
    # Submit button
200
    submit_button = st.form_submit_button(label="Submit")
201
202
if submit_button:
203
    # Define the input values
204
    input_values = {
205
        'General_Health': general_health,
206
        'Checkup': checkup,
207
        'Exercise': exercise,
208
        'Depression': depression,
209
        'Arthritis': arthritis,
210
        'Sex': sex,
211
        'Age_Category': age_category,
212
        'Height_(cm)': height,
213
        'Weight_(kg)': weight,
214
        'BMI': bmi,
215
        'Smoking_History': smoking_history,
216
        'Alcohol_Consumption': alcohol_consumption,
217
        'Fruit_Consumption': fruit_consumption,
218
        'Green_Vegetables_Consumption': green_vegetables_consumption,
219
        'FriedPotato_Consumption': fried_potato_consumption
220
    }
221
222
    # Create a DataFrame from the input values
223
224
    input_df = pd.DataFrame([input_values])
225
226
    # Encode categorical columns using the stored LabelEncoders
227
    for column in categorical_columns:
228
        if column in input_df.columns:
229
            input_df[column] = lbl_encoders[column].transform(input_df[column].astype(str))
230
231
    # Display the input DataFrame after encoding
232
    # st.write("Encoded Input DataFrame:")
233
    # st.write(input_df)
234
235
    # Predict using the model
236
    pred_dt = lr_dt.predict_proba(input_df)[0]
237
    pred_ht = lr_ht.predict_proba(input_df)[0]
238
    pred_ob = lr_ob.predict(input_df)
239
    print(pred_dt)
240
    print(pred_ht)
241
    print(pred_ob)
242
243
    # Display the prediction result
244
    st.write(f"Diabetes: {pred_dt[0]}")
245
    st.write(f"Hearts Decises: {pred_ht[0]}")
246
    st.write(f"Obesitiy: {pred_ob[0]}")
247
    st.title("Health Risk Assessment")
248
    feedback = feedback = generate_feedback(pred_dt[0], pred_ht[0])
249
250
    # Display the feedback
251
    for key, value in feedback.items():
252
        st.write(value)
253
254