File size: 13,158 Bytes
edc3e39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import pickle 
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
import sklearn 
import pickle 

import joblib as jb

import xgboost as xgb

# Esconder os menu padrao
hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True) 


 # pipreqs . --force
 # cat requirements.txt
 # pip install -r requirements.txt

# DICIONARIO DE DADOS - ATRIBUTOS
# HeartDisease: Entrevistados que já relataram ter doença cardíaca coronária ou infarto do miocárdio.
#
# BMI: IMC.
# Smoking : Você fumou pelo menos 100 cigarros em toda a sua vida?
# AlcoholDrinking: Bebedores pesados.
# Stroke: Você teve um derrame?
# PhysicalHealth: Sua saúde física, que inclui doenças físicas e lesões, por quantos dias, nos últimos 30 dias.
# MentalHealth: Saúde mental, por quantos dias nos últimos 30 dias sua saúde mental não foi boa? (0-30 dias).
# DiffWalking: Você tem muita dificuldade para andar ou subir escadas?
# Sex: Sexo.
# AgeCategory: Categoria de idade de quatorze níveis.
# Race: Etinía.
# Diabetic: Se têm diabetes.
# PhysicalActivity: Adultos que relataram fazer atividade física ou exercício durante os últimos 30 dias fora do trabalho regular.
# GenHealth: Você diria que, em geral, sua saúde é.
# SleepTime: Em média, quantas horas você dorme em um período de 24 horas?
# Asthma: Você tem asma?
# KidneyDisease: Cálculos renais, infecção da bexiga ou incontinência, alguma vez lhe disseram que tinha doença renal?
# SkinCancer: Você teve câncer de pele?

dict_cat_ingles = {
 'HeartDisease': {'No': 0, 'Yes': 1},
 'Smoking': {'No': 0, 'Yes': 1},
 'AlcoholDrinking': {'No': 0, 'Yes': 1},
 'Stroke': {'No': 0, 'Yes': 1},
 'DiffWalking': {'No': 0, 'Yes': 1},
 'Sex': {'Female': 0, 'Male': 1},
 'PhysicalActivity': {'No': 0, 'Yes': 1},
 'Asthma': {'No': 0, 'Yes': 1},
 'KidneyDisease': {'No': 0, 'Yes': 1},
 'SkinCancer': {'No': 0, 'Yes': 1},
 'Race': {'American Indian/Alaskan Native': 0,
  'Asian': 1,
  'Black': 2,
  'Hispanic': 3,
  'Other': 4,
  'White': 5},
 'Diabetic': {'No': 0,
  'No, borderline diabetes': 1,
  'Yes': 2,
  'Yes (during pregnancy)': 3},
 'GenHealth': {'Poor': 0,
  'Fair': 1,
  'Good': 2,
  'Very good': 3,
  'Excellent': 4}
  }

dict_cat_portugues = {
 'HeartDisease': {'Não': 0, 'Sim': 1},
 'Smoking': {'Não': 0, 'Sim': 1},
 'AlcoholDrinking': {'Não': 0, 'Sim': 1},
 'Stroke': {'Não': 0, 'Sim': 1},
 'DiffWalking': {'Não': 0, 'Sim': 1},
 'Sex': {'Feminino': 0, 'Masculino': 1},
 'PhysicalActivity': {'Não': 0, 'Sim': 1},
 'Asthma': {'Não': 0, 'Sim': 1},
 'KidneyDisease': {'Não': 0, 'Sim': 1},
 'SkinCancer': {'Não': 0, 'Sim': 1},
 'Race': {'Índio americano/nativo do Alasca': 0,
  'Asiático': 1,
  'Negro': 2,
  'Hispânico': 3,
  'Outros': 4,
  'Branco': 5},
 'Diabetic': {'Não': 0,
  'Não, diabetes limítrofe': 1,
  'Sim': 2,
  'Sim (durante a gravidez)': 3},
 'GenHealth': {'Ruim': 0,
  'Razoável': 1,
  'Boa': 2,
  'Muito Boa': 3,
  'Excelente': 4}
  }


