JACINTO VELASCO commited on
Commit
ef8cdab
·
verified ·
1 Parent(s): 6822065

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -284
app.py CHANGED
@@ -7,42 +7,56 @@ import tempfile
7
  import random
8
  import os
9
  import re
 
 
10
 
11
  # --- CONFIGURACIÓN DE PÁGINA ---
12
  st.set_page_config(
13
- page_title="Examen Python",
14
  layout="wide",
15
  page_icon="🎓",
16
  initial_sidebar_state="expanded"
17
  )
18
 
19
- # --- CSS PARA MODO CLARO Y ESTILO LIMPIO ---
20
  st.markdown("""
21
  <style>
22
- /* Ajustes para modo claro */
23
- .stApp {
24
- background-color: #ffffff;
 
 
 
 
 
 
 
 
 
25
  }
26
- /* Botones más visibles */
 
27
  div.stButton > button {
28
  background-color: #007acc;
29
  color: white;
30
  border: none;
31
- font-weight: bold;
 
32
  }
33
  div.stButton > button:hover {
34
  background-color: #005f9e;
35
- color: white;
36
  }
37
- /* Resaltar bloques de código */
38
- .stCodeBlock {
39
- border: 1px solid #e0e0e0;
40
- border-radius: 5px;
41
  }
42
  </style>
43
  """, unsafe_allow_html=True)
44
 
45
- # --- CARGAR DATOS ---
 
46
  @st.cache_data
47
  def load_questions():
48
  try:
@@ -55,374 +69,283 @@ def load_questions():
55
  st.error(f"Error al cargar JSON: {e}")
56
  return []
57
 
58
- # --- RENDERIZADO INTELIGENTE ---
59
  def render_content(text):
60
- """Detecta bloques de código ```python ... ``` o ```text ... ```"""
61
  parts = text.split("```")
62
-
63
  for i, part in enumerate(parts):
64
- if i % 2 == 1: # Contenido dentro de bloques
65
  content = part.strip()
66
  if content.startswith("python"):
67
- code_body = content.replace("python", "", 1).strip()
68
- st.code(code_body, language="python")
69
  elif content.startswith("text"):
70
- diagram_body = content.replace("text", "", 1).strip("\n")
71
- st.code(diagram_body, language="plaintext")
72
  else:
73
  st.code(content, language="python")
74
  else:
75
- # Texto normal
76
  if part.strip():
77
  st.markdown(part)
78
 
79
- # --- GENERAR PDF ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def generate_pdf(history_data, final_score, total_questions):
81
  pdf = FPDF()
82
  pdf.add_page()
83
  pdf.set_font("Arial", size=12)
84
-
85
- # Título y Nota
86
- pdf.set_font("Arial", 'B', 16)
87
- pdf.cell(0, 10, txt="Resultados Examen Python", ln=1, align='C')
88
- pdf.set_font("Arial", size=12)
89
  pdf.cell(0, 10, txt=f"Nota Final: {final_score} / {total_questions}", ln=1, align='C')
90
  pdf.ln(10)
91
 
92
  pdf.set_font("Arial", size=10)
93
  for i, item in enumerate(history_data):
94
- # Limpieza básica
95
- q_text = item['question'].replace("```python", "").replace("```text", "").replace("```", "").strip()
96
- # Cortar texto muy largo y limpiar caracteres
97
- q_text = q_text[:300].encode('latin-1', 'replace').decode('latin-1')
98
-
99
  status = "CORRECTO" if item['correct'] else "INCORRECTO"
100
 
101
  pdf.set_text_color(0, 150, 0) if item['correct'] else pdf.set_text_color(200, 0, 0)
102
- pdf.cell(0, 8, txt=f"{i+1}. [{status}]", ln=1)
103
-
104
  pdf.set_text_color(0, 0, 0)
105
- pdf.multi_cell(0, 5, txt=f"P: {q_text}...")
106
  pdf.ln(2)
107
-
108
  return pdf
109
 
