File size: 10,286 Bytes
fdac493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f605843
fdac493
9c8c059
fdac493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e3edd8
fdac493
 
 
 
0161f2f
 
fdac493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import os
import random
import pickle
import tensorflow as tf
import firebase_admin
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import load_model
from firebase_admin import credentials, firestore


current_directory = os.path.dirname(__file__)
firebase_config = os.path.join(current_directory,"anxiety-test-c3553-firebase-adminsdk-5urg9-2928954445.json")
cred = credentials.Certificate(firebase_config)
if not firebase_admin._apps:
    firebase_admin.initialize_app(cred)

fs = firestore.client()

def main():
    # Create a sidebar with navigation links
    st.sidebar.title("Navigation")
    page = st.sidebar.selectbox("Select a page", ["Home", "Wellness Test"])

    if page == "Home":
        show_home_page()
    elif page == "Wellness Test":
        show_wellness_test_page()

def show_home_page():
    st.title(" Wellness Test")
    st.subheader("A Website to test your wellness")
    st.write("A Project By Wissem karous & Alaa Eddine Ayedi & Aziz Gassara")
    st.write('To Start Test, Click on the left side bar and choose Wellness Test')

def show_wellness_test_page():
    st.title("Wellness Test App")

    st.write("This app allows you to take the GAD (Generalized Anxiety Disorder), SWL (Satisfaction with Life), SPIN (Social Phobia Inventory), and answer some Personal Questions.")

    # GAD Test
    st.header("GAD Test")
    gad_questions = ["Feeling nervous, anxious or on edge?",
                     "Not being able to stop or control worrying?",
                     "Worrying too much about different things?",
                     "Trouble relaxing?",
                     "Being so restless that it's hard to sit still?",
                     "Becoming easily annoyed or irritable?",
                     "Feeling afraid as if something awful might happen"]
    gad_responses = collect_gad_responses(gad_questions)
    gad_total_score = sum(gad_responses.values())

    st.divider()
    # SWL Test
    st.header("SWL Test")
    swl_questions = ["In most ways, my life is close to my ideal.",
                     "The conditions of my life are excellent.",
                     "I am satisfied with my life.",
                     "So far, I have gotten the important things I want in life.",
                     "If I could live my life over, I would change almost nothing"]
    swl_responses = collect_swl_responses(swl_questions)
    swl_total_score = sum(swl_responses.values())

    st.divider()
    # SPIN Test
    st.header("SPIN Test")
    spin_questions = ["I avoid talking to people I don’t know.",
                      "I am afraid to speak in public.",
                      "I avoid activities in which I am the center of attention.",
                      "Being criticized scares me.",
                      "I avoid making phone calls.",
                      "I avoid parties and social events.",
                      "I avoid participating in class or at meetings.",
                      "I avoid participating in small groups.",
                      "I avoid eating with others.",
                      "I am uncomfortable writing in front of others.",
                      "I avoid talking to authority figures.",
                      "I avoid using public restrooms.",
                      "I avoid expressing disagreement with others.",
                      "I avoid talking to strangers.",
                      "I avoid eye contact with others.",
                      "I am uncomfortable talking to people in authority.",
                      "I am afraid to date or ask someone out on a date"]
    spin_responses = collect_spin_responses(spin_questions)
    spin_total_score = sum(spin_responses.values())

    st.divider()
    # Personal Questions
    st.header("Personal Questions")
    income = st.number_input("1. How much do you earn in a month?", value=0, step=1)
    age = st.number_input("2. How old are you?", value=18, step=1)
    work_options = {"Not Working" :0, "Part Time":1, "Full Time":2}
    work = st.selectbox("3. What is your employment status?", options=list(work_options.keys()))
    degree_options = {"Still in School" : 0, "Bachelor":1, "Master":2, "Doctor":3, "Professor":4}
    degree = st.selectbox("4. What is your highest degree?", options=list(degree_options.keys()))
    confidence_rating = st.slider("5. Rate your confidence when talking to somebody (1 lowest, 5 highest)", min_value=1, max_value=5, value=3)
    gender_options = {"Male": 0, "Female": 1}
    gender = st.selectbox("6. What is your gender?", options=list(gender_options.keys()))

    # Collect all answers in lists
    GAD_T = gad_total_score/21
    SWL_T = swl_total_score/25
    SPIN_T = spin_total_score/51
    GAD_T = round(GAD_T,6)
    SWL_T = round(SWL_T,6)
    SPIN_T = round(SPIN_T,6)

    all_gad_answers = list(gad_responses.values())
    all_swl_answers = list(swl_responses.values())
    all_spin_answers = list(spin_responses.values())
    all_personal_answers = [confidence_rating,income, gender_options[gender], age, work_options[work], degree_options[degree], GAD_T, SWL_T, SPIN_T]

    all_answers = all_gad_answers + all_swl_answers + all_spin_answers + all_personal_answers
    display_df = pd.DataFrame([all_answers], columns=get_feature_names())
    df = display_df.copy()

    # scaler_path = "scaler.pkl"  # Replace with the actual path to your model file
    # with open(scaler_path, 'rb') as file:
    #     data = pickle.load(file)
    #     scaler = data['scaler']
    
    # model = load_model('Anxiety_ANN_model.h5')

    # result = model.predict(df)
    # result = int(result*100)
    
    # st.write("Kemungkinan anda mengalami Anxiety sebesar : ",result,"%")
    # df = scaler.transform(df)

    st.subheader("DataFrame of Answers")
    st.dataframe(df)

    pred = st.button('Predict')

    if pred:
        # Pass the values to the prediction page
        result = predict_result(df)
        st.write("Result : ",result,"%")
        st.write("Made with <3")
        threshold = 50
        thresholded_result = 1 if result > threshold else 0
        df['Label'] = thresholded_result
        save_dataframe_to_firestore(df)