with open('DICT_CATEGORIAS_VALORES.pkl', 'rb') as f:
    DICT_CATEGORIAS_VALORES = pickle.load(f)

with open('DICT_INVERSO_VALORES_CATEGORIAS_PORTUGUES.pkl', 'rb') as f:
    DICT_INVERSO_VALORES_CATEGORIAS_PORTUGUES = pickle.load(f)


CHOICES = { **DICT_CATEGORIAS_VALORES, **dict_cat_portugues }

# Configuração da página
#st.set_page_config(page_title = "Precisão de Doenças Cardíacas", layout = "centered")
st.title('Sistema de Auxílio à Previsão de Problemas Cardíacos')
st.sidebar.title("Anamnese - Sintomas")

imagem = 'coracao01.jpeg'
image = Image.open(imagem)
st.image(image, width=500)

CHOICES = DICT_INVERSO_VALORES_CATEGORIAS_PORTUGUES.copy()

# inicializacao das variaveis
SleepTime = PhysicalHealth = MentalHealth = BMI = HeartDisease = Smoking = AlcoholDrinking = Stroke = 0
AgeCategory = DiffWalking= Sex= PhysicalActivity= Asthma= KidneyDisease= SkinCancer= 0
Race = Diabetic = GenHealth = 0

with st.sidebar:

    with st.form(key='my_form'):

        # retorna o mapeamento para Categoria Numérica da opção
        # def format_func(option):
        #     return CHOICES[option]

        def format_IMC(imc):
            if (imc >= 0 and imc < 18):
                imc_int = 17
            elif (imc >= 18 and imc <= 24):
                imc_int = 24
            elif (imc > 24 and imc <= 30):
                imc_int = 30
            elif (imc > 30 and imc <= 35):
                imc_int = 35
            elif (imc > 35 and imc <= 40):
                imc_int = 40
            else:
                imc_int = 41

            return int(imc_int)

    
        BMI = st.number_input('IMC', min_value=15.0, max_value=300.0, step=1.0)
        BMI = format_IMC(BMI)

        Smoking = st.selectbox('Fumante', options = CHOICES['Smoking'], 
                                format_func=lambda x: CHOICES['Smoking'][x] )

        AlcoholDrinking = st.selectbox('Alto Consumo de Alcool', options = CHOICES['AlcoholDrinking'],      
                                             format_func=lambda x: CHOICES['AlcoholDrinking'][x] )

        Stroke = st.selectbox('Você teve um AVC?', options = CHOICES['Stroke'],
                                format_func=lambda x: CHOICES['Stroke'][x])

        PhysicalHealth =  st.number_input('Saúde Física, por quantos dias neste mês', 
                          min_value=0.0, max_value=30.0, step=1.0)

        def converter_PhysicalHealth_categoria(PhysicalHealth):
            if PhysicalHealth <= 4.0:
                PhysicalHealth_cat = 4
            elif (PhysicalHealth > 4.0 and PhysicalHealth <= 5.0):
                PhysicalHealth_cat = 5
            elif (PhysicalHealth > 5 and PhysicalHealth <= 6):
                PhysicalHealth_cat = 6
            elif (PhysicalHealth > 6 and PhysicalHealth <= 7):
                PhysicalHealth_cat = 7
            elif (PhysicalHealth > 7 and PhysicalHealth <= 8):
                PhysicalHealth_cat = 8
            else:
                PhysicalHealth_cat = 9

            return PhysicalHealth_cat

        PhysicalHealth = converter_PhysicalHealth_categoria(PhysicalHealth)

        MentalHealth  =  st.number_input('Saúde mental, por quantos dias não foi boa no mês', 
                          min_value=0.0, max_value=30.0, step=1.0)

        def converter_MentalHealth_categoria(MentalHealth):
            if MentalHealth <= 0:
                MentalHealth_cat = 0
            elif (MentalHealth >= 3.0 and MentalHealth < 10.0):
                MentalHealth_cat = 3
            elif (MentalHealth >= 10 and MentalHealth < 20):
                MentalHealth_cat = 20
            else:
                MentalHealth_cat = 30

            return MentalHealth_cat

        MentalHealth = converter_MentalHealth_categoria(MentalHealth)       

        DiffWalking = st.selectbox(
            'Dificuldade de andar ou subir escadas', options = CHOICES['DiffWalking'],
            format_func=lambda x: CHOICES['DiffWalking'][x])


        Sex = st.selectbox('Sexo', options = CHOICES['Sex'],
                            format_func=lambda x: CHOICES['Sex'][x])

        AgeCategory = st.selectbox('Idade (categoria)', options = CHOICES['AgeCategory'],
                                    format_func=lambda x: CHOICES['AgeCategory'][x])

        Race = st.selectbox('Etnia', options = CHOICES['Race'],
                                format_func=lambda x: CHOICES['Race'][x])

        Diabetic = st.selectbox('Diabetes', options = CHOICES['Diabetic'],
                                    format_func=lambda x: CHOICES['Diabetic'][x] )

        PhysicalActivity = st.selectbox(
            'Atividade Física nos últimos 30 dias', options = CHOICES['PhysicalActivity'],
             format_func=lambda x: CHOICES['PhysicalActivity'][x] )

        GenHealth = st.selectbox('Estado Geral de Saúde', options = CHOICES['GenHealth'],
                                    format_func=lambda x: CHOICES['GenHealth'][x])

        SleepTime =  st.number_input('Quantas horas você dorme por dia', 
                          min_value=1.0, max_value=24.0, step=1.0)

        def converter_sleepTime_categoria(SleepTime):
            if SleepTime <= 4:
                sleep_cat = 4
            elif (SleepTime > 4 and SleepTime <= 5):
                sleep_cat = 5
            elif (SleepTime > 5 and SleepTime <= 6):
                sleep_cat = 6
            elif (SleepTime > 6 and SleepTime < 8):
                sleep_cat = 7
            elif (SleepTime >= 8 and SleepTime < 9):
                sleep_cat = 8
            elif (SleepTime >= 9 ):
                sleep_cat = 9

            return sleep_cat

        SleepTime = converter_sleepTime_categoria(SleepTime)

 
        Asthma  = st.selectbox('Você tem asma?', CHOICES['Asthma'],
                                 format_func=lambda x: CHOICES['Asthma'][x])

        KidneyDisease = st.selectbox('Doença renal (cálculo, incontinência, etc.', 
                                      options = CHOICES['KidneyDisease'],
                                      format_func=lambda x: CHOICES['KidneyDisease'][x]) 

        SkinCancer = st.selectbox('Câncer de pele', options = CHOICES['SkinCancer'],
                                    format_func=lambda x: CHOICES['SkinCancer'][x])


        predict_button = st.form_submit_button(label='Prever')