110
- # --- MAIN APP ---
111
  def main():
112
  all_questions = load_questions()
113
  if not all_questions:
114
- st.warning("⚠️ Sube el archivo 'questions.json' en la pestaña Files.")
115
  return
116
 
117
- # Inicializar Estado de la Aplicación
118
  if 'exam_active' not in st.session_state:
119
  st.session_state.exam_active = False
120
  st.session_state.current_idx = 0
121
  st.session_state.score = 0
122
  st.session_state.history = []
123
- st.session_state.exam_pool = [] # Lista filtrada de preguntas para este examen
124
  st.session_state.answered_current = False
 
125
 
126
- # --- BARRA LATERAL (CONFIGURACIÓN Y PROGRESO) ---
127
  with st.sidebar:
128
- st.title("⚙️ Configuración")
 
129
 
 
130
  if not st.session_state.exam_active:
131
- # --- FASE DE CONFIGURACIÓN ---
132
- st.markdown("### 1. Selecciona Niveles")
133
- # Extraer niveles únicos del JSON (normalizando a minúsculas)
134
- niveles_disponibles = sorted(list(set([q.get('nivel', 'básico').lower() for q in all_questions])))
135
- if not niveles_disponibles: niveles_disponibles = ["básico", "medio", "alto"]
136
 
137
- selected_levels = st.multiselect(
138
- "Niveles a incluir:",
139
- options=niveles_disponibles,
140
- default=niveles_disponibles
141
- )
 
 
 
142
 
143
- st.markdown("### 2. Modo de Examen")
144
- exam_mode = st.radio(
145
- "Tipo de prueba:",
146
- ["Examen Aleatorio (25 preguntas)", "Banco Completo (Todas)"]
147
- )
148
 
149
- st.divider()
150
 
151
- if st.button("🚀 COMENZAR EXAMEN", use_container_width=True):
152
- if not selected_levels:
153
- st.error("Selecciona al menos un nivel.")
154
  else:
155
- # 1. Filtrar por nivel
156
- filtered_qs = [q for q in all_questions if q.get('nivel', 'básico').lower() in selected_levels]
157
-
158
- if not filtered_qs:
159
- st.error("No hay preguntas con esos filtros.")
160
  else:
161
- # 2. Barajar
162
- random.shuffle(filtered_qs)
163
-
164
- # 3. Aplicar modo (Recortar si es necesario)
165
- if exam_mode == "Examen Aleatorio (25 preguntas)":
166
- final_pool = filtered_qs[:25]
167
- else:
168
- final_pool = filtered_qs
169
-
170
- # Guardar en sesión e iniciar
171
- st.session_state.exam_pool = final_pool
172
  st.session_state.exam_active = True
 
173
  st.session_state.current_idx = 0
174
  st.session_state.score = 0
175
  st.session_state.history = []
176
- st.session_state.answered_current = False
177
  st.rerun()
178
-
 
179
  else:
180
- # --- FASE DE PROGRESO (DURANTE EL EXAMEN) ---
181
- total_q = len(st.session_state.exam_pool)
182
  current = st.session_state.current_idx
183
 
184
- st.markdown(f"### Pregunta {current + 1} de {total_q}")
185
- st.progress(min(current / total_q, 1.0))
 
 
186
 
 
 
187
  st.metric("Aciertos", f"{st.session_state.score}")
188
 
189
- # Cálculo de % en tiempo real
190
- if current > 0:
191
- acc = (st.session_state.score / current) * 100
192
- st.caption(f"Precisión actual: **{acc:.1f}%**")
193
-
194
- st.divider()
195
- if st.button("❌ Cancelar / Reiniciar"):
196
- st.session_state.exam_active = False
 
 
 
 
197
  st.rerun()
198
 
199
- # --- PANTALLA PRINCIPAL ---
200
 
201
- # CASO 1: Examen en curso
202
  if st.session_state.exam_active and st.session_state.current_idx < len(st.session_state.exam_pool):
203
  q = st.session_state.exam_pool[st.session_state.current_idx]
