Spaces:
Runtime error
Runtime error
Upload: Multiple files to assets directory
Browse files
app.py
CHANGED
@@ -8,16 +8,96 @@ matplotlib.use('Agg')
|
|
8 |
import matplotlib.pyplot as plt
|
9 |
import io
|
10 |
import base64
|
|
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
19 |
-
|
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...")
|
@@ -27,61 +107,68 @@ def download_reference():
|
|
27 |
f.write(r.content)
|
28 |
print("Descarga completa:", LOCAL_REF_PATH)
|
29 |
|
30 |
-
download_reference() # Se
|
31 |
|
|
|
|
|
|
|
32 |
def evaluate_prediction(pred_path, ref_path):
|
33 |
"""
|
34 |
-
Lee el
|
35 |
-
Calcula
|
36 |
-
|
37 |
-
|
38 |
-
-
|
39 |
-
- predictions.csv: col [wavelength, prediction]
|
40 |
"""
|
41 |
# Leer la referencia
|
42 |
df_ref = pd.read_csv(ref_path)
|
43 |
-
# Leer la predicción
|
44 |
df_pred = pd.read_csv(pred_path)
|
45 |
|
46 |
-
#
|
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
|
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
|
61 |
return {
|
62 |
-
"mre_mean": mre_mean,
|
63 |
-
"rmse": rmse,
|
64 |
-
"mre_spectrum": mre.tolist()
|
65 |
}
|
66 |
|
67 |
def evaluate_and_save(pred_file, participant_name):
|
68 |
"""
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
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 |
-
#
|
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')
|
@@ -89,7 +176,6 @@ def evaluate_and_save(pred_file, participant_name):
|
|
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()
|
@@ -97,7 +183,7 @@ def evaluate_and_save(pred_file, participant_name):
|
|
97 |
img_str = base64.b64encode(buf.read()).decode('utf-8')
|
98 |
img_str = f"data:image/png;base64,{img_str}"
|
99 |
|
100 |
-
#
|
101 |
message = (
|
102 |
f"Participant: {participant_name}\n"
|
103 |
f"MRE mean: {results['mre_mean']:.4f}\n"
|
@@ -106,11 +192,14 @@ def evaluate_and_save(pred_file, participant_name):
|
|
106 |
|
107 |
return message, img_str
|
108 |
|
109 |
-
#
|
|
|
|
|
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 (
|
114 |
|
115 |
output_message = gr.Textbox(label="Resultados")
|
116 |
output_image = gr.HTML(label="Gráfica")
|
|
|
8 |
import matplotlib.pyplot as plt
|
9 |
import io
|
10 |
import base64
|
11 |
+
import json
|
12 |
+
import time
|
13 |
|
14 |
+
from huggingface_hub import Repository
|
15 |
+
|
16 |
+
# -----------------------------------------------------------------------------
|
17 |
+
# CONFIGURACIÓN DEL REPO DEL SPACE Y DE LA REFERENCIA
|
18 |
+
# -----------------------------------------------------------------------------
|
19 |
+
SPACE_REPO_URL = "https://huggingface.co/spaces/juliocontrerash/my-challenge"
|
20 |
+
SPACE_LOCAL_DIR = "." # Usa la carpeta actual (el mismo repo del Space)
|
21 |
+
|
22 |
+
# URL de tu archivo de referencia CSV en un dataset (por ejemplo, "reference.csv")
|
23 |
REFERENCE_FILE_URL = "https://huggingface.co/datasets/juliocontrerash/my-challenge-submissions/resolve/main/reference.csv"
|
24 |
+
LOCAL_REF_PATH = "reference.csv" # Lo guardaremos con este nombre local
|
25 |
+
|
26 |
+
def setup_local_repo_for_push():
|
27 |
+
"""
|
28 |
+
Inicializa un objeto 'Repository' apuntando al mismo repo del Space.
|
29 |
+
Requiere un token con permisos de escritura, guardado en HF_SPACE_TOKEN
|
30 |
+
como secret en la configuración del Space.
|
31 |
+
"""
|
32 |
+
token = os.environ.get("HF_SPACE_TOKEN", None) # <--- ASEGÚRATE DE QUE SE LLAME ASÍ
|
33 |
+
if not token:
|
34 |
+
print("WARNING: HF_SPACE_TOKEN no está configurado. No se podrá hacer push.")
|
35 |
+
return None
|
36 |
+
|
37 |
+
repo = Repository(
|
38 |
+
local_dir=SPACE_LOCAL_DIR,
|
39 |
+
clone_from=SPACE_REPO_URL,
|
40 |
+
use_auth_token=token
|
41 |
+
)
|
42 |
+
# Por si se actualizó el Space en remoto
|
43 |
+
try:
|
44 |
+
repo.git_pull()
|
45 |
+
except:
|
46 |
+
pass
|
47 |
+
|
48 |
+
return repo
|
49 |
+
|
50 |
+
# Inicializamos la posibilidad de hacer push a nuestro Space
|
51 |
+
space_repo = setup_local_repo_for_push()
|
52 |
+
|
53 |
+
def add_submission_entry(entry):
|
54 |
+
"""
|
55 |
+
Abre/crea submissions.jsonl (en la raíz del Space),
|
56 |
+
agrega la nueva 'entry', y hace commit+push al repo.
|
57 |
+
"""
|
58 |
+
global space_repo
|
59 |
+
if space_repo is None:
|
60 |
+
print("No repo handle (space_repo is None). Skipping save.")
|
61 |
+
return
|
62 |
+
|
63 |
+
submissions_file = "submissions.jsonl"
|
64 |
+
|
65 |
+
# 1) Traer la última versión de remoto (por si hubo otros commits)
|
66 |
+
space_repo.git_pull()
|
67 |
+
|
68 |
+
# 2) Leer el archivo actual (si existe)
|
69 |
+
submissions = []
|
70 |
+
if os.path.exists(submissions_file):
|
71 |
+
with open(submissions_file, "r") as f:
|
72 |
+
for line in f:
|
73 |
+
line = line.strip()
|
74 |
+
if line:
|
75 |
+
submissions.append(json.loads(line))
|
76 |
+
|
77 |
+
# 3) Añadir la nueva entrada
|
78 |
+
submissions.append(entry)
|
79 |
+
|
80 |
+
# 4) Guardar sobrescribiendo
|
81 |
+
with open(submissions_file, "w") as f:
|
82 |
+
for s in submissions:
|
83 |
+
f.write(json.dumps(s) + "\n")
|
84 |
+
|
85 |
+
# 5) Hacer commit y push
|
86 |
+
space_repo.git_add(submissions_file)
|
87 |
+
space_repo.git_commit("Add new submission entry")
|
88 |
+
try:
|
89 |
+
space_repo.git_push()
|
90 |
+
print("Submission pushed successfully to the Space repo.")
|
91 |
+
except Exception as e:
|
92 |
+
print("Error pushing submission:", e)
|
93 |
|
94 |
+
# -----------------------------------------------------------------------------
|
95 |
+
# DESCARGA DEL ARCHIVO DE REFERENCIA
|
96 |
+
# -----------------------------------------------------------------------------
|
97 |
def download_reference():
|
98 |
"""
|
99 |
+
Descarga el CSV de referencia desde el dataset en Hugging Face,
|
100 |
+
guardándolo como 'reference.csv' si no existe aún.
|
|
|
101 |
"""
|
102 |
if not os.path.exists(LOCAL_REF_PATH):
|
103 |
print("Descargando archivo de referencia...")
|
|
|
107 |
f.write(r.content)
|
108 |
print("Descarga completa:", LOCAL_REF_PATH)
|
109 |
|
110 |
+
download_reference() # Se ejecuta al iniciar el Space
|
111 |
|
112 |
+
# -----------------------------------------------------------------------------
|
113 |
+
# LÓGICA DE EVALUACIÓN
|
114 |
+
# -----------------------------------------------------------------------------
|
115 |
def evaluate_prediction(pred_path, ref_path):
|
116 |
"""
|
117 |
+
Lee el CSV subido (pred_path) y el CSV de referencia (ref_path),
|
118 |
+
Calcula el MRE y RMSE, y retorna un dict con resultados.
|
119 |
+
Formato esperado:
|
120 |
+
- reference.csv: [wavelength, power]
|
121 |
+
- predictions.csv: [wavelength, prediction]
|
|
|
122 |
"""
|
123 |
# Leer la referencia
|
124 |
df_ref = pd.read_csv(ref_path)
|
125 |
+
# Leer la predicción
|
126 |
df_pred = pd.read_csv(pred_path)
|
127 |
|
128 |
+
# Merge en base a 'wavelength'
|
129 |
df_merged = pd.merge(df_ref, df_pred, on='wavelength', how='inner')
|
130 |
|
|
|
131 |
real = df_merged['power'].values
|
132 |
pred = df_merged['prediction'].values
|
133 |
|
134 |
+
# Calcular MRE
|
135 |
mre = np.abs((pred - real) / real)
|
136 |
mre_mean = mre.mean()
|
137 |
|
138 |
# Calcular RMSE
|
139 |
rmse = np.sqrt(np.mean((pred - real)**2))
|
140 |
|
141 |
+
# Retornar
|
142 |
return {
|
143 |
+
"mre_mean": float(mre_mean),
|
144 |
+
"rmse": float(rmse),
|
145 |
+
"mre_spectrum": mre.tolist()
|
146 |
}
|
147 |
|
148 |
def evaluate_and_save(pred_file, participant_name):
|
149 |
"""
|
150 |
+
1. Toma el archivo subido (pred_file).
|
151 |
+
2. Evalúa comparándolo con la referencia (LOCAL_REF_PATH).
|
152 |
+
3. Agrega la entrada a submissions.jsonl.
|
153 |
+
4. Genera una gráfica y mensaje de resultados.
|
|
|
154 |
"""
|
155 |
if not pred_file:
|
156 |
return "No file uploaded", None
|
157 |
|
|
|
158 |
pred_path = pred_file.name
|
|
|
|
|
159 |
results = evaluate_prediction(pred_path, LOCAL_REF_PATH)
|
160 |
+
|
161 |
+
# Guardar submission en submissions.jsonl
|
162 |
+
submission_entry = {
|
163 |
+
"submission_id": int(time.time()),
|
164 |
+
"participant": participant_name,
|
165 |
+
"mre_mean": results["mre_mean"],
|
166 |
+
"rmse": results["rmse"],
|
167 |
+
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
|
168 |
+
}
|
169 |
+
add_submission_entry(submission_entry)
|
170 |
|
171 |
+
# Graficar
|
172 |
mre_spectrum = results["mre_spectrum"]
|
173 |
plt.figure(figsize=(6,4))
|
174 |
plt.plot(np.arange(len(mre_spectrum)), mre_spectrum, marker='o', label='MRE Spectrum')
|
|
|
176 |
plt.ylabel('MRE')
|
177 |
plt.title('Spectral Error')
|
178 |
plt.legend()
|
|
|
179 |
buf = io.BytesIO()
|
180 |
plt.savefig(buf, format='png')
|
181 |
plt.close()
|
|
|
183 |
img_str = base64.b64encode(buf.read()).decode('utf-8')
|
184 |
img_str = f"data:image/png;base64,{img_str}"
|
185 |
|
186 |
+
# Mensaje final
|
187 |
message = (
|
188 |
f"Participant: {participant_name}\n"
|
189 |
f"MRE mean: {results['mre_mean']:.4f}\n"
|
|
|
192 |
|
193 |
return message, img_str
|
194 |
|
195 |
+
# -----------------------------------------------------------------------------
|
196 |
+
# INTERFAZ GRADIO
|
197 |
+
# -----------------------------------------------------------------------------
|
198 |
with gr.Blocks() as demo:
|
199 |
gr.Markdown("# My Challenge\nSube tu archivo de predicciones en CSV para evaluar tu modelo.")
|
200 |
+
|
201 |
participant_name = gr.Textbox(label="Nombre del participante")
|
202 |
+
pred_file = gr.File(label="Subir archivo CSV (predictions.csv)")
|
203 |
|
204 |
output_message = gr.Textbox(label="Resultados")
|
205 |
output_image = gr.HTML(label="Gráfica")
|