# Pagina pricipal

import xgboost
from xgboost import Booster

def previsao_doenca_cardiaca(Smoking, AlcoholDrinking, Stroke,  DiffWalking, Sex, Race,  
          Diabetic, PhysicalActivity, GenHealth, Asthma, KidneyDisease,
          SkinCancer, AgeCategory, SleepTime, PhysicalHealth,
          MentalHealth, BMI):

    # Colocar em escala (Padronizacao)
    sc = jb.load('std_scaler.bin')

    X = np.array([Smoking, AlcoholDrinking, Stroke,  DiffWalking, Sex, Race,  
          Diabetic, PhysicalActivity, GenHealth, Asthma, KidneyDisease,
          SkinCancer, AgeCategory, SleepTime, PhysicalHealth,
          MentalHealth, BMI]).reshape(1, -1)

    scaler_X = sc.transform(X) 
    print(scaler_X)


    #file = "modeloXGBoostv50.pkl" 
    #xgb = joblib.load(file)

    # PREDICT
    # file = 'modeloXGBoostv50.pkl'
    # # # load

    #file = "modeloXGBoostv50.pkl" 
    # clf = True
    # with open(file, 'rb') as f:
    #     clf = pickle.load(f)

    # model = clf


    #file = 'modeloXGBoostv50.json'

    #load saved model
    #model = xgbst = jb.load(file)


    # booster = Booster()
    # model = booster.load_model(file)

    file = 'modeloXGBoostv50.bin'
    booster = xgb.Booster()
    booster.load_model(file)
    model = booster


    #model = xgbst.Booster(file)
    #model.predict(new_data)

    drow = xgb.DMatrix(scaler_X, label=[0, 1]) #, feature_names=X_test.columns)
    prob = model.predict(drow)
    if prob > 0.5:
        pred = ':red[Doença Cardíaca]' 
    else:
        pred = ':blue[Normal]'
        prob = 1 - prob
    # pred = ['Normal' if  model.predict(drow) > 0.5 else 'Doença Cardíaca']
    # pred = pred[0]
    print(pred)
    print(type(pred))
    print(prob)
    

    # if pred == 0:
    #     diagnostico_doenca_cardiaca = "Normal"
    #     image = 'saudavel.jpg' 
    # elif pred == 1:
    #     diagnostico_doenca_cardiaca = "Doença Cardíaca"
    #     image = 'diabetes02.jpg' 
    # else:
    #     diagnostico_doenca_cardiaca = "Sem Diagnóstico"

    return pred, prob[0] #, image