204
 
205
- # Enunciado (Sin Topic)
206
  st.subheader(f"Pregunta {st.session_state.current_idx + 1}")
207
- # Solo mostramos el nivel, hemos quitado el Topic como pediste
208
- st.caption(f"Nivel: {q.get('nivel', 'General').capitalize()}")
209
 
210
  render_content(q['question'])
211
 
212
- st.write("---")
 
 
 
 
213
 
214
- # Formulario de Respuesta
215
- with st.form(key=f"form_{st.session_state.current_idx}"):
216
- # Barajamos las opciones para que no sea siempre la misma posición
217
- # Pero necesitamos mantener el rastreo de la correcta.
218
- # El JSON tiene 'answer_index' apuntando a la lista original 'options'.
219
-
220
- options_original = q['options']
221
- # Creamos una lista de tuplas (índice_original, texto_opcion)
222
- options_with_idx = list(enumerate(options_original))
223
-
224
- # Si aún no hemos guardado el orden aleatorio para esta pregunta, lo hacemos
225
- if f"shuffled_opts_{st.session_state.current_idx}" not in st.session_state:
226
- random.shuffle(options_with_idx)
227
- st.session_state[f"shuffled_opts_{st.session_state.current_idx}"] = options_with_idx
228
-
229
- current_options = st.session_state[f"shuffled_opts_{st.session_state.current_idx}"]
230
-
231
- # Mostramos solo el texto en el radio button
232
- radio_labels = [opt[1] for opt in current_options]
233
-
234
- user_selection = st.radio("Selecciona una opción:", radio_labels, index=None)
235
-
236
- submitted = st.form_submit_button("✅ Enviar Respuesta")
237
 
238
- if submitted:
239
- if user_selection:
240
- # Buscar el índice original de la selección del usuario
241
- selected_original_index = -1
242
- for original_idx, text in current_options:
243
- if text == user_selection:
244
- selected_original_index = original_idx
245
- break
246
 
247
- correct_index = q['answer_index']
248
- is_correct = (selected_original_index == correct_index)
249
- correct_text = options_original[correct_index]
250
-
251
- # Guardar lógica para mostrar fuera del form
252
- st.session_state.last_feedback = {
253
- "is_correct": is_correct,
254
- "correct_text": correct_text,
255
- "explanation": q['explanation'],
256
- "user_text": user_selection
257
  }
258
 
259
- # Actualizar estado si es la primera vez que responde esta pregunta
260
  if not st.session_state.answered_current:
261
- if is_correct:
262
- st.session_state.score += 1
263
-
264
  st.session_state.history.append({
265
  "question": q["question"],
266
  "correct": is_correct,
267
- "user_answer": user_selection,
268
- "correct_answer": correct_text,
269
- "tipo": q["tipo"]
270
  })
271
  st.session_state.answered_current = True
272
-
273
  st.rerun()
274
  else:
275
  st.warning("Selecciona una opción.")
276
 
277
- # Mostrar Feedback y Botón Siguiente
278
- if st.session_state.answered_current and "last_feedback" in st.session_state:
279
- fb = st.session_state.last_feedback
280
- if fb["is_correct"]:
281
- st.success(f"**¡Correcto!** \n\n{fb['explanation']}")
282
  else:
283
- st.error(f"**Incorrecto**")
284
- st.markdown(f"La respuesta correcta era: **{fb['correct_text']}**")
285
- st.info(f"ℹ️ **Explicación:** {fb['explanation']}")
286
 
287
- if st.button("Siguiente ➡", type="primary"):
288
- st.session_state.current_idx += 1
289
- st.session_state.answered_current = False
290
- # Limpiar el shuffle guardado para ahorrar memoria o por limpieza
291
- del st.session_state[f"shuffled_opts_{st.session_state.current_idx - 1}"]
292
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
293
 
294
- # CASO 2: Examen Finalizado
295
- elif st.session_state.exam_active and st.session_state.current_idx >= len(st.session_state.exam_pool):
296
  st.balloons()
