Spaces:
Running
Running
JACINTO VELASCO commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,103 +6,98 @@ import tempfile
|
|
| 6 |
import random
|
| 7 |
import os
|
| 8 |
import time
|
| 9 |
-
import requests
|
| 10 |
import streamlit.components.v1 as components
|
| 11 |
import html
|
| 12 |
|
| 13 |
# --- CONFIGURACIÓN DE PÁGINA ---
|
| 14 |
st.set_page_config(
|
| 15 |
-
page_title="
|
| 16 |
layout="wide",
|
| 17 |
page_icon="🎓",
|
| 18 |
initial_sidebar_state="expanded"
|
| 19 |
)
|
| 20 |
|
| 21 |
-
# --- CSS:
|
| 22 |
st.markdown("""
|
| 23 |
<style>
|
| 24 |
-
/*
|
| 25 |
-
.stApp { background:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
padding-top: 1.2rem;
|
| 29 |
-
padding-bottom: 2.0rem;
|
| 30 |
-
max-width: 1200px;
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
html, body, [class*="css"] {
|
| 34 |
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial, "Helvetica Neue", "Noto Sans", "Liberation Sans", sans-serif;
|
| 35 |
}
|
| 36 |
|
| 37 |
-
/*
|
| 38 |
[data-testid="stHeader"]{
|
| 39 |
-
background: rgba(255,255,255,0.
|
| 40 |
border-bottom: 1px solid #e5e7eb;
|
| 41 |
}
|
| 42 |
|
| 43 |
-
/*
|
| 44 |
[data-testid="stSidebar"]{
|
| 45 |
-
background:
|
| 46 |
-
border-right:
|
| 47 |
}
|
| 48 |
[data-testid="stSidebar"] > div { padding-top: 1rem; }
|
| 49 |
|
| 50 |
-
/*
|
| 51 |
div.stButton > button,
|
| 52 |
div.stDownloadButton > button,
|
| 53 |
div.stFormSubmitButton > button {
|
| 54 |
-
background:
|
| 55 |
-
color:
|
| 56 |
-
border:
|
| 57 |
-
border-radius:
|
| 58 |
-
font-weight:
|
| 59 |
-
padding:
|
| 60 |
transition: transform .06s ease, filter .15s ease;
|
| 61 |
}
|
| 62 |
-
|
| 63 |
div.stButton > button:hover,
|
| 64 |
div.stDownloadButton > button:hover,
|
| 65 |
div.stFormSubmitButton > button:hover {
|
| 66 |
-
filter: brightness(0.
|
| 67 |
transform: translateY(-1px);
|
| 68 |
}
|
| 69 |
|
| 70 |
-
/* Botón
|
| 71 |
button[kind="primary"]{
|
| 72 |
-
background:
|
| 73 |
-
border:
|
| 74 |
-
color:
|
| 75 |
}
|
| 76 |
|
| 77 |
-
/*
|
| 78 |
[data-testid="stMetric"]{
|
| 79 |
-
background:
|
| 80 |
-
border:
|
| 81 |
-
border-radius:
|
| 82 |
-
padding:
|
| 83 |
}
|
| 84 |
|
| 85 |
-
/*
|
| 86 |
.stCodeBlock pre {
|
| 87 |
-
background:
|
| 88 |
-
border:
|
| 89 |
-
border-radius:
|
| 90 |
-
padding:
|
| 91 |
}
|
| 92 |
-
|
| 93 |
code {
|
| 94 |
-
background:
|
| 95 |
-
border:
|
| 96 |
-
border-radius:
|
| 97 |
-
padding:
|
| 98 |
-
color:
|
| 99 |
}
|
| 100 |
|
| 101 |
-
/* Texto
|
| 102 |
-
.stMarkdown, .stText, p, span, label { color:
|
|
|
|
| 103 |
|
| 104 |
-
/*
|
| 105 |
-
[data-testid="
|
|
|
|
|
|
|
|
|
|
| 106 |
</style>
|
| 107 |
""", unsafe_allow_html=True)
|
| 108 |
|
|
@@ -119,7 +114,7 @@ def load_questions():
|
|
| 119 |
st.error(f"Error al cargar JSON: {e}")
|
| 120 |
return []
|
| 121 |
|
| 122 |
-
# --- MERMAID (diagramas
|
| 123 |
def render_mermaid(mermaid_code: str):
|
| 124 |
mermaid_code = mermaid_code.strip()
|
| 125 |
mermaid_code_escaped = html.escape(mermaid_code)
|
|
@@ -159,70 +154,23 @@ def format_time(seconds):
|
|
| 159 |
m, s = divmod(seconds, 60)
|
| 160 |
return f"{int(m):02d}:{int(s):02d}"
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
txt = (r.text or "").strip()
|
| 180 |
-
return {"error": f"Servidor HF con problemas (HTTP {r.status_code}). Respuesta: {txt[:200] or '[vacía]'}"}
|
| 181 |
-
|
| 182 |
-
raw = (r.text or "").strip()
|
| 183 |
-
if not raw:
|
| 184 |
-
return {"error": "Respuesta vacía del servidor (posible modelo cargando). Reintenta."}
|
| 185 |
-
|
| 186 |
-
ctype = (r.headers.get("content-type") or "").lower()
|
| 187 |
-
if "application/json" in ctype or raw.startswith("{") or raw.startswith("["):
|
| 188 |
-
try:
|
| 189 |
-
return r.json()
|
| 190 |
-
except Exception:
|
| 191 |
-
return {"error": f"Respuesta no JSON válida. Primeros 200 chars: {raw[:200]}"}
|
| 192 |
-
|
| 193 |
-
return {"error": f"HF devolvió contenido no JSON ({ctype}). Primeros 200 chars: {raw[:200]}"}
|
| 194 |
-
|
| 195 |
-
except requests.exceptions.Timeout:
|
| 196 |
-
return {"error": "Timeout consultando a HF (45s). Reintenta o usa un modelo más ligero."}
|
| 197 |
-
except Exception as e:
|
| 198 |
-
return {"error": f"Error de red: {e}"}
|
| 199 |
-
|
| 200 |
-
def get_ai_explanation(question_text, correct_answer, topic, token):
|
| 201 |
-
if not token:
|
| 202 |
-
return "⚠️ La IA no está configurada. Contacta con el profesor."
|
| 203 |
-
|
| 204 |
-
prompt = f"""[INST] Actúa como un profesor experto en Ingeniería Matemática y Python.
|
| 205 |
-
Explica brevemente por qué esta es la respuesta correcta.
|
| 206 |
-
|
| 207 |
-
Tema: {topic}
|
| 208 |
-
Pregunta: {question_text}
|
| 209 |
-
Respuesta Correcta: {correct_answer}
|
| 210 |
-
|
| 211 |
-
Explicación concisa: [/INST]"""
|
| 212 |
-
|
| 213 |
-
with st.spinner("🤖 Consultando a la IA..."):
|
| 214 |
-
output = query_huggingface({"inputs": prompt, "parameters": {"max_new_tokens": 220}}, token)
|
| 215 |
-
|
| 216 |
-
if isinstance(output, list) and output and isinstance(output[0], dict) and "generated_text" in output[0]:
|
| 217 |
-
return output[0]["generated_text"].replace(prompt, "").strip()
|
| 218 |
-
|
| 219 |
-
if isinstance(output, dict):
|
| 220 |
-
if "estimated_time" in output:
|
| 221 |
-
return f"⏳ El modelo se está cargando. Reintenta en ~{output['estimated_time']}s."
|
| 222 |
-
if "error" in output:
|
| 223 |
-
return f"Error técnico con la IA: {output['error']}"
|
| 224 |
-
|
| 225 |
-
return f"No se pudo generar la explicación. Respuesta: {str(output)[:200]}"
|
| 226 |
|
| 227 |
# --- PDF ---
|
| 228 |
def generate_pdf(history_data, final_score, total_questions):
|
|
@@ -239,7 +187,7 @@ def generate_pdf(history_data, final_score, total_questions):
|
|
| 239 |
q_clean = q_clean.encode('latin-1', 'replace').decode('latin-1')
|
| 240 |
status = "BIEN" if item['correct'] else "MAL"
|
| 241 |
|
| 242 |
-
pdf.set_text_color(0,
|
| 243 |
pdf.cell(0, 8, txt=f"{i+1}. [{status}]", ln=1)
|
| 244 |
pdf.set_text_color(0, 0, 0)
|
| 245 |
pdf.multi_cell(0, 5, txt=f"P: {q_clean}...")
|
|
@@ -249,8 +197,6 @@ def generate_pdf(history_data, final_score, total_questions):
|
|
| 249 |
|
| 250 |
# --- MAIN ---
|
| 251 |
def main():
|
| 252 |
-
hf_token = st.secrets.get("HF_TOKEN", None)
|
| 253 |
-
|
| 254 |
all_questions = load_questions()
|
| 255 |
if not all_questions:
|
| 256 |
st.warning("⚠️ No se han cargado las preguntas.")
|
|
@@ -270,22 +216,22 @@ def main():
|
|
| 270 |
st.title("🧭 Panel de Control")
|
| 271 |
|
| 272 |
if not st.session_state.exam_active:
|
| 273 |
-
st.markdown("### ⚙️ Configuración
|
| 274 |
|
| 275 |
niveles = sorted(list(set([q.get('nivel', 'básico').lower() for q in all_questions])))
|
| 276 |
if not niveles:
|
| 277 |
niveles = ["básico", "medio", "alto"]
|
| 278 |
|
| 279 |
-
sel_levels = st.multiselect("📌
|
| 280 |
-
mode = st.radio("⏳ Longitud:", ["Rápido (10
|
| 281 |
|
| 282 |
-
if st.button("▶️
|
| 283 |
if not sel_levels:
|
| 284 |
st.error("Selecciona al menos un nivel.")
|
| 285 |
else:
|
| 286 |
filtered = [q for q in all_questions if q.get('nivel', 'básico').lower() in sel_levels]
|
| 287 |
if not filtered:
|
| 288 |
-
st.error("No hay preguntas
|
| 289 |
else:
|
| 290 |
random.shuffle(filtered)
|
| 291 |
limit = 10 if "10" in mode else 25 if "25" in mode else len(filtered)
|
|
@@ -309,20 +255,21 @@ def main():
|
|
| 309 |
st.progress(min(current / total, 1.0))
|
| 310 |
st.metric("📍 Pregunta", f"{current + 1} / {total}")
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
|
|
|
| 315 |
|
|
|
|
| 316 |
if st.session_state.history:
|
| 317 |
st.markdown("---")
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
st.
|
| 322 |
-
st.bar_chart(stats, height=150)
|
| 323 |
|
| 324 |
st.markdown("---")
|
| 325 |
-
if st.button("❌ Terminar
|
| 326 |
st.session_state.current_idx = len(st.session_state.exam_pool)
|
| 327 |
st.rerun()
|
| 328 |
|
|
@@ -355,8 +302,6 @@ def main():
|
|
| 355 |
"ok": is_correct,
|
| 356 |
"expl": q["explanation"],
|
| 357 |
"corr": correct_txt,
|
| 358 |
-
"q_text": q["question"],
|
| 359 |
-
"topic": q["topic"]
|
| 360 |
}
|
| 361 |
|
| 362 |
if not st.session_state.answered_current:
|
|
@@ -365,11 +310,12 @@ def main():
|
|
| 365 |
st.session_state.history.append({
|
| 366 |
"question": q["question"],
|
| 367 |
"correct": is_correct,
|
| 368 |
-
"tipo": q
|
| 369 |
"user_answer": user_ans,
|
| 370 |
"correct_answer": correct_txt
|
| 371 |
})
|
| 372 |
st.session_state.answered_current = True
|
|
|
|
| 373 |
st.rerun()
|
| 374 |
else:
|
| 375 |
st.warning("Por favor, selecciona una opción.")
|
|
@@ -383,24 +329,14 @@ def main():
|
|
| 383 |
else:
|
| 384 |
st.error(f"❌ Incorrecto. La respuesta correcta era: **{res['corr']}**")
|
| 385 |
|
| 386 |
-
with st.expander("📖 Ver explicación
|
| 387 |
st.markdown(res["expl"])
|
| 388 |
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
expl = get_ai_explanation(res["q_text"], res["corr"], res["topic"], hf_token)
|
| 395 |
-
st.info(expl)
|
| 396 |
-
else:
|
| 397 |
-
st.caption("ℹ️ IA no disponible (HF_TOKEN no configurado).")
|
| 398 |
-
|
| 399 |
-
with col2:
|
| 400 |
-
if st.button("➡️ Siguiente Pregunta", type="primary", use_container_width=True):
|
| 401 |
-
st.session_state.current_idx += 1
|
| 402 |
-
st.session_state.answered_current = False
|
| 403 |
-
st.rerun()
|
| 404 |
|
| 405 |
# FINAL
|
| 406 |
elif st.session_state.exam_active:
|
|
@@ -415,26 +351,33 @@ def main():
|
|
| 415 |
c1.metric("✅ Nota", f"{final} / {total}")
|
| 416 |
c2.metric("📈 Porcentaje", f"{perc:.1f}%")
|
| 417 |
elapsed_time = format_time(time.time() - st.session_state.start_time)
|
| 418 |
-
c3.metric("⏱️ Tiempo
|
| 419 |
|
|
|
|
| 420 |
if st.session_state.history:
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
if
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
|
|
|
| 428 |
try:
|
| 429 |
pdf = generate_pdf(st.session_state.history, final, total)
|
| 430 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 431 |
pdf.output(tmp.name)
|
| 432 |
with open(tmp.name, "rb") as f:
|
| 433 |
-
st.download_button(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
except Exception:
|
| 435 |
st.error("Error generando PDF. Asegúrate de tener 'fpdf' instalado.")
|
| 436 |
|
| 437 |
-
if st.button("🏠 Volver al
|
| 438 |
st.session_state.exam_active = False
|
| 439 |
st.rerun()
|
| 440 |
|
|
|
|
| 6 |
import random
|
| 7 |
import os
|
| 8 |
import time
|
|
|
|
| 9 |
import streamlit.components.v1 as components
|
| 10 |
import html
|
| 11 |
|
| 12 |
# --- CONFIGURACIÓN DE PÁGINA ---
|
| 13 |
st.set_page_config(
|
| 14 |
+
page_title="Examen Python & Matemáticas",
|
| 15 |
layout="wide",
|
| 16 |
page_icon="🎓",
|
| 17 |
initial_sidebar_state="expanded"
|
| 18 |
)
|
| 19 |
|
| 20 |
+
# --- CSS: BLANCO LIMPIO + BOTONES CLAROS + CÓDIGO VS CODE + NOTIFICACIONES CLARAS ---
|
| 21 |
st.markdown("""
|
| 22 |
<style>
|
| 23 |
+
/* Base */
|
| 24 |
+
.stApp { background:#ffffff; color:#0f172a; }
|
| 25 |
+
.block-container { padding-top:1.1rem; padding-bottom:2rem; max-width:1200px; }
|
| 26 |
+
html, body, [class*="css"] {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial, "Helvetica Neue", "Noto Sans", "Liberation Sans", sans-serif;
|
| 28 |
}
|
| 29 |
|
| 30 |
+
/* Header */
|
| 31 |
[data-testid="stHeader"]{
|
| 32 |
+
background: rgba(255,255,255,0.96);
|
| 33 |
border-bottom: 1px solid #e5e7eb;
|
| 34 |
}
|
| 35 |
|
| 36 |
+
/* Sidebar fijo y limpio */
|
| 37 |
[data-testid="stSidebar"]{
|
| 38 |
+
background:#f8fafc;
|
| 39 |
+
border-right:1px solid #e5e7eb;
|
| 40 |
}
|
| 41 |
[data-testid="stSidebar"] > div { padding-top: 1rem; }
|
| 42 |
|
| 43 |
+
/* Botones claros (NO azul oscuro) */
|
| 44 |
div.stButton > button,
|
| 45 |
div.stDownloadButton > button,
|
| 46 |
div.stFormSubmitButton > button {
|
| 47 |
+
background:#e0f2fe !important; /* celeste muy claro */
|
| 48 |
+
color:#075985 !important; /* texto azul oscuro */
|
| 49 |
+
border:1px solid #7dd3fc !important;
|
| 50 |
+
border-radius:12px !important;
|
| 51 |
+
font-weight:800 !important;
|
| 52 |
+
padding:0.58rem 0.95rem !important;
|
| 53 |
transition: transform .06s ease, filter .15s ease;
|
| 54 |
}
|
|
|
|
| 55 |
div.stButton > button:hover,
|
| 56 |
div.stDownloadButton > button:hover,
|
| 57 |
div.stFormSubmitButton > button:hover {
|
| 58 |
+
filter: brightness(0.98);
|
| 59 |
transform: translateY(-1px);
|
| 60 |
}
|
| 61 |
|
| 62 |
+
/* Botón primary (lo usamos para "Siguiente") */
|
| 63 |
button[kind="primary"]{
|
| 64 |
+
background:#dcfce7 !important; /* verde muy claro */
|
| 65 |
+
border:1px solid #86efac !important;
|
| 66 |
+
color:#166534 !important;
|
| 67 |
}
|
| 68 |
|
| 69 |
+
/* Métricas en tarjeta */
|
| 70 |
[data-testid="stMetric"]{
|
| 71 |
+
background:#ffffff;
|
| 72 |
+
border:1px solid #e5e7eb;
|
| 73 |
+
border-radius:14px;
|
| 74 |
+
padding:10px 12px;
|
| 75 |
}
|
| 76 |
|
| 77 |
+
/* CÓDIGO estilo VS Code (gris) */
|
| 78 |
.stCodeBlock pre {
|
| 79 |
+
background:#f3f4f6 !important;
|
| 80 |
+
border:1px solid #e5e7eb !important;
|
| 81 |
+
border-radius:12px !important;
|
| 82 |
+
padding:14px !important;
|
| 83 |
}
|
|
|
|
| 84 |
code {
|
| 85 |
+
background:#f3f4f6 !important;
|
| 86 |
+
border:1px solid #e5e7eb !important;
|
| 87 |
+
border-radius:8px !important;
|
| 88 |
+
padding:1px 6px !important;
|
| 89 |
+
color:#0f172a !important;
|
| 90 |
}
|
| 91 |
|
| 92 |
+
/* Texto */
|
| 93 |
+
.stMarkdown, .stText, p, span, label { color:#0f172a !important; }
|
| 94 |
+
[data-testid="stRadio"] label, [data-testid="stSelectbox"] label { font-weight:800; }
|
| 95 |
|
| 96 |
+
/* Alertas claras (success/error/warning/info) */
|
| 97 |
+
[data-testid="stAlert"]{
|
| 98 |
+
border-radius: 14px !important;
|
| 99 |
+
border: 1px solid #e5e7eb !important;
|
| 100 |
+
}
|
| 101 |
</style>
|
| 102 |
""", unsafe_allow_html=True)
|
| 103 |
|
|
|
|
| 114 |
st.error(f"Error al cargar JSON: {e}")
|
| 115 |
return []
|
| 116 |
|
| 117 |
+
# --- MERMAID (diagramas) ---
|
| 118 |
def render_mermaid(mermaid_code: str):
|
| 119 |
mermaid_code = mermaid_code.strip()
|
| 120 |
mermaid_code_escaped = html.escape(mermaid_code)
|
|
|
|
| 154 |
m, s = divmod(seconds, 60)
|
| 155 |
return f"{int(m):02d}:{int(s):02d}"
|
| 156 |
|
| 157 |
+
def topic_table(history):
|
| 158 |
+
"""Devuelve un DataFrame resumen por tema con intentos/aciertos/tasa."""
|
| 159 |
+
if not history:
|
| 160 |
+
return None
|
| 161 |
+
df = pd.DataFrame(history)
|
| 162 |
+
if "tipo" not in df.columns:
|
| 163 |
+
return None
|
| 164 |
+
t = df.groupby("tipo").agg(
|
| 165 |
+
Intentos=("correct", "count"),
|
| 166 |
+
Aciertos=("correct", "sum"),
|
| 167 |
+
Tasa=("correct", "mean"),
|
| 168 |
+
).reset_index().rename(columns={"tipo": "Tema"})
|
| 169 |
+
t["Tasa"] = (t["Tasa"] * 100).round(1).astype(str) + "%"
|
| 170 |
+
# Ordena por peor rendimiento primero (para que sea útil)
|
| 171 |
+
def pct_to_float(x): return float(x.replace("%", ""))
|
| 172 |
+
t = t.sort_values(by="Tasa", key=lambda s: s.map(pct_to_float))
|
| 173 |
+
return t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
# --- PDF ---
|
| 176 |
def generate_pdf(history_data, final_score, total_questions):
|
|
|
|
| 187 |
q_clean = q_clean.encode('latin-1', 'replace').decode('latin-1')
|
| 188 |
status = "BIEN" if item['correct'] else "MAL"
|
| 189 |
|
| 190 |
+
pdf.set_text_color(0, 140, 0) if item['correct'] else pdf.set_text_color(200, 0, 0)
|
| 191 |
pdf.cell(0, 8, txt=f"{i+1}. [{status}]", ln=1)
|
| 192 |
pdf.set_text_color(0, 0, 0)
|
| 193 |
pdf.multi_cell(0, 5, txt=f"P: {q_clean}...")
|
|
|
|
| 197 |
|
| 198 |
# --- MAIN ---
|
| 199 |
def main():
|
|
|
|
|
|
|
| 200 |
all_questions = load_questions()
|
| 201 |
if not all_questions:
|
| 202 |
st.warning("⚠️ No se han cargado las preguntas.")
|
|
|
|
| 216 |
st.title("🧭 Panel de Control")
|
| 217 |
|
| 218 |
if not st.session_state.exam_active:
|
| 219 |
+
st.markdown("### ⚙️ Configuración")
|
| 220 |
|
| 221 |
niveles = sorted(list(set([q.get('nivel', 'básico').lower() for q in all_questions])))
|
| 222 |
if not niveles:
|
| 223 |
niveles = ["básico", "medio", "alto"]
|
| 224 |
|
| 225 |
+
sel_levels = st.multiselect("📌 Dificultad:", niveles, default=niveles)
|
| 226 |
+
mode = st.radio("⏳ Longitud:", ["Rápido (10)", "Estándar (25)", "Completo (Todas)"])
|
| 227 |
|
| 228 |
+
if st.button("▶️ Comenzar", use_container_width=True):
|
| 229 |
if not sel_levels:
|
| 230 |
st.error("Selecciona al menos un nivel.")
|
| 231 |
else:
|
| 232 |
filtered = [q for q in all_questions if q.get('nivel', 'básico').lower() in sel_levels]
|
| 233 |
if not filtered:
|
| 234 |
+
st.error("No hay preguntas con ese filtro.")
|
| 235 |
else:
|
| 236 |
random.shuffle(filtered)
|
| 237 |
limit = 10 if "10" in mode else 25 if "25" in mode else len(filtered)
|
|
|
|
| 255 |
st.progress(min(current / total, 1.0))
|
| 256 |
st.metric("📍 Pregunta", f"{current + 1} / {total}")
|
| 257 |
|
| 258 |
+
# ✅ TASA DE ACIERTO EN TIEMPO REAL (debajo del contador)
|
| 259 |
+
answered = current # preguntas ya pasadas
|
| 260 |
+
acc = (st.session_state.score / answered) * 100 if answered > 0 else 0.0
|
| 261 |
+
st.caption(f"✅ Tasa de acierto: **{acc:.1f}%**")
|
| 262 |
|
| 263 |
+
# Tabla rendimiento por tema (bonita)
|
| 264 |
if st.session_state.history:
|
| 265 |
st.markdown("---")
|
| 266 |
+
st.caption("📊 Rendimiento por tema")
|
| 267 |
+
t = topic_table(st.session_state.history)
|
| 268 |
+
if t is not None and not t.empty:
|
| 269 |
+
st.dataframe(t, use_container_width=True, hide_index=True)
|
|
|
|
| 270 |
|
| 271 |
st.markdown("---")
|
| 272 |
+
if st.button("❌ Terminar examen", use_container_width=True):
|
| 273 |
st.session_state.current_idx = len(st.session_state.exam_pool)
|
| 274 |
st.rerun()
|
| 275 |
|
|
|
|
| 302 |
"ok": is_correct,
|
| 303 |
"expl": q["explanation"],
|
| 304 |
"corr": correct_txt,
|
|
|
|
|
|
|
| 305 |
}
|
| 306 |
|
| 307 |
if not st.session_state.answered_current:
|
|
|
|
| 310 |
st.session_state.history.append({
|
| 311 |
"question": q["question"],
|
| 312 |
"correct": is_correct,
|
| 313 |
+
"tipo": q.get("tipo", "General"),
|
| 314 |
"user_answer": user_ans,
|
| 315 |
"correct_answer": correct_txt
|
| 316 |
})
|
| 317 |
st.session_state.answered_current = True
|
| 318 |
+
|
| 319 |
st.rerun()
|
| 320 |
else:
|
| 321 |
st.warning("Por favor, selecciona una opción.")
|
|
|
|
| 329 |
else:
|
| 330 |
st.error(f"❌ Incorrecto. La respuesta correcta era: **{res['corr']}**")
|
| 331 |
|
| 332 |
+
with st.expander("📖 Ver explicación"):
|
| 333 |
st.markdown(res["expl"])
|
| 334 |
|
| 335 |
+
# Solo siguiente (sin IA)
|
| 336 |
+
if st.button("➡️ Siguiente pregunta", type="primary", use_container_width=True):
|
| 337 |
+
st.session_state.current_idx += 1
|
| 338 |
+
st.session_state.answered_current = False
|
| 339 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
# FINAL
|
| 342 |
elif st.session_state.exam_active:
|
|
|
|
| 351 |
c1.metric("✅ Nota", f"{final} / {total}")
|
| 352 |
c2.metric("📈 Porcentaje", f"{perc:.1f}%")
|
| 353 |
elapsed_time = format_time(time.time() - st.session_state.start_time)
|
| 354 |
+
c3.metric("⏱️ Tiempo total", elapsed_time)
|
| 355 |
|
| 356 |
+
# Tabla rendimiento por tema en bonito
|
| 357 |
if st.session_state.history:
|
| 358 |
+
st.markdown("### 📊 Rendimiento por tema (tabla)")
|
| 359 |
+
t = topic_table(st.session_state.history)
|
| 360 |
+
if t is not None and not t.empty:
|
| 361 |
+
st.dataframe(t, use_container_width=True, hide_index=True)
|
| 362 |
+
|
| 363 |
+
# Descargar PDF (sin botón gigante doble: lo hacemos 1 paso)
|
| 364 |
+
st.markdown("### 📄 Informe")
|
| 365 |
+
if st.button("📥 Generar y descargar PDF", use_container_width=True):
|
| 366 |
try:
|
| 367 |
pdf = generate_pdf(st.session_state.history, final, total)
|
| 368 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 369 |
pdf.output(tmp.name)
|
| 370 |
with open(tmp.name, "rb") as f:
|
| 371 |
+
st.download_button(
|
| 372 |
+
"💾 Descargar ahora",
|
| 373 |
+
f,
|
| 374 |
+
"resultados_examen.pdf",
|
| 375 |
+
use_container_width=True
|
| 376 |
+
)
|
| 377 |
except Exception:
|
| 378 |
st.error("Error generando PDF. Asegúrate de tener 'fpdf' instalado.")
|
| 379 |
|
| 380 |
+
if st.button("🏠 Volver al inicio", use_container_width=True):
|
| 381 |
st.session_state.exam_active = False
|
| 382 |
st.rerun()
|
| 383 |
|