diabetes / app.py
valencar's picture
Rename app_diabetes.py to app.py
667a397 verified
import streamlit as st
import pandas as pd
# import xgboost as xgb
# import xgboost
import pickle
import numpy as np
from PIL import Image
# Remove whitespace from the top of the page
reduce_header_height_style = """
<style> .stDeployButton {visibility: hidden;} </style>
<style> div[class^='block-container'] { padding-top: 1rem; } </style>
"""
st.markdown(reduce_header_height_style, unsafe_allow_html=True)
# predict_button = None
# Pagina pricipal
def previsao_diabetes(modelo, Pressao_Alta, Colesterol_Alto, Checagem_Colesterol_em_5_anos, IMC, Fumante, AVC,
Doenca_coronaria_cardiaca, Atividade_Fisica_nos_ultimos_30_dias,
Consumo_Frutas, Consumo_Vegetais, Alto_Consumo_Alcool,
Plano_de_Saude, Nao_pode_ir_ao_medico_devido_custo, Estado_Geral_Saude,
Saude_mental, Saude_fisica, Dificuldade_andar_ou_subir_escadas, Sexo,
Idade, Nivel_Educacional, Renda):
# 0 = no diabetes 1 = prediabetes 2 = diabetes
new_X = np.array([Pressao_Alta, Colesterol_Alto, Checagem_Colesterol_em_5_anos, IMC, Fumante, AVC,
Doenca_coronaria_cardiaca, Atividade_Fisica_nos_ultimos_30_dias,
Consumo_Frutas, Consumo_Vegetais, Alto_Consumo_Alcool,
Plano_de_Saude, Nao_pode_ir_ao_medico_devido_custo, Estado_Geral_Saude,
Saude_mental, Saude_fisica, Dificuldade_andar_ou_subir_escadas, Sexo,
Idade, Nivel_Educacional, Renda])
xgb = modelo
# Colocar em escala (Padronizacao)
import joblib as jb
sc = jb.load('std_scaler.bin')
scaler_X = sc.transform(new_X.reshape(1, -1)) # fit_transform
preds = xgb.predict(scaler_X.reshape(1,-1))[0]
print(scaler_X)
probabilidades = xgb.predict_proba(scaler_X.reshape(1,-1))[0]
probabilidade = np.max(np.array(probabilidades))
probabilidade = int(round(probabilidade * 100, 0))
diagnostico_previsto = preds
if diagnostico_previsto == 0:
Diagnostico_Diabetes = ":blue[Sem Diabetes]"
image = 'saudavel.jpg'
elif diagnostico_previsto == 1:
Diagnostico_Diabetes = ":red[Diabetes tipo 2]"
image = 'diabetes02.jpg'
else:
Diagnostico_Diabetes = "Sem Diagnóstico"
return Diagnostico_Diabetes, image, probabilidade
if __name__=="__main__":
st.title('Sistema para Previsão de Diabetes Tipo 2')
# carregando o modelo
if 'xgb' not in st.session_state:
with st.spinner('carregando o modelo...'):
file = 'modeloXGBoost_Diabetes.pkl'
with open(file, 'rb') as f:
xgb = pickle.load(f)
with st.container():
col1 = st.container()
def format_func(option):
return CHOICES[option]
st.sidebar.title("Atributos")
# # variaveis
atributos = ['Diagnostico_Diabetes', 'Pressao_Alta', 'Colesterol_Alto', 'Checagem_Colesterol_em_5_anos', 'IMC', 'Fumante', 'AVC', 'Doenca_coronaria_cardiaca', 'Atividade_Fisica_nos_ultimos_30_dias', 'Consumo_Frutas', 'Consumo_Vegetais', 'Alto_Consumo_Alcool', 'Plano_de_Saude', 'Nao_pode_ir_ao_medico_devido_custo', 'Estado_Geral_Saude', 'Saude_mental', 'Saude_fisica', 'Dificuldade_andar_ou_subir_escadas', 'Sexo', 'Idade', 'Nivel_Educacional', 'Renda']
# inicializacao das variaveis
Diagnostico_Diabetes= Pressao_Alta= Colesterol_Alto= Checagem_Colesterol_em_5_anos= IMC= Fumante= AVC= Doenca_coronaria_cardiaca= Atividade_Fisica_nos_ultimos_30_dias= Consumo_Frutas= Consumo_Vegetais= Alto_Consumo_Alcool= Plano_de_Saude= Nao_pode_ir_ao_medico_devido_custo= Estado_Geral_Saude= Saude_mental= Saude_fisica= Dificuldade_andar_ou_subir_escadas= Sexo= Idade= Nivel_Educacional= Renda = 0
with st.sidebar: # scrolling=True
with st.form(key='my_form'):
CHOICES = {0: "Não", 1: "Sim"}
Pressao_Alta = st.selectbox('Pressão Alta', options=list(CHOICES.keys()), format_func=format_func)
Colesterol_Alto = st.selectbox('Colesterol Alto',options=list(CHOICES.keys()), format_func=format_func)
Checagem_Colesterol_em_5_anos = st.selectbox(
'Checagem colesterol em 5 anos',options=list(CHOICES.keys()), format_func=format_func)
imc = IMC = st.number_input('IMC', min_value=25.0, max_value=500.0, step=1.0)
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
IMC = imc_int
CHOICES = {0: "Não", 1: "Sim"}
Fumante = st.selectbox('Fumante',options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {0: "Não", 1: "Sim"}
AVC = st.selectbox('AVC',options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {0: "Não", 1: "Sim"}
Doenca_coronaria_cardiaca = st.selectbox('Doenca coronária cardíaca',
options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {0: "Não", 1: "Sim"}
# physical activity in past 30 days - not including job 0 = no 1 = yes
Atividade_Fisica_nos_ultimos_30_dias = st.selectbox(
'Atividade Física nos últimos 30 dias',
options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {0: "Não", 1: "Sim"}
Consumo_Frutas = st.selectbox('Consumo de Frutas',options=list(CHOICES.keys()), format_func=format_func)
Consumo_Vegetais = st.selectbox('Consumo de Vegetais',options=list(CHOICES.keys()), format_func=format_func)
Alto_Consumo_Alcool = st.selectbox('Alto Consumo de Alcool',options=list(CHOICES.keys()), format_func=format_func)
Plano_de_Saude = st.selectbox('Plano de Saúde',options=list(CHOICES.keys()), format_func=format_func)
Nao_pode_ir_ao_medico_devido_custo = st.selectbox(
'Não pode ir ao medico devido ao custo',options=list(CHOICES.keys()), format_func=format_func)
# 1 = excellent 2 = very good 3 = good 4 = fair 5 = poor
CHOICES = {1: "Excelente" , 2: "Muito Bom", 3: "Bom", 4: "Razoável", 5: "Ruim"}
Estado_Geral_Saude = st.selectbox('Estado Geral de Saúde',
options=list(CHOICES.keys()), format_func=format_func)
valor = Saude_mental = st.number_input('Problemas com Saude Mental (em dias)',
min_value=0, max_value=30)
if (valor == 0):
valor_categoria = 0
elif (valor == 1):
valor_categoria = 1
elif (valor == 2):
valor_categoria = 2
elif (valor > 2 and valor <= 29):
valor_categoria = 29
elif (valor == 30):
valor_categoria = 30
Saude_mental = valor_categoria
valor = Saude_fisica = st.number_input('Problemas com Saude Física (em dias)',
min_value=0, max_value=30)
if (valor == 0):
valor_categoria = 0
elif (valor == 1):
valor_categoria = 1
elif (valor == 2):
valor_categoria = 2
elif (valor > 2 and valor <= 29):
valor_categoria = 29
elif (valor == 30):
valor_categoria = 30
Saude_fisica = valor_categoria
Dificuldade_andar_ou_subir_escadas = st.selectbox(
'Dificuldade de andar ou subir escadas',options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {0: "Maculino", 1: "Feminino"}
Sexo = st.selectbox('Sexo',options=list(CHOICES.keys()), format_func=format_func)
CHOICES = {1: "18-24", 2: "25-29", 3: "30-34", 4: "35-39", 5: "40-44", 6: "45-49", 7: "50-54",
8: "55-59", 9: "60-64", 10: "65-69", 11: "70-74", 12: "75-79", 13:"80+"}
valor = Idade = st.selectbox('Idade', options=list(CHOICES.keys()), format_func=format_func)
if (valor == 1):
valor_categoria = 6
elif (valor == 2):
valor_categoria = 6
elif (valor == 3):
valor_categoria = 6
elif (valor == 4):
valor_categoria = 6
elif (valor == 5):
valor_categoria = 6
elif (valor == 6):
valor_categoria = 6
elif (valor == 7):
valor_categoria = 8
elif (valor == 8):
valor_categoria = 8
elif (valor == 9):
valor_categoria = 9
elif (valor == 10):
valor_categoria = 10
elif (valor == 11):
valor_categoria = 13
elif (valor == 12):
valor_categoria = 13
elif (valor == 13):
valor_categoria = 13
Idade = valor_categoria
# Educação - 1 = Never attended school or only kindergarten 2 = Grades 1 through 8 (Elementary) 3 = Grades 9 through 11 (Some high school) 4 = Grade 12 or GED (High school graduate) 5 = College 1 year to 3 years (Some college or technical school) 6 = College 4 years or more (College graduate)
CHOICES = {1: 'Não frequentou a escola', 2: 'Ensino Básico', 3: 'Ensino Médio Incompleto',
4: 'Ensino Médio Completo', 4: "Faculdade (1 a 3 anos) ou Técnico",
5: "Superior Completo" }
valor = Nivel_Educacional = st.selectbox('Nivel Educacional',
options=list(CHOICES.keys()), format_func=format_func)
if (valor == 1):
valor_categoria = 2
elif (valor == 2):
valor_categoria = 2
elif (valor == 3):
valor_categoria = 3
elif (valor == 4):
valor_categoria = 4
elif (valor == 5):
valor_categoria = 5
elif (valor == 6):
valor_categoria = 6
Nivel_Educacional = valor_categoria
CHOICES = { 1:'Menos de $10,000', 2:'$10,000 até menos que $15,000',
3:'$15,000 até menos que $20,000', 4:'$20,000 até menos que $25,000',
5:'$25,000 até menos que $35,000', 6:'$35,000 até menos que $50,000',
7:'$50,000 até menos que $75,000', 8:'Mais de $75,000' }
valor = Renda = st.selectbox('Renda Anual (em Dólar)',
options=list(CHOICES.keys()), format_func=format_func)
if (valor == 1):
valor_categoria = 1
elif (valor == 2):
valor_categoria = 1
elif (valor == 3):
valor_categoria = 1
elif (valor == 4):
valor_categoria = 1
elif (valor == 5):
valor_categoria = 5
elif (valor == 6):
valor_categoria = 6
elif (valor == 7):
valor_categoria = 7
elif (valor == 8):
valor_categoria = 8
Renda = valor_categoria
predict_button = st.form_submit_button(label='Prever')
if predict_button: # is not None:
# atributos_por_ordem =[ \
# 'HighBP', 'HighChol', 'CholCheck', 'Smoker', 'Stroke',
# 'HeartDiseaseorAttack', 'PhysActivity', 'Fruits', 'Veggies',
# 'HvyAlcoholConsump', 'AnyHealthcare', 'NoDocbcCost', 'GenHlth',
# 'DiffWalk', 'Sex', 'MentHlth_cat', 'PhysHlth_cat', 'Income_cat',
# 'Education_cat', 'BMI_cat', 'Age_cat']
# ['HighBP' 'HighChol' 'CholCheck' 'Smoker' 'Stroke'
# 'HeartDiseaseorAttack', 'PhysActivity' 'Fruits' 'Veggies',
# 'HvyAlcoholConsump', 'AnyHealthcare' 'NoDocbcCost' 'GenHlth'
# 'DiffWalk' 'Sex' 'MentHlth_cat' 'PhysHlth_cat''Income_cat'
# 'Education_cat' 'BMI_cat' 'Age_cat']
Diagnostico_Diabetes, imagem, probabilidade = previsao_diabetes(xgb,
Pressao_Alta, Colesterol_Alto, Checagem_Colesterol_em_5_anos, Fumante, AVC,
Doenca_coronaria_cardiaca, Atividade_Fisica_nos_ultimos_30_dias, Consumo_Frutas, Consumo_Vegetais,
Alto_Consumo_Alcool, Plano_de_Saude, Nao_pode_ir_ao_medico_devido_custo, Estado_Geral_Saude,
Dificuldade_andar_ou_subir_escadas, Sexo, Saude_mental, Saude_fisica, Renda,
Nivel_Educacional, IMC, Idade)
image = Image.open(imagem)
#st.markdown('## Diagnóstico: ' + Diagnostico_Diabetes + " - " + str(probabilidade) + "%")
#st.write('Diagnóstico:' + Diagnostico_Diabetes)
#st.image(image, width=250)
string_saida = 'Diagnóstico: ' + Diagnostico_Diabetes + " - " + str(probabilidade) + "%"
col1.header(string_saida)
col1.image(image, width=700)
else:
imagem = 'diabetes_desktop.jpg'
image = Image.open(imagem)
# st.image(image, width=250)
col1.image(image, width=700)
# main()
st.write("")
st.write("")
st.write("")
st.write("")
st.write("")
aviso = "ESTE RESULTADO NÃO SUBSTITUI A AVALIAÇÃO DO MÉDICO. Este é um sistema para auxílio diagnóstico de doenças usando modelos ensemble. Todo o processamento é feito no seu dispositivo e as imagens não são enviadas para o seu servidor. Ao continuar, você assume toda a responsabilidade com o uso."
st.markdown(f'<div style="color: #856404; background-color: #fff3cd; border-color: #ffeeba; padding-top:10px; padding-top:10px; padding-bottom:10px; padding-left:10px; padding-right:10px;">{aviso}</div>',
unsafe_allow_html=True)
st.write("")
st.write("")
st.write("")
st.write("")
st.write("")
st.write("")
st.write("")
footer="\
<div > \
<p>Sistema de Apoio ao Diagnóstico de Diabetes tipo 2 versão 1.0.1.<br> \
Desenvolvido por Prof. Dr. Vladimir Costa de Alencar e Equipe de Pesquisadores do LANA/UEPB. <br> \
Campina Grande, Paraíba, Brasil, 2024.<br> \
<a href='https://www.valencar.com' target='_blank'>www.valencar.com</a></p>"
st.markdown(footer, unsafe_allow_html=True)
name_image = "LANA_Card.png"
imagem = Image.open(name_image)
st.image(imagem, width=300)