297
- st.markdown("<h1 style='text-align: center;'>🏆 Examen Finalizado</h1>", unsafe_allow_html=True)
298
 
299
- final_score = st.session_state.score
300
  total = len(st.session_state.exam_pool)
301
- if total > 0:
302
- perc = round((final_score / total) * 100, 1)
303
- else:
304
- perc = 0
305
-
306
- col1, col2, col3 = st.columns([1, 2, 1])
307
- with col2:
308
- st.metric("Nota Final", f"{final_score} / {total}", f"{perc}%")
309
- if perc >= 50:
310
- st.success("¡Has aprobado! 🎉")
311
- else:
312
- st.error("Necesitas repasar más. 📚")
313
 
314
- # Estadísticas por Tipo (que era tu pregunta original)
315
  if st.session_state.history:
316
  df = pd.DataFrame(st.session_state.history)
317
- st.subheader("Rendimiento por Tema")
318
-
319
- if "tipo" in df.columns:
320
- stats = df.groupby("tipo")["correct"].mean() * 100
321
- fig, ax = plt.subplots(figsize=(6, 3))
322
- stats.plot(kind="bar", color="#007acc", ax=ax)
323
- ax.set_ylabel("% Acierto")
324
- plt.xticks(rotation=45)
325
- ax.grid(axis='y', linestyle='--', alpha=0.5)
326
- st.pyplot(fig)
327
-
328
- # Generar PDF
329
- if st.button("📄 Descargar Certificado/Resultados (PDF)"):
330
- try:
331
- pdf = generate_pdf(st.session_state.history, final_score, total)
332
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
333
- pdf.output(tmp.name)
334
- with open(tmp.name, "rb") as f:
335
- st.download_button(
336
- "⬇️ Descargar PDF",
337
- data=f,
338
- file_name="resultados_examen.pdf",
339
- mime="application/pdf"
340
- )
341
- except Exception as e:
342
- st.error(f"Error al generar PDF: {e}")
343
-
344
- if st.button("🏠 Volver al Inicio"):
345
- st.session_state.exam_active = False
346
- st.rerun()
347
-
348
- # CASO 3: Pantalla de Bienvenida (Si no está activo)
349
- else:
350
- st.info("👈 Configura tu examen en la barra lateral izquierda para comenzar.")
351
- st.markdown("""
352
- ### Instrucciones:
353
- 1. Elige los **niveles** que quieres practicar.
354
- 2. Elige si quieres hacer el **banco completo** o un **test rápido de 25**.
355
- 3. Pulsa **Comenzar**.
356
- """)
357
-
358
- # ==========================================
359
- # 🛠️ HERRAMIENTA DE LIMPIEZA (Ejecutar en la web)
360
- # ==========================================
361
- import difflib
362
-
363
- def clean_duplicates_logic():
364
- st.sidebar.markdown("---")
365
- st.sidebar.header("🔧 Zona Admin")
366
-
367
- if st.sidebar.button("🧹 Limpiar Duplicados Ahora"):
368
- try:
369
- with open("questions.json", "r", encoding="utf-8") as f:
370
- data = json.load(f)
371
-
372
- unique_questions = []
373
- seen_texts = []
374
- removed_count = 0
375
-
376
- # Barra de progreso
377
- progress_bar = st.sidebar.progress(0)
378
 
