Spaces:
Runtime error
Runtime error
Upload: Multiple files to assets directory
Browse files
app.py
CHANGED
@@ -1,81 +1,126 @@
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
import os
|
4 |
-
import
|
5 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
-
|
|
|
10 |
|
11 |
def download_reference():
|
|
|
|
|
|
|
|
|
|
|
12 |
if not os.path.exists(LOCAL_REF_PATH):
|
|
|
13 |
r = requests.get(REFERENCE_FILE_URL)
|
|
|
14 |
with open(LOCAL_REF_PATH, 'wb') as f:
|
15 |
f.write(r.content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
def evaluate_and_save(pred_file, participant_name):
|
20 |
"""
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
25 |
"""
|
26 |
if not pred_file:
|
27 |
return "No file uploaded", None
|
28 |
|
29 |
-
#
|
30 |
pred_path = pred_file.name
|
31 |
|
32 |
-
# Evaluar
|
33 |
results = evaluate_prediction(pred_path, LOCAL_REF_PATH)
|
34 |
|
35 |
-
#
|
36 |
-
# 1. Descarga submissions.jsonl
|
37 |
-
# 2. A帽ade una nueva l铆nea con participant_name, results, time, etc.
|
38 |
-
# 3. `git push` o usar huggingface_hub para subir la versi贸n actualizada
|
39 |
-
|
40 |
-
# Aqui creamos una grafica (opcional)
|
41 |
-
# Por ejemplo un plot con MRE_spectrum:
|
42 |
-
import matplotlib
|
43 |
-
matplotlib.use('Agg')
|
44 |
-
import matplotlib.pyplot as plt
|
45 |
-
import io
|
46 |
-
import base64
|
47 |
-
import numpy as np
|
48 |
-
|
49 |
mre_spectrum = results["mre_spectrum"]
|
50 |
plt.figure(figsize=(6,4))
|
51 |
-
plt.plot(np.arange(len(mre_spectrum)), mre_spectrum, label='MRE Spectrum')
|
52 |
-
plt.xlabel('
|
53 |
-
plt.ylabel('
|
54 |
plt.title('Spectral Error')
|
55 |
plt.legend()
|
56 |
-
|
57 |
buf = io.BytesIO()
|
58 |
plt.savefig(buf, format='png')
|
59 |
plt.close()
|
60 |
buf.seek(0)
|
61 |
-
img_str = base64.b64encode(buf.read())
|
62 |
-
img_str = "data:image/png;base64,"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
message = f"Participant: {participant_name}\nMRE mean: {results['mre_mean']:.4f}\nRMSE: {results['rmse']:.4f}"
|
65 |
return message, img_str
|
66 |
|
|
|
67 |
with gr.Blocks() as demo:
|
68 |
-
gr.Markdown("# My Challenge\nSube tu archivo de predicciones para evaluar tu modelo.")
|
69 |
participant_name = gr.Textbox(label="Nombre del participante")
|
70 |
-
pred_file = gr.File(label="Subir archivo (
|
71 |
|
72 |
output_message = gr.Textbox(label="Resultados")
|
73 |
output_image = gr.HTML(label="Gr谩fica")
|
74 |
|
75 |
submit_btn = gr.Button("Evaluar")
|
76 |
|
77 |
-
submit_btn.click(
|
78 |
-
|
79 |
-
|
|
|
|
|
80 |
|
81 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
import os
|
4 |
+
import pandas as pd
|
5 |
+
import numpy as np
|
6 |
+
import matplotlib
|
7 |
+
matplotlib.use('Agg')
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import io
|
10 |
+
import base64
|
11 |
|
12 |
+
# 1) URL del archivo de referencia
|
13 |
+
REFERENCE_FILE_URL = "https://huggingface.co/datasets/juliocontrerash/my-challenge-submissions/resolve/main/reference.csv"
|
14 |
+
LOCAL_REF_PATH = "reference.csv"
|
15 |
|
16 |
def download_reference():
|
17 |
+
"""
|
18 |
+
Descarga el CSV de referencia desde Hugging Face Datasets
|
19 |
+
y lo guarda como un archivo local 'reference.csv'.
|
20 |
+
Se ejecuta solo si el archivo no existe todav铆a.
|
21 |
+
"""
|
22 |
if not os.path.exists(LOCAL_REF_PATH):
|
23 |
+
print("Descargando archivo de referencia...")
|
24 |
r = requests.get(REFERENCE_FILE_URL)
|
25 |
+
r.raise_for_status()
|
26 |
with open(LOCAL_REF_PATH, 'wb') as f:
|
27 |
f.write(r.content)
|
28 |
+
print("Descarga completa:", LOCAL_REF_PATH)
|
29 |
+
|
30 |
+
download_reference() # Se ejecutar谩 una sola vez al iniciar el Space
|
31 |
+
|
32 |
+
def evaluate_prediction(pred_path, ref_path):
|
33 |
+
"""
|
34 |
+
Lee el archivo CSV subido (pred_path) y el archivo CSV de referencia (ref_path).
|
35 |
+
Calcula alguna m茅trica, por ejemplo MRE y RMSE.
|
36 |
+
|
37 |
+
Formato de CSV esperado:
|
38 |
+
- reference.csv: col [wavelength, power]
|
39 |
+
- predictions.csv: col [wavelength, prediction]
|
40 |
+
"""
|
41 |
+
# Leer la referencia
|
42 |
+
df_ref = pd.read_csv(ref_path)
|
43 |
+
# Leer la predicci贸n del participante
|
44 |
+
df_pred = pd.read_csv(pred_path)
|
45 |
+
|
46 |
+
# Hacer merge en base a la columna 'wavelength'
|
47 |
+
df_merged = pd.merge(df_ref, df_pred, on='wavelength', how='inner')
|
48 |
+
|
49 |
+
# Extraer valores
|
50 |
+
real = df_merged['power'].values
|
51 |
+
pred = df_merged['prediction'].values
|
52 |
+
|
53 |
+
# Calcular Mean Relative Error (MRE) por cada fila
|
54 |
+
mre = np.abs((pred - real) / real)
|
55 |
+
mre_mean = mre.mean()
|
56 |
|
57 |
+
# Calcular RMSE
|
58 |
+
rmse = np.sqrt(np.mean((pred - real)**2))
|
59 |
+
|
60 |
+
# Retornar resultados
|
61 |
+
return {
|
62 |
+
"mre_mean": mre_mean,
|
63 |
+
"rmse": rmse,
|
64 |
+
"mre_spectrum": mre.tolist() # vector
|
65 |
+
}
|
66 |
|
67 |
def evaluate_and_save(pred_file, participant_name):
|
68 |
"""
|
69 |
+
Funci贸n que se llama al presionar el bot贸n "Evaluar" en la interfaz.
|
70 |
+
1. Lee el CSV de predicciones (subido por usuario).
|
71 |
+
2. Llama a evaluate_prediction().
|
72 |
+
3. Genera una gr谩fica y arma un mensaje final.
|
73 |
+
4. Retorna el mensaje y la gr谩fica embebida (base64).
|
74 |
"""
|
75 |
if not pred_file:
|
76 |
return "No file uploaded", None
|
77 |
|
78 |
+
# 1. El archivo subido es un objeto tipo gradio.tempfile. Obtenemos la ruta
|
79 |
pred_path = pred_file.name
|
80 |
|
81 |
+
# 2. Evaluar la predicci贸n
|
82 |
results = evaluate_prediction(pred_path, LOCAL_REF_PATH)
|
83 |
|
84 |
+
# 3. Generar la gr谩fica
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
mre_spectrum = results["mre_spectrum"]
|
86 |
plt.figure(figsize=(6,4))
|
87 |
+
plt.plot(np.arange(len(mre_spectrum)), mre_spectrum, marker='o', label='MRE Spectrum')
|
88 |
+
plt.xlabel('Index')
|
89 |
+
plt.ylabel('MRE')
|
90 |
plt.title('Spectral Error')
|
91 |
plt.legend()
|
92 |
+
|
93 |
buf = io.BytesIO()
|
94 |
plt.savefig(buf, format='png')
|
95 |
plt.close()
|
96 |
buf.seek(0)
|
97 |
+
img_str = base64.b64encode(buf.read()).decode('utf-8')
|
98 |
+
img_str = f"data:image/png;base64,{img_str}"
|
99 |
+
|
100 |
+
# 4. Construir mensaje final
|
101 |
+
message = (
|
102 |
+
f"Participant: {participant_name}\n"
|
103 |
+
f"MRE mean: {results['mre_mean']:.4f}\n"
|
104 |
+
f"RMSE: {results['rmse']:.4f}"
|
105 |
+
)
|
106 |
|
|
|
107 |
return message, img_str
|
108 |
|
109 |
+
# === Construcci贸n de la interfaz con Gradio ===
|
110 |
with gr.Blocks() as demo:
|
111 |
+
gr.Markdown("# My Challenge\nSube tu archivo de predicciones en CSV para evaluar tu modelo.")
|
112 |
participant_name = gr.Textbox(label="Nombre del participante")
|
113 |
+
pred_file = gr.File(label="Subir archivo CSV (ej. predictions.csv)")
|
114 |
|
115 |
output_message = gr.Textbox(label="Resultados")
|
116 |
output_image = gr.HTML(label="Gr谩fica")
|
117 |
|
118 |
submit_btn = gr.Button("Evaluar")
|
119 |
|
120 |
+
submit_btn.click(
|
121 |
+
fn=evaluate_and_save,
|
122 |
+
inputs=[pred_file, participant_name],
|
123 |
+
outputs=[output_message, output_image]
|
124 |
+
)
|
125 |
|
126 |
demo.launch()
|