Update modules/planilha.py
Browse files- modules/planilha.py +8 -47
modules/planilha.py
CHANGED
|
@@ -6,7 +6,6 @@ from .shared_state import state # Importa o estado compartilhado
|
|
| 6 |
# Variável global para armazenar o DataFrame original
|
| 7 |
original_df = None
|
| 8 |
|
| 9 |
-
# PLANILHA
|
| 10 |
def list_sheets(file):
|
| 11 |
if file is None:
|
| 12 |
return "Nenhum arquivo carregado.", []
|
|
@@ -47,7 +46,6 @@ def add_new_variable(file, sheet_name, first_var, operation, second_var, new_var
|
|
| 47 |
df = pd.read_excel(file.name, sheet_name=sheet_name)
|
| 48 |
if first_var not in df.columns or second_var not in df.columns:
|
| 49 |
return pd.DataFrame({"Erro": ["Variáveis selecionadas não existem no DataFrame."]})
|
| 50 |
-
|
| 51 |
try:
|
| 52 |
if operation == "Adição":
|
| 53 |
df[new_var_name] = df[first_var] + df[second_var]
|
|
@@ -61,7 +59,6 @@ def add_new_variable(file, sheet_name, first_var, operation, second_var, new_var
|
|
| 61 |
return pd.DataFrame({"Erro": ["Divisão por zero detectada."]})
|
| 62 |
except Exception as e:
|
| 63 |
return pd.DataFrame({"Erro": [f"Erro ao realizar a operação: {str(e)}"]})
|
| 64 |
-
|
| 65 |
return df
|
| 66 |
|
| 67 |
def update_variable_choices(file, sheet_name):
|
|
@@ -83,19 +80,17 @@ def update_columns(file, sheet_name):
|
|
| 83 |
gr.update(choices=columns, value=[], interactive=True)
|
| 84 |
)
|
| 85 |
|
| 86 |
-
# Função para restaurar o DataFrame ao estado inicial
|
| 87 |
def restore_dataframe():
|
| 88 |
global original_df
|
| 89 |
if original_df is not None:
|
| 90 |
-
return original_df, None
|
| 91 |
-
return pd.DataFrame(), None
|
| 92 |
|
| 93 |
def finalize_dataframe(file, sheet_name, selected_columns, first_var, operation, second_var, new_var_name, add_index):
|
| 94 |
if file is None or not sheet_name:
|
| 95 |
return pd.DataFrame({"Erro": ["Carregue um arquivo e selecione uma aba."]})
|
| 96 |
df = pd.read_excel(file.name, sheet_name=sheet_name)
|
| 97 |
|
| 98 |
-
# Adiciona a nova variável, se necessário
|
| 99 |
if new_var_name and first_var and second_var:
|
| 100 |
try:
|
| 101 |
if operation == "Adição":
|
|
@@ -111,74 +106,56 @@ def finalize_dataframe(file, sheet_name, selected_columns, first_var, operation,
|
|
| 111 |
except Exception as e:
|
| 112 |
return pd.DataFrame({"Erro": [f"Erro ao realizar a operação: {str(e)}"]})
|
| 113 |
|
| 114 |
-
# Adiciona a nova variável às colunas selecionadas, se existir
|
| 115 |
if new_var_name and new_var_name in df.columns:
|
| 116 |
selected_columns.append(new_var_name)
|
| 117 |
-
|
| 118 |
if selected_columns:
|
| 119 |
df = df[selected_columns]
|
| 120 |
|
| 121 |
-
# Adiciona índice na primeira coluna, se necessário
|
| 122 |
if add_index:
|
| 123 |
df.insert(0, 'Índice', range(1, len(df) + 1))
|
| 124 |
|
| 125 |
-
# Salvando DataFrame filtrado em arquivo CSV
|
| 126 |
file_path = "Planilha_final.xlsx"
|
| 127 |
df.to_excel(file_path)
|
| 128 |
-
|
| 129 |
return df, file_path
|
| 130 |
|
| 131 |
def planilha_tab(filtered_df_output):
|
| 132 |
-
# Criação da aba
|
| 133 |
with gr.Tab("Carregar Planilha"):
|
| 134 |
-
# Checkbox para escolher entre usar o arquivo da aba anterior ou carregar um novo arquivo
|
| 135 |
-
use_filtered_df = gr.Checkbox(label="Usar arquivo da aba anterior", value=True)
|
| 136 |
-
|
| 137 |
-
# Upload do arquivo Excel
|
| 138 |
with gr.Row():
|
| 139 |
-
excel_file = gr.File(label="Carregue sua planilha Excel", file_types=[".xls", ".xlsx"], elem_classes=["small-file-upload"]
|
| 140 |
|
| 141 |
with gr.Row():
|
| 142 |
list_button = gr.Button("Listar Abas")
|
| 143 |
|
| 144 |
-
# Exibição das abas disponíveis e seleção de aba
|
| 145 |
with gr.Row():
|
| 146 |
sheet_output = gr.Textbox(label="Abas disponíveis", interactive=False)
|
| 147 |
sheet_dropdown = gr.Dropdown(label="Selecione uma aba")
|
| 148 |
|
| 149 |
-
# Botão para carregar aba e exibir colunas
|
| 150 |
with gr.Row():
|
| 151 |
load_button = gr.Button("Carregar Aba")
|
| 152 |
|
| 153 |
-
# Informações e exibição de colunas da aba carregada
|
| 154 |
with gr.Row():
|
| 155 |
sheet_info = gr.Text(label="Informação de Linhas e Colunas")
|
| 156 |
sheet_columns = gr.JSON(label="Lista de Colunas", visible=False)
|
| 157 |
view_sheet_checkbox = gr.Checkbox(label="Visualizar a planilha", value=False)
|
| 158 |
|
| 159 |
-
# Exibição do conteúdo da aba selecionada
|
| 160 |
with gr.Row():
|
| 161 |
sheet_content = gr.Dataframe(
|
| 162 |
label="Conteúdo da Aba Selecionada",
|
| 163 |
visible=False
|
| 164 |
)
|
| 165 |
|
| 166 |
-
# CheckboxGroup para seleção de colunas
|
| 167 |
with gr.Row():
|
| 168 |
column_selector = gr.CheckboxGroup(
|
| 169 |
label="Selecione colunas para análise",
|
| 170 |
-
choices=[],
|
| 171 |
interactive=True
|
| 172 |
)
|
| 173 |
|
| 174 |
-
# Checkbox para adicionar índice na primeira coluna
|
| 175 |
with gr.Row():
|
| 176 |
add_index_checkbox = gr.Checkbox(label="Adicionar índice na primeira coluna", value=False)
|
| 177 |
|
| 178 |
-
# Checkbox para habilitar operações com variáveis
|
| 179 |
operations_checkbox = gr.Checkbox(label="Operações com variáveis", value=False)
|
| 180 |
|
| 181 |
-
# Elementos relacionados às operações, inicialmente invisíveis
|
| 182 |
with gr.Row(visible=False) as operations_inputs:
|
| 183 |
variable_name_textbox = gr.Textbox(
|
| 184 |
label="Nome da nova variável",
|
|
@@ -201,47 +178,31 @@ def planilha_tab(filtered_df_output):
|
|
| 201 |
interactive=True
|
| 202 |
)
|
| 203 |
|
| 204 |
-
# Associações de eventos
|
| 205 |
-
use_filtered_df.change(lambda x: gr.update(visible=not x), inputs=[use_filtered_df], outputs=[excel_file])
|
| 206 |
list_button.click(update_dropdown, inputs=[excel_file], outputs=[sheet_output, sheet_dropdown])
|
| 207 |
-
load_button.click(update_columns, inputs=[excel_file, sheet_dropdown], outputs=[sheet_content, sheet_info, sheet_columns])
|
| 208 |
-
load_button.click(update_column_selector, inputs=[excel_file, sheet_dropdown], outputs=[column_selector])
|
| 209 |
view_sheet_checkbox.change(toggle_sheet_visibility, inputs=[view_sheet_checkbox], outputs=[sheet_content])
|
| 210 |
operations_checkbox.change(toggle_operations_inputs, inputs=[operations_checkbox], outputs=[operations_inputs])
|
| 211 |
|
| 212 |
apply_operations_button = gr.Button("Criar Nova Variável")
|
| 213 |
new_df_output = gr.Dataframe(label="Novo DataFrame", interactive=True)
|
|
|
|
| 214 |
apply_operations_button.click(add_new_variable, inputs=[excel_file, sheet_dropdown, first_variable_dropdown, operation_dropdown, second_variable_dropdown, variable_name_textbox], outputs=[new_df_output])
|
| 215 |
load_button.click(update_variable_choices, inputs=[excel_file, sheet_dropdown], outputs=[first_variable_dropdown, second_variable_dropdown])
|
| 216 |
|
| 217 |
-
# Botão para finalizar o DataFrame
|
| 218 |
finalize_button = gr.Button("Finalizar DataFrame")
|
| 219 |
download_output = gr.File(label="Baixar Novo Dataframe")
|
|
|
|
| 220 |
finalize_button.click(finalize_dataframe, inputs=[excel_file, sheet_dropdown, column_selector, first_variable_dropdown, operation_dropdown, second_variable_dropdown, variable_name_textbox, add_index_checkbox], outputs=[new_df_output, download_output])
|
| 221 |
|
| 222 |
-
# Adicionar botões "Restaurar" e "Limpar"
|
| 223 |
with gr.Row():
|
| 224 |
restore_button = gr.Button("Restaurar")
|
| 225 |
-
clear_button = gr.ClearButton(components=[excel_file, sheet_output, sheet_dropdown, sheet_info, sheet_columns, view_sheet_checkbox, sheet_content, column_selector, add_index_checkbox, operations_checkbox, variable_name_textbox, first_variable_dropdown, operation_dropdown, second_variable_dropdown, new_df_output, download_output],
|
| 226 |
-
value="Limpar")
|
| 227 |
|
| 228 |
-
# Associações de eventos para os botões "Restaurar"
|
| 229 |
restore_button.click(restore_dataframe, outputs=[new_df_output, download_output])
|
| 230 |
|
| 231 |
-
# Se a opção "Usar arquivo da aba anterior" estiver marcada, carregue o filtered_df_output
|
| 232 |
-
def load_filtered_df(use_filtered_df, filtered_df_output):
|
| 233 |
-
if use_filtered_df:
|
| 234 |
-
df = pd.DataFrame(filtered_df_output)
|
| 235 |
-
return df, f"{df.shape[0]} linhas e {df.shape[1]} colunas", df.columns.tolist(), df.columns.tolist()
|
| 236 |
-
return None, "", [], []
|
| 237 |
-
|
| 238 |
-
use_filtered_df.change(load_filtered_df, inputs=[use_filtered_df, filtered_df_output], outputs=[sheet_content, sheet_info, column_selector, column_selector])
|
| 239 |
-
|
| 240 |
return locals(), new_df_output
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
### Manipulação de colunas
|
| 247 |
### Receber planilha da aba dados
|
|
|
|
| 6 |
# Variável global para armazenar o DataFrame original
|
| 7 |
original_df = None
|
| 8 |
|
|
|
|
| 9 |
def list_sheets(file):
|
| 10 |
if file is None:
|
| 11 |
return "Nenhum arquivo carregado.", []
|
|
|
|
| 46 |
df = pd.read_excel(file.name, sheet_name=sheet_name)
|
| 47 |
if first_var not in df.columns or second_var not in df.columns:
|
| 48 |
return pd.DataFrame({"Erro": ["Variáveis selecionadas não existem no DataFrame."]})
|
|
|
|
| 49 |
try:
|
| 50 |
if operation == "Adição":
|
| 51 |
df[new_var_name] = df[first_var] + df[second_var]
|
|
|
|
| 59 |
return pd.DataFrame({"Erro": ["Divisão por zero detectada."]})
|
| 60 |
except Exception as e:
|
| 61 |
return pd.DataFrame({"Erro": [f"Erro ao realizar a operação: {str(e)}"]})
|
|
|
|
| 62 |
return df
|
| 63 |
|
| 64 |
def update_variable_choices(file, sheet_name):
|
|
|
|
| 80 |
gr.update(choices=columns, value=[], interactive=True)
|
| 81 |
)
|
| 82 |
|
|
|
|
| 83 |
def restore_dataframe():
|
| 84 |
global original_df
|
| 85 |
if original_df is not None:
|
| 86 |
+
return original_df, None
|
| 87 |
+
return pd.DataFrame(), None
|
| 88 |
|
| 89 |
def finalize_dataframe(file, sheet_name, selected_columns, first_var, operation, second_var, new_var_name, add_index):
|
| 90 |
if file is None or not sheet_name:
|
| 91 |
return pd.DataFrame({"Erro": ["Carregue um arquivo e selecione uma aba."]})
|
| 92 |
df = pd.read_excel(file.name, sheet_name=sheet_name)
|
| 93 |
|
|
|
|
| 94 |
if new_var_name and first_var and second_var:
|
| 95 |
try:
|
| 96 |
if operation == "Adição":
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
return pd.DataFrame({"Erro": [f"Erro ao realizar a operação: {str(e)}"]})
|
| 108 |
|
|
|
|
| 109 |
if new_var_name and new_var_name in df.columns:
|
| 110 |
selected_columns.append(new_var_name)
|
|
|
|
| 111 |
if selected_columns:
|
| 112 |
df = df[selected_columns]
|
| 113 |
|
|
|
|
| 114 |
if add_index:
|
| 115 |
df.insert(0, 'Índice', range(1, len(df) + 1))
|
| 116 |
|
|
|
|
| 117 |
file_path = "Planilha_final.xlsx"
|
| 118 |
df.to_excel(file_path)
|
|
|
|
| 119 |
return df, file_path
|
| 120 |
|
| 121 |
def planilha_tab(filtered_df_output):
|
|
|
|
| 122 |
with gr.Tab("Carregar Planilha"):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
with gr.Row():
|
| 124 |
+
excel_file = gr.File(label="Carregue sua planilha Excel", file_types=[".xls", ".xlsx"], elem_classes=["small-file-upload"])
|
| 125 |
|
| 126 |
with gr.Row():
|
| 127 |
list_button = gr.Button("Listar Abas")
|
| 128 |
|
|
|
|
| 129 |
with gr.Row():
|
| 130 |
sheet_output = gr.Textbox(label="Abas disponíveis", interactive=False)
|
| 131 |
sheet_dropdown = gr.Dropdown(label="Selecione uma aba")
|
| 132 |
|
|
|
|
| 133 |
with gr.Row():
|
| 134 |
load_button = gr.Button("Carregar Aba")
|
| 135 |
|
|
|
|
| 136 |
with gr.Row():
|
| 137 |
sheet_info = gr.Text(label="Informação de Linhas e Colunas")
|
| 138 |
sheet_columns = gr.JSON(label="Lista de Colunas", visible=False)
|
| 139 |
view_sheet_checkbox = gr.Checkbox(label="Visualizar a planilha", value=False)
|
| 140 |
|
|
|
|
| 141 |
with gr.Row():
|
| 142 |
sheet_content = gr.Dataframe(
|
| 143 |
label="Conteúdo da Aba Selecionada",
|
| 144 |
visible=False
|
| 145 |
)
|
| 146 |
|
|
|
|
| 147 |
with gr.Row():
|
| 148 |
column_selector = gr.CheckboxGroup(
|
| 149 |
label="Selecione colunas para análise",
|
| 150 |
+
choices=[],
|
| 151 |
interactive=True
|
| 152 |
)
|
| 153 |
|
|
|
|
| 154 |
with gr.Row():
|
| 155 |
add_index_checkbox = gr.Checkbox(label="Adicionar índice na primeira coluna", value=False)
|
| 156 |
|
|
|
|
| 157 |
operations_checkbox = gr.Checkbox(label="Operações com variáveis", value=False)
|
| 158 |
|
|
|
|
| 159 |
with gr.Row(visible=False) as operations_inputs:
|
| 160 |
variable_name_textbox = gr.Textbox(
|
| 161 |
label="Nome da nova variável",
|
|
|
|
| 178 |
interactive=True
|
| 179 |
)
|
| 180 |
|
|
|
|
|
|
|
| 181 |
list_button.click(update_dropdown, inputs=[excel_file], outputs=[sheet_output, sheet_dropdown])
|
| 182 |
+
load_button.click(update_columns, inputs=[excel_file, sheet_dropdown], outputs=[sheet_content, sheet_info, sheet_columns, column_selector])
|
|
|
|
| 183 |
view_sheet_checkbox.change(toggle_sheet_visibility, inputs=[view_sheet_checkbox], outputs=[sheet_content])
|
| 184 |
operations_checkbox.change(toggle_operations_inputs, inputs=[operations_checkbox], outputs=[operations_inputs])
|
| 185 |
|
| 186 |
apply_operations_button = gr.Button("Criar Nova Variável")
|
| 187 |
new_df_output = gr.Dataframe(label="Novo DataFrame", interactive=True)
|
| 188 |
+
|
| 189 |
apply_operations_button.click(add_new_variable, inputs=[excel_file, sheet_dropdown, first_variable_dropdown, operation_dropdown, second_variable_dropdown, variable_name_textbox], outputs=[new_df_output])
|
| 190 |
load_button.click(update_variable_choices, inputs=[excel_file, sheet_dropdown], outputs=[first_variable_dropdown, second_variable_dropdown])
|
| 191 |
|
|
|
|
| 192 |
finalize_button = gr.Button("Finalizar DataFrame")
|
| 193 |
download_output = gr.File(label="Baixar Novo Dataframe")
|
| 194 |
+
|
| 195 |
finalize_button.click(finalize_dataframe, inputs=[excel_file, sheet_dropdown, column_selector, first_variable_dropdown, operation_dropdown, second_variable_dropdown, variable_name_textbox, add_index_checkbox], outputs=[new_df_output, download_output])
|
| 196 |
|
|
|
|
| 197 |
with gr.Row():
|
| 198 |
restore_button = gr.Button("Restaurar")
|
| 199 |
+
clear_button = gr.ClearButton(components=[excel_file, sheet_output, sheet_dropdown, sheet_info, sheet_columns, view_sheet_checkbox, sheet_content, column_selector, add_index_checkbox, operations_checkbox, variable_name_textbox, first_variable_dropdown, operation_dropdown, second_variable_dropdown, new_df_output, download_output], value="Limpar")
|
|
|
|
| 200 |
|
|
|
|
| 201 |
restore_button.click(restore_dataframe, outputs=[new_df_output, download_output])
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
return locals(), new_df_output
|
| 204 |
|
| 205 |
|
| 206 |
|
|
|
|
|
|
|
| 207 |
### Manipulação de colunas
|
| 208 |
### Receber planilha da aba dados
|