379
- for i, q in enumerate(data):
380
- is_duplicate = False
381
- current_text = q['question'].strip()
382
-
383
- # Comprobar similitud con las ya guardadas
384
- for seen_text in seen_texts:
385
- # Usamos difflib para comparar similitud de texto (0 a 1)
386
- ratio = difflib.SequenceMatcher(None, current_text, seen_text).ratio()
387
- if ratio > 0.9: # Si es más del 90% igual, es duplicada
388
- is_duplicate = True
389
- removed_count += 1
390
- break
391
-
392
- if not is_duplicate:
393
- unique_questions.append(q)
394
- seen_texts.append(current_text)
395
-
396
- progress_bar.progress((i + 1) / len(data))
397
-
398
- # Renumerar IDs
399
- for idx, q in enumerate(unique_questions):
400
- q['id'] = idx + 1
401
-
402
- # Guardar el archivo limpio en el sistema temporal
403
- with open("questions.json", "w", encoding="utf-8") as f:
404
- json.dump(unique_questions, f, ensure_ascii=False, indent=2)
405
-
406
- st.sidebar.success(f"✅ ¡Limpieza completada! Eliminadas: {removed_count}. Total actual: {len(unique_questions)}")
407
-
408
- # Botón para descargar el JSON arreglado
409
- with open("questions.json", "r", encoding="utf-8") as f:
410
- st.sidebar.download_button(
411
- label="⬇️ Descargar JSON Limpio",
412
- data=f,
413
- file_name="questions_clean.json",
414
- mime="application/json"
415
- )
416
-
417
- # Forzar recarga
418
  st.rerun()
419
 
420
- except Exception as e:
421
- st.sidebar.error(f"Error: {e}")
422
-
423
- # Añadir esta llamada dentro de tu función main() o al final del script
424
- # Si lo pones al final del script, asegúrate de que esté identado correctamente o fuera del main
425
-
426
 
427
  if __name__ == "__main__":
428
  main()
 
7
  import random
8
  import os
9
  import re
10
+ import time
11
+ import requests
12
 
13
  # --- CONFIGURACIÓN DE PÁGINA ---
14
  st.set_page_config(
15
+ page_title="Examen Python & Matemáticas",
16
  layout="wide",
17
  page_icon="🎓",
18
  initial_sidebar_state="expanded"
19
  )
20
 
21
+ # --- CSS MEJORADO (Estilo Limpio + Código VS Code) ---
22
  st.markdown("""
23
  <style>
24
+ .stApp { background-color: #ffffff; color: #1f1f1f; }
25
+
26
+ /* Bloques de código oscuros estilo VS Code */
27
+ code {
28
+ color: #dcdcaa;
29
+ background-color: #1e1e1e;
30
+ padding: 2px 5px;
31
+ border-radius: 4px;
32
+ }
33
+ .stCodeBlock pre {
34
+ background-color: #1e1e1e !important;
35
+ border: 1px solid #333;
36
  }
37
+
38
+ /* Botones */
39
  div.stButton > button {
40
  background-color: #007acc;
41
  color: white;
42
  border: none;
43
+ font-weight: 600;
44
+ transition: 0.3s;
45
  }
46
  div.stButton > button:hover {
47
  background-color: #005f9e;
48
+ transform: scale(1.02);
49
  }
50
+
51
+ /* Sidebar */
52
+ [data-testid="stSidebar"] {
53
+ background-color: #f0f2f6;
54
  }
55
  </style>
56
  """, unsafe_allow_html=True)
57
 
58
+ # --- FUNCIONES DE CARGA Y UTILIDADES ---
59
+
60
  @st.cache_data
61
  def load_questions():
62
  try:
 
69
  st.error(f"Error al cargar JSON: {e}")
70
  return []
71
 
 
72
  def render_content(text):
73
+ """Renderiza texto mezclado con bloques de código."""
74
  parts = text.split("```")
 
75
  for i, part in enumerate(parts):
76
+ if i % 2 == 1:
77
  content = part.strip()
78
  if content.startswith("python"):
79
+ st.code(content.replace("python", "", 1).strip(), language="python")
 
80
  elif content.startswith("text"):
81
+ st.code(content.replace("text", "", 1).strip(), language="plaintext")
 
82
  else:
83
  st.code(content, language="python")
84
  else:
 
85
  if part.strip():
86
  st.markdown(part)
87
 
