Spaces:
Running
Running
File size: 23,690 Bytes
af86901 f001425 af86901 f001425 ee32251 f001425 a3add5a 5ea884b 550a9d2 5ea884b a3add5a f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 9b6d256 f001425 9b6d256 f001425 fd0a6a9 f001425 af86901 f001425 cb9d2b1 32067fc fc033f4 f001425 af86901 f001425 af86901 f001425 af86901 66237ff af86901 5f6e121 f001425 af86901 3d6ec9a 32067fc af86901 3d6ec9a af86901 3d6ec9a af86901 3d6ec9a af86901 3d6ec9a af86901 3d6ec9a af86901 32067fc f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 af86901 f001425 c5b0371 3d6ec9a af86901 550a9d2 af86901 |
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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 |
import os
import markdown
import plotly.express as px
import streamlit as st
from groq import Groq
from html2docx import html2docx
from mistralai import Mistral
from streamlit_extras.add_vertical_space import add_vertical_space
from streamlit_extras.stylable_container import stylable_container
from streamlit_option_menu import option_menu
from data_cleaning import processar_arquivo
st.title(" 📊 - Análise de microárea")
ch1, ch2 = st.columns([0.6, 0.4])
with ch1:
st.markdown("""
#### 📑 Instruções:
##### 1. Site :orange[PEC SUS], relatórios, :blue[*RELATÓRIO DE CADASTRO INDIVIDUAL*]
##### 2. Clique em :orange[baixar arquivo .csv]. Faça o upload do arquivo .csv, no menu ao lado. 👈
##### 3. Solicite o relatório ao 🤖 Zé Flamengo, ou tire suas dúvidas.
###### ⏳ :red[_ATENÇÃO!_], Caso solicite o relatório, clique :blue[**uma vez**] em "Gerar Relatório e aguarde. Demora cerca de 1 minuto para ficar pronto!
""")
st.write("-----")
st.markdown("""
#### Dados de saúde Relatório de cadastro individual.""")
with ch2, stylable_container(
key="banner",
css_styles="""
img {
width: 360px;
height: 360px;
overflow: hidden;
position: relative;
object-fit: cover;
border-radius: 28px; /* Adiciona bordas arredondadas */
mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
-webkit-mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0)); /* For Safari */
}
""",
): st.image("icon/family.png")
def clear_chat_history():
"""
Clears the chat history and resets the initial analysis in the session state.
This function clears the chat history and resets the initial analysis in the session state.
It sets the value of "groq_chat_history" in the session state to an empty list and the value of "initial_analysis" to an empty string.
"""
st.session_state["groq_chat_history"] = []
st.session_state["initial_analysis"] = ""
#################################
############ DATA ###############
#################################
my_secret = os.environ['GROQ_API_KEY']
DF_DATA = None
DF_HEAD = None
DF_IDADE = None
DF_GENERO = None
DF_COR = None
DF_DEFICIENCIA = None
DF_DOENCAS = None
DF_ESCOLA = None
DF_TRANSGEN = None
uploaded_file = st.sidebar.file_uploader("Escolha um arquivo CSV", type="csv")
if uploaded_file is not None:
dataframes = processar_arquivo(uploaded_file)
DF_DATA = dataframes.get("Data")
DF_HEAD = dataframes.get("Head")
DF_IDADE = dataframes.get("Idade")
DF_GENERO = dataframes.get("genero")
DF_COR = dataframes.get("cor")
DF_DEFICIENCIA = dataframes.get("deficiencia")
DF_DOENCAS = dataframes.get("doencas")
DF_ESCOLA = dataframes.get("Escola")
DF_TRANSGEN = dataframes.get("transgen")
for df in [
DF_IDADE,
DF_GENERO,
DF_COR,
DF_DEFICIENCIA,
DF_DOENCAS,
DF_ESCOLA,
DF_TRANSGEN,
]:
if df is not None:
df["Descrição"] = df["Descrição"].str.capitalize()
else:
st.sidebar.info("Adicione um arquivo .csv.")
if st.sidebar.button("Limpar", type="primary"):
clear_chat_history()
def gerar_resumo_df():
"""
Generates a summary of the dataframes.
This function creates a summary of the dataframes by concatenating the
string representation of each dataframe.
The summary includes the name of the dataframe and its content.
Returns:
str: The summary of the dataframes.
"""
resumo = ""
if DF_DATA is not None:
resumo += "Resumo DF_DATA:\n"
resumo += DF_DATA.to_string(index=False) + "\n\n"
if DF_HEAD is not None:
resumo += "Resumo DF_HEAD:\n"
resumo += DF_HEAD.to_string(index=False) + "\n\n"
if DF_IDADE is not None:
resumo += "Resumo DF_IDADE:\n"
resumo += DF_IDADE.to_string(index=False) + "\n\n"
if DF_GENERO is not None:
resumo += f"Resumo DF_GENERO:\n{DF_GENERO.to_string(index=False)}\n\n"
if DF_COR is not None:
resumo += f"Resumo DF_COR:\n{DF_COR.to_string(index=False)}\n\n"
if DF_DEFICIENCIA is not None:
resumo += f"Resumo DF_DEFICIENCIA:\n{DF_DEFICIENCIA.to_string(index=False)}\n\n"
if DF_DOENCAS is not None:
resumo += f"Resumo DF_DOENCAS:\n{DF_DOENCAS.to_string(index=False)}\n\n"
if DF_ESCOLA is not None:
resumo += f"Resumo DF_ESCOLA:\n{DF_ESCOLA.to_string(index=False)}\n\n"
if DF_TRANSGEN is not None:
resumo += f"Resumo DF_TRANSGEN:\n{DF_TRANSGEN.to_string(index=False)}\n\n"
return resumo
###########################################
############### EXPANDERCOM GRÁFICOS ######
###########################################
def criar_grafico_personalizado(df, x_col, y_col, titulo):
"""
A function to create a customized bar chart based on the input data, x
and y columns, and title.
Parameters:
df (DataFrame): The input DataFrame containing the data.
x_col (str): The column name for the x-axis data.
y_col (str): The column name for the y-axis data.
titulo (str): The title of the chart.
Returns:
fig: The customized bar chart figure.
"""
fig = px.bar(
df,
x=x_col,
y=y_col,
title=titulo,
text=y_col,
color=x_col,
color_discrete_sequence=px.colors.qualitative.Bold,
)
fig.update_traces(texttemplate="%{text:.2s}", textposition="outside")
fig.update_layout(
uniformtext_minsize=8,
uniformtext_mode="hide",
xaxis_title=x_col,
yaxis_title=y_col,
title_font_size=24,
title_font_family="Arial",
title_font_color="white",
title_x=0.2,
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
xaxis_tickangle=-45,
)
return fig
if uploaded_file is not None:
c1, c2 = st.columns(2)
with c1:
if DF_DATA is not None:
st.dataframe(DF_DATA, hide_index=True)
else:
st.write("Data não disponível")
with c2:
if DF_HEAD is not None:
st.dataframe(DF_HEAD, hide_index=True)
else:
st.write("Informações não disponíveis")
if uploaded_file is not None:
with st.expander("Visualização", expanded=True):
selected_tab = option_menu(
menu_title=None,
options=[
"Faixa Etária",
"Gênero",
"Cor",
"Deficiência",
"Doenças",
"Escolaridade",
"Identidade de Gênero",
],
icons=[
"person",
"gender-female",
"person-plus",
"person-wheelchair",
"capsule-pill",
"stars",
"gender-trans",
],
menu_icon="cast",
default_index=0,
orientation="horizontal",
styles={
"container": {
"padding": "0!important",
"background-color": "#262730",
},
"icon": {
"color": "#4FCBFC",
"font-size": "18px"
},
"nav-link": {
"font-size": "14px",
"text-align": "center",
"margin": "0px",
"padding": "10px",
"--hover-color": "#363940",
"color": "#FFFFFF",
},
"nav-link-selected": {
"background-color": "#0083B8"
},
"separator": {
"border-color": "#4B4B4B"
},
},
)
if selected_tab == "Faixa Etária" and DF_IDADE is not None:
st.subheader("Distribuição por Faixa Etária")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_IDADE, hide_index=True)
with col2:
DF_IDADE["Masculino"] = DF_IDADE["Masculino"].astype(int) * -1
DF_IDADE["Feminino"] = DF_IDADE["Feminino"].astype(int)
fig_idade = px.bar(
DF_IDADE,
x=["Masculino", "Feminino"],
y="Descrição",
orientation="h",
title="Pirâmide Etária",
labels={
"value": "População",
"Descrição": "Faixa Etária"
},
color="Descrição",
color_discrete_sequence=px.colors.qualitative.Set3,
)
fig_idade.update_layout(
barmode="relative",
xaxis_title="População",
yaxis_title="Faixa Etária",
)
st.plotly_chart(fig_idade)
DF_IDADE["Masculino"] = DF_IDADE["Masculino"].abs()
elif selected_tab == "Gênero" and DF_GENERO is not None:
st.subheader("Distribuição por Gênero")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_GENERO, hide_index=True)
with col2:
fig_genero = px.pie(
DF_GENERO,
names="Descrição",
values="Valor",
title="Distribuição por Gênero",
color_discrete_sequence=px.colors.qualitative.Pastel,
)
st.plotly_chart(fig_genero)
elif selected_tab == "Cor" and DF_COR is not None:
st.subheader("Distribuição por Cor")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_COR, hide_index=True)
with col2:
fig_cor = px.pie(
DF_COR,
names="Descrição",
values="Valor",
title="Distribuição por Cor",
color_discrete_sequence=px.colors.qualitative.Vivid,
)
st.plotly_chart(fig_cor)
elif selected_tab == "Deficiência" and DF_DEFICIENCIA is not None:
st.subheader("Distribuição por Deficiência")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_DEFICIENCIA, hide_index=True)
with col2:
fig_deficiencia = criar_grafico_personalizado(
DF_DEFICIENCIA,
x_col="Descrição",
y_col="Valor",
titulo="Distribuição por Deficiência",
)
st.plotly_chart(fig_deficiencia)
elif selected_tab == "Doenças" and DF_DOENCAS is not None:
st.subheader("Distribuição por Doenças")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_DOENCAS, hide_index=True)
with col2:
fig_doencas = criar_grafico_personalizado(
DF_DOENCAS,
x_col="Descrição",
y_col="Valor",
titulo="Distribuição por Doenças",
)
st.plotly_chart(fig_doencas)
elif selected_tab == "Escolaridade" and DF_ESCOLA is not None:
st.subheader("Distribuição por Escolaridade")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_ESCOLA, hide_index=True)
with col2:
fig_escola = criar_grafico_personalizado(
DF_ESCOLA,
x_col="Descrição",
y_col="Valor",
titulo="Distribuição por Escolaridade",
)
st.plotly_chart(fig_escola)
elif selected_tab == "Identidade de Gênero" and DF_TRANSGEN is not None:
st.subheader("Distribuição por Identidade de Gênero")
col1, col2 = st.columns(2)
with col1:
st.dataframe(DF_TRANSGEN, hide_index=True)
with col2:
fig_transgen = criar_grafico_personalizado(
DF_TRANSGEN,
x_col="Descrição",
y_col="Valor",
titulo="Distribuição por Identidade de Gênero",
)
st.plotly_chart(fig_transgen)
add_vertical_space(2)
###########################################
############### FOTO DO BOT ###############
###########################################
with stylable_container(
key="bot",
css_styles="""
img {
width: 200px;
height: 260px;
overflow: hidden;
position: relative;
object-fit: cover;
border-radius: 14px; /* Adiciona bordas arredondadas */
}
""",
):
st.image("src/Images/bot.png")
###########################################
############### CHATBOT RCI ###############
###########################################
# Configuração inicial do Groq client
client = Groq(api_key=my_secret)
my_secret_mi = os.environ['MISTRAL_API_KEY']
client_mi = Mistral(api_key=my_secret_mi)
def create_word_doc(markdown_content):
# Converter o Markdown em HTML
html = markdown.markdown(markdown_content)
# Converter o HTML em um documento Word
# html2docx() retorna um objeto BytesIO
docx_file = html2docx(html, title="Análise Inicial")
# Retornar o objeto BytesIO contendo o documento Word
return docx_file
# Função para gerar a análise inicial
def generate_initial_analysis(resumo_rci):
"""
Generates an initial analysis report based on the provided resumo_rci.
Parameters:
resumo_rci (str): The resumo_rci to be analyzed.
"""
initial_analysis = client_mi.agents.complete(
agent_id="ag:493f2384:20240924:agent-rci:23eed30a",
messages=[
{
"role": "user",
"content": f"""
Dados da microárea:
<resumo_rci>
{resumo_rci}
</resumo_rci>
""",
},
],
)
# Check if initial_analysis is None or does not have choices
if initial_analysis is None or not hasattr(initial_analysis,
'choices') or (
initial_analysis.choices is not None and len(initial_analysis.choices) == 0):
return "An error occurred: no response from the analysis API."
output = (
initial_analysis.choices[0].message.content
if initial_analysis and initial_analysis.choices
else None
)
return output
# Carregar arquivo de dados do usuário
if uploaded_file is not None and st.button("Gerar Resumo"):
spinner = st.empty()
spinner.text("Gerando resumo...")
try:
# Gera o resumo do DataFrame e a análise inicial
st.session_state.resumo_rci = gerar_resumo_df()
st.session_state.initial_analysis = generate_initial_analysis(
st.session_state.resumo_rci)
finally:
spinner.empty()
st.success("Resumo gerado com sucesso!")
col1, col2 = st.columns(2)
with col1, st.expander("Resumo Inicial", expanded=True):
if "initial_analysis" in st.session_state and st.session_state.initial_analysis:
st.write("**Panorama Geral dos Dados:**")
markdown_content = st.session_state.initial_analysis
if markdown_content and markdown_content.strip():
html_content = f'''
<div style="height:600px; overflow-y: auto; padding: 10px;
border: 1px solid #CCC;">
{markdown_content}
</div>
'''
st.markdown(html_content, unsafe_allow_html=True)
# Botão para baixar o documento em formato Word
docx_file = create_word_doc(markdown_content)
st.download_button(
label="Baixar em formato Word",
data=docx_file.getvalue(),
file_name="analise_inicial.docx",
mime=
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.warning(
"Não há conteúdo disponível para gerar o documento.")
else:
st.write("**Clique em 'Gerar Resumo' para analisar os dados.**")
with col2, st.expander("Converse com o 🤖 Zé Flamengo", expanded=True):
# Inicialização do histórico do chat
if "groq_chat_history" not in st.session_state:
st.session_state.groq_chat_history = []
# Criar um container para o histórico do chat
chat_container = st.container()
# Exibição do histórico do chat dentro do container
with chat_container:
for message in st.session_state.groq_chat_history:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Input do usuário (colocado fora e abaixo do container do histórico)
user_message = st.chat_input("Digite sua pergunta sobre saúde na microárea:")
# Processamento da mensagem do usuário
if user_message:
# Adiciona a mensagem do usuário ao histórico
st.session_state.groq_chat_history.append({
"role": "user",
"content": user_message
})
try:
# Usar o resumo já gerado
if "resumo_rci" not in st.session_state:
st.warning("Por favor, gere o resumo antes de fazer perguntas.")
else:
resumo_rci = st.session_state.resumo_rci
# Preparação do contexto para a API
context = f"""
Seu nome é Zé Flamengo, você é um assistente virtual especializado
em análise de dados médicos epidemiológicos. Você tem 20 anos de
experiência em análise de dados de saúde de microáreas de um PSF
(Programa Saúde da Família).
Sua função é:
1. Analisar dados de uma unidade básica de saúde.
2. Os dados que irá analisar são provenientes do Relatório de
Cadastro Individual, advindos do PEC SUS.
3. Suas respostas devem ser sempre em português.
4. Seja conciso e evite conversar sobre outros temas.
5. Sempre retome o tema da conversa.
6. Realize sempre os cálculos novamente para garantir que os
resultados fornecidos sejam precisos e atualizados.
Os dataframes que irá analisar são do Relatório de cadastro
individual.
Ele foi transformado em texto aqui disponível:
{resumo_rci}
As faixas etárias recomendadas para exames preventivos são:
- **Papanicolau (Preventivo):** Mulheres entre 25 e 64 anos, com
frequência anual nos primeiros dois exames
consecutivos com resultados normais, depois a cada três anos.
- **Mamografia:** Mulheres entre 50 e 69 anos, com frequência
bienal.
Informações sobre o Relatório de Cadastro Individual:
- **Objetivo:** Coletar dados sociodemográficos e de saúde dos
indivíduos cadastrados em uma unidade básica de saúde.
- **Principais Indicadores:** Idade, sexo, condições de saúde
(doenças crônicas, gestantes, etc.), status de vacinação, hábitos
de vida (tabagismo, alcoolismo, atividade física), entre outros.
Exemplos de perguntas esperadas:
- Qual a porcentagem de mulheres na faixa etária de preventivo?
- Qual a porcentagem de mulheres na faixa etária de mamografia?
- Quantas mulheres estão nas faixas etárias de preventivo e
mamografia?
- Qual a relação masculino/feminino?
- Qual a porcentagem das doenças em relação à população total?
- Use essas informações para responder às perguntas do usuário.
Regras:
1. Seja sempre cortês.
2. Responda somente assuntos referentes ao resumo.
3. Caso seja feita alguma pergunta a você diferente de resumos,
responda: "Vamos voltar ao trabalho que interessa?"
4. Responda sempre em português.
5. Se não souber a resposta, responda: "Desculpe, mas não tenho
esta informação."
6. Nas suas respostas, não forneça os nomes dos dataframes, apenas
responda às perguntas.
7. Destaque os principais achados e tendências nos dados sempre
que possível.
8. Se aplicável, sugira possíveis ações ou recomendações baseadas
nos dados analisados.
"""
# Chamada à API Groq
chat_rci = client.chat.completions.create(
messages=[
{
"role": "system",
"content": context
},
*st.session_state.groq_chat_history,
],
model="llama3-70b-8192",
temperature=0.3,
max_tokens=2500,
)
# Processamento da resposta
if chat_rci.choices and len(chat_rci.choices) > 0:
response_message = chat_rci.choices[0].message.content
else:
response_message = "Não foi possível gerar uma resposta."
# Adição da resposta ao histórico
st.session_state.groq_chat_history.append({
"role": "assistant",
"content": response_message
})
# Exibição da nova resposta
with chat_container, st.chat_message("assistant"):
st.markdown(response_message)
except Exception as e:
st.error(f"Ocorreu um erro: {str(e)}")
# Rolar para o final do chat após uma nova mensagem
st.rerun()
# Botão para limpar o histórico do chat
if st.sidebar.button("Limpar histórico do chat"):
st.session_state.groq_chat_history = []
st.rerun()
st.sidebar.markdown("""
#### - Iniciativa - Ubs Flamengo
### Links:
##
##### - [PEC SUS](https://sape.pecsus.com.br/) 📝
##### - [GitHub - Dr Guilherme](http://dr-guilhermeapolinario.com) 🌎
""")
add_vertical_space(5)
st.divider() |