Spaces:
Sleeping
Sleeping
| 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' | |