88
+ def format_time(seconds):
89
+ """Convierte segundos a formato MM:SS"""
90
+ m, s = divmod(seconds, 60)
91
+ return f"{int(m):02d}:{int(s):02d}"
92
+
93
+ # --- INTEGRACIÓN HUGGING FACE API ---
94
+ def query_huggingface(payload, api_token):
95
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
96
+ headers = {"Authorization": f"Bearer {api_token}"}
97
+
98
+ try:
99
+ response = requests.post(API_URL, headers=headers, json=payload)
100
+ return response.json()
101
+ except Exception as e:
102
+ return {"error": str(e)}
103
+
104
+ def get_ai_explanation(question_text, correct_answer, topic, token):
105
+ if not token:
106
+ return "⚠️ Necesitas un Token de Hugging Face para usar la IA."
107
+
108
+ prompt = f"""[INST] Actúa como un profesor experto en programación Python e Ingeniería.
109
+ Explica de forma didáctica, breve y clara el siguiente concepto teórico relacionado con la pregunta.
110
+
111
+ Tema: {topic}
112
+ Pregunta: {question_text}
113
+ La respuesta correcta es: {correct_answer}
114
+
115
+ Explica POR QUÉ es la correcta y da un ejemplo breve si aplica. [/INST]
116
+ """
117
+
118
+ with st.spinner("🤖 La IA está pensando..."):
119
+ output = query_huggingface({"inputs": prompt, "parameters": {"max_new_tokens": 500}}, token)
120
+
121
+ if isinstance(output, list) and 'generated_text' in output[0]:
122
+ # Limpiar el prompt de la respuesta
123
+ return output[0]['generated_text'].replace(prompt, "").strip()
124
+ elif 'error' in output:
125
+ return f"Error API: {output['error']}"
126
+ else:
127
+ return "No se pudo generar la explicación."
128
+
129
+ # --- GENERACIÓN PDF ---
130
  def generate_pdf(history_data, final_score, total_questions):
131
  pdf = FPDF()
132
  pdf.add_page()
133
  pdf.set_font("Arial", size=12)
134
+ pdf.cell(0, 10, txt="Informe de Resultados - Examen Python", ln=1, align='C')
 
 
 
 
135
  pdf.cell(0, 10, txt=f"Nota Final: {final_score} / {total_questions}", ln=1, align='C')
136
  pdf.ln(10)
137
 
138
  pdf.set_font("Arial", size=10)
139
  for i, item in enumerate(history_data):
140
+ q_clean = item['question'].replace("```python", "").replace("```text", "").replace("```", "")[:200]
141
+ q_clean = q_clean.encode('latin-1', 'replace').decode('latin-1')
 
 
 
142
  status = "CORRECTO" if item['correct'] else "INCORRECTO"
143
 
144
  pdf.set_text_color(0, 150, 0) if item['correct'] else pdf.set_text_color(200, 0, 0)
145
+ pdf.cell(0, 8, txt=f"{i+1}. [{status}] - {item['tipo']}", ln=1)
 
146
  pdf.set_text_color(0, 0, 0)
147
+ pdf.multi_cell(0, 5, txt=f"P: {q_clean}...")
148
  pdf.ln(2)
 
149
  return pdf
150
 
151
+ # --- MAIN ---
152
  def main():
153
  all_questions = load_questions()
154
  if not all_questions:
155
+ st.warning("⚠️ Sube 'questions.json' en la pestaña Files.")
156
  return
157
 
158
+ # Inicializar Session State
159
  if 'exam_active' not in st.session_state:
160
  st.session_state.exam_active = False
161
  st.session_state.current_idx = 0
162
  st.session_state.score = 0
163
  st.session_state.history = []
164
+ st.session_state.exam_pool = []
165
  st.session_state.answered_current = False
166
+ st.session_state.start_time = None
167
 
168
+ # --- BARRA LATERAL ---
169
  with st.sidebar:
170
+ st.image("https://img.icons8.com/color/96/python.png", width=50)
171
+ st.title("Panel de Control")
172
 
173
+ # 1. Configuración (Solo si no hay examen activo)
174
  if not st.session_state.exam_active:
