It looks like you've provided a complete and complex Dash application code meant to create a performance dashboard using data from CSV files. Below, I will review the structure and suggest improvements, while also correcting some formatting errors and code style issues.
Key Considerations and Improvements:
-
Formatting: The code provided has indentation and formatting errors when dealing with blocks, especially for functions, classes, and callback definitions. Proper indentation is crucial in Python for defining scopes.
-
Error Handling: While you have logging implemented, ensure that errors are not just logged, but perhaps also reported to the user in a user-friendly way through Dash components (like html.Div).
-
Code Modularity: If the application grows, consider splitting the code into modules. For instance, separate files for callbacks, layout definitions, and utility functions can help maintainability.
-
Localization: You set the locale for numeric formatting explicitly. Make sure the application execution environment supports this locale.
-
Documentation: Adding docstrings to functions and methods enhances code readability and maintainability.
-
Global Variables: name should be replaced with __name__ in the logging setup and the if __name__ == '__main__' block.
-
Update Methods: When you want to update specific components, return dash.no_update for other outputs, instead of returning them as empty lists or dictionaries.
Here’s a refactored snippet maintaining the application structure but correcting the above issues:
import pandas as pd
import plotly.express as px
from dash import Dash, dcc, html, Input, Output, dash_table, State, callback_context
import locale
import base64
import io
from datetime import datetime
import logging
import os
# Configurar o logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Inicializar o Dash app
app = Dash(__name__)
# Layout do dashboard
app.layout = html.Div([
html.H1("Dashboard de Performance Executiva", style={'textAlign': 'center', 'fontSize': '36px', 'fontWeight': 'bold'}),
# Componente de upload
dcc.Upload(
id='upload-data',
children=html.Button('Selecionar Arquivo CSV', style={
'fontSize': '18px',
'padding': '12px 24px',
'borderRadius': '5px',
'border': '1px solid #ccc',
'background-color': '#00AEEF',
'color': 'white',
'cursor': 'pointer'
}),
style={'display': 'flex', 'justifyContent': 'center', 'marginBottom': '20px'},
multiple=False
),
dcc.Store(id='processed-data'),
# Botão Selecionar Todos
html.Div([
html.Button('Selecionar Todos', id='selecionar-todos', n_clicks=0, style={
'fontSize': '16px',
'padding': '10px 20px',
'borderRadius': '5px',
'border': 'none',
'background-color': '#003366',
'color': 'white',
'cursor': 'pointer',
'marginBottom': '20px'
})
], style={'display': 'flex', 'justifyContent': 'center'}),
# Checklist para Executivos
html.Div([
html.Label('Selecione os Executivos:', style={'fontSize': '20px', 'fontWeight': 'bold'}),
dcc.Checklist(
id='executivo-checkbox',
options=[],
value=[],
inline=True,
inputStyle={"margin-right": "10px"},
labelStyle={"display": "block", "fontSize": "18px", "fontWeight": "bold"}
),
], style={'margin': '0 50px'}),
# Dropdown para a ordem
html.Div([
html.Label('Selecione a Ordem:', style={'fontSize': '20px', 'fontWeight': 'bold', 'marginTop': '20px'}),
dcc.Dropdown(
id='ordem-dropdown',
options=[
{'label': 'Do Maior para o Menor', 'value': 'desc'},
{'label': 'Do Menor para o Maior', 'value': 'asc'}
],
value='desc',
clearable=False,
style={'fontSize': '18px'}
),
], style={'margin': '0 50px'}),
# Botão para baixar o gráfico
html.Div([
html.Button('Baixar Gráfico em Alta Resolução', id='download-image', n_clicks=0, style={
'fontSize': '16px',
'padding': '12px 24px',
'borderRadius': '5px',
'border': 'none',
'background-color': '#28a745',
'color': 'white',
'cursor': 'pointer',
'marginTop': '20px',
'marginBottom': '20px'
})
], style={'display': 'flex', 'justifyContent': 'center'}),
dcc.Download(id="download"),
# Gráfico
dcc.Graph(id='grafico-diario'),
# Tabela
dash_table.DataTable(
id='tabela-executivos',
style_table={'overflowX': 'auto'},
style_cell={
'textAlign': 'left',
'padding': '10px',
'minWidth': '150px',
'fontSize': '16px'
},
style_header={
'backgroundColor': '#003366',
'color': 'white',
'fontWeight': 'bold',
'fontSize': '18px'
}
)
])
def parse_contents(contents, filename):
"""Decodes and processes the uploaded CSV file content."""
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename.lower():
locale.setlocale(locale.LC_NUMERIC, 'pt_BR.UTF-8')
df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), delimiter=';')
else:
return html.Div(['Arquivo não suportado. Por favor, carregue um arquivo CSV.'])
except Exception as e:
logger.error(f'Erro ao processar o arquivo: {e}')
return html.Div([f'Ocorreu um erro ao processar o arquivo: {str(e)}'])
# Clean column names
df.columns = df.columns.str.strip()
logger.info(f'Colunas do CSV: {df.columns.tolist()}')
required_columns = ['Executivo', 'Nº Quartil - set/24', '% Quartil - set/24']
if not all(col in df.columns for col in required_columns):
return html.Div(['O arquivo carregado não contém as colunas necessárias: Executivo, Nº Quartil - set/24, % Quartil - set/24.'])
# Filter out unwanted executives
executivos_indesejados = ['regis alves dourado', 'TBA - CN - JUNDIAI - 2']
df = df[~df['Executivo'].str.lower().isin([nome.lower() for nome in executivos_indesejados])]
logger.info(f'Número de executivos após remoção: {len(df["Executivo"].unique())}')
# Clean non-numeric values in metric columns
for col in ['Nº Quartil - set/24', '% Quartil - set/24']:
df[col] = pd.to_numeric(df[col], errors='coerce')
# Aggregate data by Executive
df_agrupado = df.groupby('Executivo').agg({
'Nº Quartil - set/24': 'sum',
'% Quartil - set/24': 'mean'
}).reset_index()
df_agrupado['Primeiro Nome'] = df_agrupado['Executivo'].str.split().str[0]
return df_agrupado
def generate_figure(df_filtrado):
"""Generates a bar chart based on the filtered DataFrame."""
logger.info(f'Gerando gráfico com {len(df_filtrado)} executivos.')
# Create bar chart
fig = px.bar(df_filtrado,
x='Primeiro Nome',
y='% Quartil - set/24',
title="% RVM e Quartil",
labels={'% Quartil - set/24': '% RVM e Quartil', 'Primeiro Nome': 'Executivo'},
barmode='group',
color_discrete_sequence=['#00AEEF']) # Unique color for the bar
fig.update_traces(
text=[
f"{row['% Quartil - set/24']}% ({int(row['Nº Quartil - set/24'])})" if not pd.isna(row['% Quartil - set/24']) and not pd.isna(row['Nº Quartil - set/24']) else 'N/A'
for _, row in df_filtrado.iterrows()
],
textposition='outside',
textfont=dict(size=16, color='black', family='Arial Black')
)
# Layout adjustments
fig.update_layout(
# ...
# (Add layout configurations as needed)
)
return fig
# Define callback functions
@app.callback(
[Output('processed-data', 'data'),
Output('executivo-checkbox', 'options'),
Output('executivo-checkbox', 'value')],
[Input('upload-data', 'contents'),
Input('selecionar-todos', 'n_clicks')],
[State('upload-data', 'filename'),
State('processed-data', 'data')]
)
def update_data(contents, n_clicks, filename, stored_data):
ctx = callback_context
if not ctx.triggered:
logger.info('Nenhum trigger acionado no callback update_data.')
return dash.no_update, dash.no_update, dash.no_update
trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
logger.info(f'Callback update_data acionado por: {trigger_id}')
if trigger_id == 'upload-data' and contents:
df_agrupado = parse_contents(contents, filename)
if isinstance(df_agrupado, pd.DataFrame):
data = df_agrupado.to_dict('records')
options = [{'label': exec, 'value': exec} for exec in df_agrupado['Executivo'].unique()]
value = df_agrupado['Executivo'].unique().tolist()
logger.info(f'Dados processados e opções do checklist atualizadas.')
return data, options, value
else:
logger.warning('Falha no processamento dos dados no upload.')
return dash.no_update, dash.no_update, dash.no_update
elif trigger_id == 'selecionar-todos' and stored_data:
executivos = [item['Executivo'] for item in stored_data]
logger.info(f'Botão "Selecionar Todos" clicado. Selecionando {len(executivos)} executivos.')
return dash.no_update, dash.no_update, executivos
logger.info('Nenhuma condição atendida no callback update_data.')
return dash.no_update, dash.no_update, dash.no_update
@app.callback(
[Output('grafico-diario', 'figure'),
Output('tabela-executivos', 'data')],
[Input('executivo-checkbox', 'value'),
Input('ordem-dropdown', 'value'),
Input('processed-data', 'data')]
)
def update_graphs(executivos_selecionados, ordem_selecionada, data):
if data is None or not executivos_selecionados:
logger.info('Dados ausentes ou nenhum executivo selecionado. Retornando gráfico e tabela vazios.')
return {}, [] # Gráfico vazio e tabela vazia
df_filtrado = pd.DataFrame(data)
df_filtrado = df_filtrado[df_filtrado['Executivo'].isin(executivos_selecionados)]
if df_filtrado.empty:
logger.info('Nenhum dado após filtro. Retornando gráfico e tabela vazios.')
return {}, []
ascending = (ordem_selecionada == 'asc')
df_filtrado = df_filtrado.sort_values(by='% Quartil - set/24', ascending=ascending)
fig_diario = generate_figure(df_filtrado)
tabela_data = df_filtrado.to_dict('records')
return fig_diario, tabela_data
@app.callback(
Output("download", "data"),
Input("download-image", "n_clicks"),
State("executivo-checkbox", "value"),
State("ordem-dropdown", "value"),
State("processed-data", "data"),
prevent_initial_call=True,
)
def generate_image(n_clicks, executivos_selecionados, ordem_selecionada, data):
logger.info(f'Callback generate_image acionado com n_clicks={n_clicks}')
if n_clicks > 0 and data is not None and executivos_selecionados:
df_filtrado = pd.DataFrame(data)
df_filtrado = df_filtrado[df_filtrado['Executivo'].isin(executivos_selecionados)]
if df_filtrado.empty:
logger.warning('DataFrame filtrado está vazio no callback generate_image.')
return dash.no_update
ascending = (ordem_selecionada == 'asc')
df_filtrado = df_filtrado.sort_values(by='% Quartil - set/24', ascending=ascending)
fig_diario = generate_figure(df_filtrado)
try:
logger.info('Tentando gerar a imagem do gráfico.')
img_bytes = fig_diario.to_image(format="png", scale=4)
except Exception as e:
logger.error(f'Erro ao gerar a imagem: {e}')
return dash.no_update
data_atual = datetime.now().strftime("%d-%m-%Y")
nome_arquivo = f"RVM - {data_atual}.png"
output_dir = r"C:\Users\dourado\OneDrive - Cielo\REGIONALSP\graficos\Nova pasta"
os.makedirs(output_dir, exist_ok=True)
file_path = os.path.join(output_dir, nome_arquivo)
try:
with open(file_path, "wb") as f:
f.write(img_bytes)
logger.info(f'Imagem salva em {file_path}')
except Exception as e:
logger.error(f'Erro ao salvar a imagem no disco: {e}')
return dash.no_update
logger.info(f'Gerando download da imagem: {nome_arquivo}')
return dcc.send_bytes(img_bytes, nome_arquivo)
logger.info('Condições para download não atendidas no callback generate_image.')
return dash.no_update
if __name__ == '__main__':
app.run_server(debug=True)
Summary
The above refactored code addresses some critical issues and enhances readability and structure. Make sure to customize and test with your specific dataset, checking particularly the parsing rules and any additional features you may want to add. Happy coding!