def collect_gad_responses(questions):
    # Initialize a dictionary to store responses
    responses = {}
    # Iterate through GAD questions and collect user responses
    for i, question in enumerate(questions, start=1):
        st.subheader(f"GAD{i}")
        st.write(f"**Question**: {question}")
        # Answer options for GAD
        response = st.radio(f"Select your response (GAD{i}):",
                            options=["Not at all", "Several days", "More than half the days", "Nearly every day"],
                            key=f"gad_radio_{i}")
        # Map response to a numerical value for scoring
        if response == "Not at all":
            score = 0
        elif response == "Several days":
            score = 1
        elif response == "More than half the days":
            score = 2
        else:
            score = 3
        # Store the response and score
        responses[f'gad{i}'] = score
    return responses

def collect_swl_responses(questions):
    # Initialize a dictionary to store responses
    responses = {}
    # Iterate through SWL questions and collect user responses
    for i, question in enumerate(questions, start=1):
        st.subheader(f"SWL{i}")
        st.write(f"**Question**: {question}")
        # Answer options for SWL
        response = st.radio(f"Select your response (SWL{i}):",
                            options=["Strongly Disagree", "Disagree", "Neither Agree nor Disagree", "Agree", "Strongly Agree"],
                            key=f"swl_radio_{i}")
        # Map response to a numerical value for scoring
        if response == "Strongly Disagree":
            score = 1
        elif response == "Disagree":
            score = 2
        elif response == "Neither Agree nor Disagree":
            score = 3
        elif response == "Agree":
            score = 4
        else:
            score = 5
        # Store the response and score
        responses[f'swl{i}'] = score
    return responses

def collect_spin_responses(questions):
    # Initialize a dictionary to store responses
    responses = {}
    # Iterate through SPIN questions and collect user responses
    for i, question in enumerate(questions, start=1):
        st.subheader(f"SPIN{i}")
        st.write(f"**Question**: {question}")
        # Answer options for SPIN
        response = st.radio(f"Select your response (SPIN{i}):",
                            options=["Not at all", "A little bit", "Somewhat", "Very much"],
                            key=f"spin_radio_{i}")
        # Map response to a numerical value for scoring
        if response == "Not at all":
            score = 0
        elif response == "A little bit":
            score = 1
        elif response == "Somewhat":
            score = 2
        else:
            score = 3
        # Store the response and score
        responses[f'spin{i}'] = score
    return responses

def get_feature_names():
    gad_features = [f'GAD{i}' for i in range(1, 8)]
    swl_features = [f'SWL{i}' for i in range(1, 6)]
    spin_features = [f'SPIN{i}' for i in range(1, 18)]
    personal_features = ['Narcissism','earnings','Gender','Age','Work','Degree','GAD_T', 'SWL_T', 'SPIN_T']
    return gad_features + swl_features + spin_features + personal_features

def predict_result(answers):
    scaler_path = "scaler.pkl"  # Replace with the actual path to your model file
    with open(scaler_path, 'rb') as file:
        data = pickle.load(file)
        scaler = data['scaler']
    
    model = load_model('Anxiety_ANN_model.h5')
    df = answers
    # df = scaler.transform(df)
    result = model.predict(df)
    result = int(result*100)
    return result

def save_dataframe_to_firestore(dataframe):
    # Convert DataFrame to dictionary
    data_dict = dataframe.to_dict(orient='records')

    # Add your Firestore collection and document name
    doc_ref = fs.collection("user_data").add({"data": data_dict})

    return "Successfull Write to Database"

if __name__ == "__main__":
    main()