175
+ st.markdown("### ⚙️ Configuración")
 
 
 
 
176
 
177
+ # Token HF (Intenta leer de secrets, si no, pide al usuario)
178
+ hf_token = st.secrets.get("HF_TOKEN", "")
179
+ if not hf_token:
180
+ hf_token = st.text_input("HF Token (para IA):", type="password", help="Necesario para las explicaciones con IA")
181
+ st.session_state.hf_token = hf_token
182
+
183
+ niveles = sorted(list(set([q.get('nivel', 'básico').lower() for q in all_questions])))
184
+ if not niveles: niveles = ["básico", "medio", "alto"]
185
 
186
+ sel_levels = st.multiselect("Nivel:", niveles, default=niveles)
 
 
 
 
187
 
188
+ mode = st.radio("Modo:", ["Examen Rápido (10 preg)", "Examen Estándar (25 preg)", "Banco Completo"])
189
 
190
+ if st.button("▶️ COMENZAR EXAMEN", use_container_width=True):
191
+ if not sel_levels:
192
+ st.error("Selecciona nivel.")
193
  else:
194
+ filtered = [q for q in all_questions if q.get('nivel', 'básico').lower() in sel_levels]
195
+ if not filtered:
196
+ st.error("No hay preguntas.")
 
 
197
  else:
198
+ random.shuffle(filtered)
199
+ limit = 10 if "10" in mode else 25 if "25" in mode else len(filtered)
200
+ st.session_state.exam_pool = filtered[:limit]
 
 
 
 
 
 
 
 
201
  st.session_state.exam_active = True
202
+ st.session_state.start_time = time.time()
203
  st.session_state.current_idx = 0
204
  st.session_state.score = 0
205
  st.session_state.history = []
 
206
  st.rerun()
207
+
208
+ # 2. Información en Vivo (Durante el examen)
209
  else:
210
+ total = len(st.session_state.exam_pool)
 
211
  current = st.session_state.current_idx
212
 
213
+ # --- RELOJ ---
214
+ if st.session_state.start_time:
215
+ elapsed = time.time() - st.session_state.start_time
216
+ st.markdown(f"### ⏱️ Tiempo: {format_time(elapsed)}")
217
 
218
+ st.progress(min(current / total, 1.0))
219
+ st.metric("Pregunta", f"{current + 1} / {total}")
220
  st.metric("Aciertos", f"{st.session_state.score}")
221
 
222
+ # --- ESTADÍSTICAS EN VIVO ---
223
+ if st.session_state.history:
224
+ st.markdown("---")
225
+ st.markdown("##### 📊 Rendimiento por Tipo")
226
+ df = pd.DataFrame(st.session_state.history)
227
+ if "tipo" in df.columns:
228
+ stats = df.groupby("tipo")["correct"].mean() * 100
229
+ st.bar_chart(stats, color="#007acc", height=150)
230
+
231
+ st.markdown("---")
232
+ if st.button("❌ Finalizar"):
233
+ st.session_state.current_idx = len(st.session_state.exam_pool)
234
  st.rerun()
235
 
236
+ # --- ÁREA PRINCIPAL ---
237
 
238
+ # PANTALLA DE EXAMEN
239
  if st.session_state.exam_active and st.session_state.current_idx < len(st.session_state.exam_pool):
240
  q = st.session_state.exam_pool[st.session_state.current_idx]
241
 
 
242
  st.subheader(f"Pregunta {st.session_state.current_idx + 1}")
243
+ st.caption(f"Tema: {q['topic']} | Nivel: {q.get('nivel', '').capitalize()}")
 
244
 
245
  render_content(q['question'])
246
 
247
+ # Opciones barajadas
248
+ if f"opts_{st.session_state.current_idx}" not in st.session_state:
249
+ opts = list(enumerate(q['options']))
250
+ random.shuffle(opts)
251
+ st.session_state[f"opts_{st.session_state.current_idx}"] = opts
252
 