if predict_button:
    print('ok')
    print('\n')

    print(Smoking, AlcoholDrinking, Stroke,  DiffWalking, Sex, Race,  
          Diabetic, PhysicalActivity, GenHealth, Asthma, KidneyDisease,
          SkinCancer, AgeCategory, SleepTime, PhysicalHealth,
          MentalHealth, BMI)

    atributos = [ Smoking, AlcoholDrinking, Stroke,  DiffWalking, Sex, Race,  
          Diabetic, PhysicalActivity, GenHealth, Asthma, KidneyDisease,
          SkinCancer, AgeCategory, SleepTime, PhysicalHealth,
          MentalHealth, BMI ]

 


    diagnostico_doenca_cardiaca, prob  = previsao_doenca_cardiaca(Smoking, AlcoholDrinking, 
      Stroke,  DiffWalking, Sex, Race,  
      Diabetic, PhysicalActivity, GenHealth, Asthma, KidneyDisease,
      SkinCancer, AgeCategory, SleepTime, PhysicalHealth,
      MentalHealth, BMI)


    string_saida = '### Previsão: ' + diagnostico_doenca_cardiaca  + \
                   ' - Probabilidade: ' + str(int(round(prob * 100, 0))) + "%" 
    st.markdown(string_saida)
    # st.markdown('## Previsão: ' + diagnostico_doenca_cardiaca)
    # st.markdown('## Probabilidade: ' + str(int(round(prob * 100, 0))) + "%")

# )


    

# BMI, Smoking, AlcoholDrinking, Stroke, PhysicalHealth, MentalHealth, DiffWalking, Sex, AgeCategory, 
# Race, Diabetic, PhysicalActivity, GenHealth, SleepTime, Asthma, KidneyDisease, SkinCancer


    #st.write(Diagnostico_Diabetes)
    # image = Image.open('diabetes/' + imagem)
    # st.markdown('## Diagnóstico: ' + '__' + Diagnostico_Diabetes + '__')
    # #st.write('Diagnóstico:' + Diagnostico_Diabetes)
    # st.image(image, width=250)

# else:
#     Diagnostico_Diabetes = 'Sem Previsão'