Spaces:
Sleeping
Sleeping
File size: 8,625 Bytes
0a90ad2 5562b19 0a90ad2 781ba69 0a90ad2 781ba69 0a90ad2 781ba69 0a90ad2 781ba69 0a90ad2 781ba69 0a90ad2 781ba69 5562b19 0a90ad2 5562b19 0a90ad2 5562b19 0a90ad2 781ba69 0a90ad2 781ba69 cfded06 781ba69 0a90ad2 781ba69 0d9c142 781ba69 0a90ad2 781ba69 0a90ad2 5562b19 0a90ad2 781ba69 |
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 |
import gradio as gr
import pandas as pd
import re
import os
from datetime import timedelta
def parse_duration(duration_str):
try:
h, m, s = map(int, duration_str.split(':'))
return timedelta(hours=h, minutes=m, seconds=s)
except:
return timedelta(0)
def format_timedelta(td):
total_seconds = int(td.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours:02}:{minutes:02}:{seconds:02}"
def normalize_html_to_csv(input_html_path, output_csv_path):
html_data = pd.read_html(input_html_path)
data = html_data[0]
data.to_csv(output_csv_path, index=False)
def normalize_multiple_excel_to_csv(input_directory, output_directory):
input_excel_paths = [os.path.join(input_directory, f) for f in os.listdir(input_directory) if f.endswith('.xlsx')]
output_csv_paths = [os.path.join(output_directory, os.path.splitext(f)[0] + '.csv') for f in os.listdir(input_directory) if f.endswith('.xlsx')]
for input_excel_path, output_csv_path in zip(input_excel_paths, output_csv_paths):
excel_data = pd.read_excel(input_excel_path)
unnecessary_columns = [col for col in excel_data.columns if 'Unnamed' in col]
if unnecessary_columns:
excel_data = excel_data.drop(columns=unnecessary_columns)
excel_data.to_csv(output_csv_path, index=False)
def extract_aluno_pattern(nome):
if isinstance(nome, str):
match = re.search(r"(\d{8,9}-\w{2})", nome.lower())
return match.group(1) if match else None
return None
def match_alunos(tarefas_csv_path, alunos_csv_path, contador_csv_path):
try:
tarefas_df = pd.read_csv(tarefas_csv_path)
alunos_df = pd.read_csv(alunos_csv_path)
except pd.errors.EmptyDataError:
print(f"Arquivo {tarefas_csv_path} ou {alunos_csv_path} está vazio. Pulando...")
return
print(f"Tarefas DataFrame (antes da normalização):\n{tarefas_df.head()}")
print(f"Alunos DataFrame (antes da normalização):\n{alunos_df.head()}")
tarefas_df.columns = tarefas_df.columns.str.strip()
alunos_df.columns = alunos_df.columns.str.strip()
if 'Aluno' not in tarefas_df.columns or 'Nota' not in tarefas_df.columns or 'Duração' not in tarefas_df.columns:
print(f"Colunas 'Aluno', 'Nota' ou 'Duração' não encontradas no arquivo {tarefas_csv_path}. Pulando este arquivo.")
return
try:
contador_df = pd.read_csv(contador_csv_path)
except FileNotFoundError:
contador_df = pd.DataFrame(columns=['Nome do Aluno', 'Tarefas Completadas', 'Acertos Absolutos', 'Total Tempo'])
if 'Tarefas Completadas' not in contador_df.columns:
contador_df['Tarefas Completadas'] = 0
if 'Acertos Absolutos' not in contador_df.columns:
contador_df['Acertos Absolutos'] = 0
if 'Total Tempo' not in contador_df.columns:
contador_df['Total Tempo'] = '00:00:00'
def generate_aluno_pattern(ra, dig_ra):
ra_str = str(ra).zfill(9)
ra_without_first_two_digits = ra_str[2:]
return f"{ra_str[1]}{ra_without_first_two_digits}{dig_ra}-sp".lower()
alunos_df['Aluno_Pattern'] = alunos_df.apply(lambda row: generate_aluno_pattern(row['RA'], row['Dig. RA']), axis=1)
print(f"Alunos DataFrame (com padrão):\n{alunos_df.head()}")
def extract_aluno_pattern(nome):
if isinstance(nome, str):
match = re.search(r'\d+.*', nome.lower())
return match.group(0) if match else None
return None
tarefas_df['Aluno_Pattern'] = tarefas_df['Aluno'].apply(extract_aluno_pattern)
tarefas_df['Duração'] = tarefas_df['Duração'].apply(parse_duration)
print(f"Tarefas DataFrame (com padrão):\n{tarefas_df.head()}")
matched_alunos = alunos_df[alunos_df['Aluno_Pattern'].isin(tarefas_df['Aluno_Pattern'])]
print(f"Matched Alunos DataFrame:\n{matched_alunos.head()}")
result_df = matched_alunos[['Nome do Aluno']].drop_duplicates()
for aluno in result_df['Nome do Aluno']:
aluno_pattern = alunos_df.loc[alunos_df['Nome do Aluno'] == aluno, 'Aluno_Pattern'].values[0]
aluno_tarefas = tarefas_df[tarefas_df['Aluno_Pattern'] == aluno_pattern]
nota_total = aluno_tarefas['Nota'].sum()
tempo_total = aluno_tarefas['Duração'].sum()
if aluno in contador_df['Nome do Aluno'].values:
contador_df.loc[contador_df['Nome do Aluno'] == aluno, 'Tarefas Completadas'] += 1
contador_df.loc[contador_df['Nome do Aluno'] == aluno, 'Acertos Absolutos'] += nota_total
current_total_tempo = pd.to_timedelta(contador_df.loc[contador_df['Nome do Aluno'] == aluno, 'Total Tempo'].values[0])
contador_df.loc[contador_df['Nome do Aluno'] == aluno, 'Total Tempo'] = str(current_total_tempo + tempo_total)
else:
contador_df = pd.concat([contador_df, pd.DataFrame({'Nome do Aluno': [aluno], 'Tarefas Completadas': [1], 'Acertos Absolutos': [nota_total], 'Total Tempo': [str(tempo_total)]})], ignore_index=True)
print(f"Contador DataFrame (atualizado):\n{contador_df.head()}")
contador_df.to_csv(contador_csv_path, index=False)
return result_df
def process_all_tarefas_in_directory(directory, alunos_csv_path, contador_csv_path, relatorio_csv_path):
tarefas_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.csv') and f not in ['alunos_fim.csv', 'contador_tarefas.csv']]
for i, tarefas_file in enumerate(tarefas_files):
print(f"Processando arquivo {i+1}/{len(tarefas_files)}: {tarefas_file}")
match_alunos(tarefas_file, alunos_csv_path, contador_csv_path)
print(f"Arquivo {tarefas_file} processado.")
process_relatorios(contador_csv_path, relatorio_csv_path)
def process_relatorios(contador_csv_path, relatorio_csv_path):
contador_df = pd.read_csv(contador_csv_path)
contador_df['Média de Acertos'] = ((contador_df['Acertos Absolutos'] / (contador_df['Tarefas Completadas'] * 2)) * 100).round(2).astype(str) + '%'
contador_df['Total Tempo'] = pd.to_timedelta(contador_df['Total Tempo'])
contador_df['Tempo Médio por Tarefa'] = (contador_df['Total Tempo'] / contador_df['Tarefas Completadas']).apply(format_timedelta)
contador_df['Total Tempo'] = contador_df['Total Tempo'].apply(format_timedelta)
contador_df = contador_df.sort_values(by='Tarefas Completadas', ascending=False)
contador_df.to_csv(relatorio_csv_path, index=False)
return contador_df
def process_inputs(html_file, tarefa_files):
input_directory = "temp_files"
output_directory = "temp_files"
os.makedirs(input_directory, exist_ok=True)
os.makedirs(output_directory, exist_ok=True)
html_path = os.path.join(input_directory, "alunos.htm")
with open(html_path, "wb") as f:
f.write(html_file)
alunos_csv_path = os.path.join(output_directory, "alunos_fim.csv")
normalize_html_to_csv(html_path, alunos_csv_path)
for idx, tarefa_file in enumerate(tarefa_files):
tarefa_path = os.path.join(input_directory, f"tarefa_{idx}.xlsx")
with open(tarefa_path, "wb") as f:
f.write(tarefa_file)
normalize_multiple_excel_to_csv(input_directory, output_directory)
contador_csv_path = os.path.join(output_directory, "contador_tarefas.csv")
relatorio_csv_path = os.path.join(output_directory, "relatorio_final.csv")
process_all_tarefas_in_directory(output_directory, alunos_csv_path, contador_csv_path, relatorio_csv_path)
df = process_relatorios(contador_csv_path, relatorio_csv_path)
html_output_path = os.path.join(output_directory, "relatorio_final.html")
df.to_html(html_output_path, index=False)
return df.to_html(index=False), html_output_path
def download_html_file(file_path):
return file_path
# --- Interface Gradio ---
with gr.Blocks() as interface:
gr.Markdown("# Processamento de Relatórios de Tarefas")
html_file = gr.File(label="Upload HTML File (alunos.htm)", type="binary")
excel_files = gr.Files(label="Upload Excel Files (Relatórios de Tarefas)", type="binary", file_count="multiple")
generate_btn = gr.Button("Generate Report")
output_html = gr.HTML()
download_btn = gr.File(label="Download Report")
def process_and_prepare_download(html_file, tarefa_files):
html_content, file_path = process_inputs(html_file, tarefa_files)
return html_content, file_path
generate_btn.click(fn=process_and_prepare_download, inputs=[html_file, excel_files], outputs=[output_html, download_btn])
interface.launch() |