253
+ current_opts = st.session_state[f"opts_{st.session_state.current_idx}"]
254
+ labels = [o[1] for o in current_opts]
255
+
256
+ with st.form(key=f"q{st.session_state.current_idx}"):
257
+ user_ans = st.radio("Tu respuesta:", labels, index=None)
258
+ sub = st.form_submit_button("Responder")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
+ if sub:
261
+ if user_ans:
262
+ # Encontrar índice original
263
+ orig_idx = next(idx for idx, txt in current_opts if txt == user_ans)
264
+ is_correct = (orig_idx == q['answer_index'])
265
+ correct_txt = q['options'][q['answer_index']]
 
 
266
 
267
+ st.session_state.last_result = {
268
+ "ok": is_correct,
269
+ "expl": q['explanation'],
270
+ "corr": correct_txt,
271
+ "q_text": q['question'],
272
+ "topic": q['topic']
 
 
 
 
273
  }
274
 
 
275
  if not st.session_state.answered_current:
276
+ if is_correct: st.session_state.score += 1
 
 
277
  st.session_state.history.append({
278
  "question": q["question"],
279
  "correct": is_correct,
280
+ "tipo": q["tipo"],
281
+ "user_answer": user_ans,
282
+ "correct_answer": correct_txt
283
  })
284
  st.session_state.answered_current = True
 
285
  st.rerun()
286
  else:
287
  st.warning("Selecciona una opción.")
288
 
289
+ # FEEDBACK Y IA
290
+ if st.session_state.answered_current and "last_result" in st.session_state:
291
+ res = st.session_state.last_result
292
+ if res["ok"]:
293
+ st.success(f"¡Correcto! 🎉\n\n{res['expl']}")
294
  else:
295
+ st.error(f"Incorrecto. La correcta era: **{res['corr']}**\n\n{res['expl']}")
 
 
296
 
297
+ # --- BOTÓN IA ---
298
+ col_ia, col_next = st.columns([1, 1])
299
+ with col_ia:
300
+ if st.button("🤖 Explicar mejor con IA"):
301
+ explanation = get_ai_explanation(
302
+ res['q_text'],
303
+ res['corr'],
304
+ res['topic'],
305
+ st.session_state.hf_token
306
+ )
307
+ st.info(explanation)
308
+
309
+ with col_next:
310
+ if st.button("Siguiente ➡", type="primary"):
311
+ st.session_state.current_idx += 1
312
+ st.session_state.answered_current = False
313
+ st.rerun()
314
 
315
+ # PANTALLA FINAL
316
+ elif st.session_state.exam_active:
317
  st.balloons()
318
+ st.title("Resultados Finales")
319
 
320
+ final = st.session_state.score
321
  total = len(st.session_state.exam_pool)
322
+ perc = (final/total)*100 if total > 0 else 0
323
+
324
+ col1, col2, col3 = st.columns(3)
325
+ col1.metric("Nota", f"{final}/{total}")
326
+ col2.metric("Porcentaje", f"{perc:.1f}%")
327
+ col3.metric("Tiempo", format_time(time.time() - st.session_state.start_time))
 
 
 
 
 
 
328
 
 
329
  if st.session_state.history:
330
  df = pd.DataFrame(st.session_state.history)
331
+ st.markdown("### Rendimiento por Tipo")
332
+ stats = df.groupby("tipo")["correct"].mean() * 100
333
+ st.bar_chart(stats)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
+ if st.button("Descargar PDF"):
336
+ pdf = generate_pdf(st.session_state.history, final, total)
337
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
338
+ pdf.output(tmp.name)
339
+ with open(tmp.name, "rb") as f:
340
+ st.download_button("📥 PDF Resultados", f, "examen.pdf")
341
+
342
+ if st.button("Volver al Inicio"):
343
+ for key in list(st.session_state.keys()):
344
+ del st.session_state[key]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  st.rerun()
346
 
347
+ else:
348
+ st.info("👈 Configura el examen en la barra lateral.")
 
 
 
 
349
 
350
  if __name__ == "__main__":
351
  main()