JACINTO VELASCO commited on
Commit
4433ec0
·
verified ·
1 Parent(s): bf4868e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +376 -199
app.py CHANGED
@@ -8,7 +8,7 @@ import html
8
  import streamlit.components.v1 as components
9
 
10
  # =========================================================
11
- # CONFIGURACIÓN GENERAL
12
  # =========================================================
13
  st.set_page_config(
14
  page_title="Fundamentos de Programación y Computadores",
@@ -18,97 +18,75 @@ st.set_page_config(
18
  )
19
 
20
  # =========================================================
21
- # ESTILOS (BLANCO, LIMPIO, BOTONES CLAROS, CÓDIGO GRIS)
22
  # =========================================================
23
  st.markdown("""
24
  <style>
25
  .stApp { background:#ffffff; color:#111827; }
 
 
26
 
27
- .block-container {
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;
35
- }
36
-
37
- /* Header */
38
- [data-testid="stHeader"]{
39
- background: rgba(255,255,255,0.96);
40
- border-bottom: 1px solid #e5e7eb;
41
- }
42
 
43
- /* Sidebar */
44
- [data-testid="stSidebar"]{
45
- background:#f8fafc;
46
- border-right:1px solid #e5e7eb;
47
  }
48
- [data-testid="stSidebar"] > div { padding-top: 1rem; }
49
 
50
  /* Botones claros */
51
- div.stButton > button,
52
- div.stFormSubmitButton > button {
53
- background:#eef2ff !important;
54
- color:#3730a3 !important;
55
- border:1px solid #c7d2fe !important;
56
- border-radius:12px !important;
57
- font-weight:800 !important;
58
- padding:0.6rem 1rem !important;
59
  }
60
  button[kind="primary"]{
61
- background:#dcfce7 !important;
62
- border:1px solid #86efac !important;
63
- color:#166534 !important;
64
- }
65
-
66
- /* Tarjetas */
67
- [data-testid="stMetric"]{
68
- background:#ffffff;
69
- border:1px solid #e5e7eb;
70
- border-radius:14px;
71
- padding:10px 12px;
72
  }
73
 
74
  /* Código estilo VS Code claro */
75
- .stCodeBlock pre {
76
- background:#f3f4f6 !important;
77
- border:1px solid #e5e7eb !important;
78
- border-radius:12px !important;
79
- padding:14px !important;
80
- }
81
- code {
82
- background:#f3f4f6 !important;
83
- border:1px solid #e5e7eb !important;
84
- border-radius:8px !important;
85
- padding:1px 6px !important;
86
- color:#111827 !important;
87
- }
88
 
89
- /* Cards */
90
- .info-card{
91
  border: 1px solid #e5e7eb;
92
- border-radius: 16px;
93
- padding: 16px 18px;
94
  background: #ffffff;
95
- margin-bottom: 16px;
 
96
  }
97
- .muted { color:#475569; }
98
- .badge {
99
- display:inline-block;
100
- padding: 2px 10px;
101
- border-radius: 999px;
102
- border: 1px solid #e5e7eb;
103
- background: #f8fafc;
104
- margin-right: 6px;
105
- margin-bottom: 6px;
 
 
 
 
 
 
 
 
 
106
  }
 
 
 
 
107
  </style>
108
  """, unsafe_allow_html=True)
109
 
110
  # =========================================================
111
- # CARGAR PREGUNTAS
112
  # =========================================================
113
  @st.cache_data
114
  def load_questions():
@@ -121,35 +99,12 @@ def norm(s):
121
  return str(s).strip().lower()
122
 
123
  # =========================================================
124
- # ESTADÍSTICAS DEL JSON
125
- # =========================================================
126
- def analyze_questions(questions):
127
- df = pd.DataFrame(questions)
128
- total = len(df)
129
-
130
- df["nivel"] = df.get("nivel", "básico").map(norm)
131
- df["tipo"] = df.get("tipo", "General").astype(str)
132
- df["topic"] = df.get("topic", "").astype(str)
133
-
134
- by_level = df["nivel"].value_counts().reset_index()
135
- by_level.columns = ["Dificultad", "Preguntas"]
136
- by_level["%"] = (by_level["Preguntas"] / total * 100).round(1)
137
-
138
- by_type = df["tipo"].value_counts().reset_index()
139
- by_type.columns = ["Tipo", "Preguntas"]
140
- by_type["%"] = (by_type["Preguntas"] / total * 100).round(1)
141
-
142
- topics = sorted([t for t in df["topic"].unique() if t.strip()])
143
-
144
- return total, by_level, by_type, topics
145
-
146
- # =========================================================
147
- # RENDER DE CONTENIDO (CÓDIGO + MERMAID)
148
  # =========================================================
149
  def render_mermaid(mermaid_code):
150
  mermaid_code = html.escape(mermaid_code.strip())
151
  components.html(f"""
152
- <div style="border:1px solid #e5e7eb;border-radius:12px;padding:14px;">
153
  <script type="module">
154
  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
155
  mermaid.initialize({{ startOnLoad: true }});
@@ -163,12 +118,14 @@ def render_content(text):
163
  for i, part in enumerate(parts):
164
  if i % 2 == 1:
165
  content = part.strip()
166
- lang = content.splitlines()[0].strip().lower()
167
- body = content[len(lang):].lstrip("\n")
168
- if lang in ("python", "py"):
169
  st.code(body, language="python")
170
- elif lang == "mermaid":
171
  render_mermaid(body)
 
 
172
  else:
173
  st.code(content, language="plaintext")
174
  else:
@@ -179,6 +136,70 @@ def format_time(sec):
179
  m, s = divmod(int(sec), 60)
180
  return f"{m:02d}:{s:02d}"
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  # =========================================================
183
  # MAIN
184
  # =========================================================
@@ -188,9 +209,9 @@ def main():
188
  st.error("No se ha encontrado questions.json")
189
  return
190
 
191
- total, by_level, by_type, topics = analyze_questions(questions)
192
 
193
- # Estado
194
  if "exam_active" not in st.session_state:
195
  st.session_state.exam_active = False
196
  st.session_state.exam_pool = []
@@ -199,131 +220,287 @@ def main():
199
  st.session_state.history = []
200
  st.session_state.start_time = None
201
  st.session_state.answered_current = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
- # =====================================================
204
- # PANTALLA DE INICIO
205
- # =====================================================
206
- if not st.session_state.exam_active:
207
- st.markdown("""
208
- <div class="info-card">
209
- <h1>🧠 Fundamentos de Programación y Computadores</h1>
210
- <p class="muted">
211
- Examen de prueba para preparar el próximo examen oficial.
212
- </p>
213
- </div>
214
- """, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  st.markdown("""
217
  <div class="info-card">
218
- <h3>✅ Cómo usar la aplicación</h3>
219
- <ol>
220
- <li>Selecciona la <b>dificultad</b> en el panel izquierdo.</li>
221
- <li>Elige la <b>longitud</b> del examen (10, 25 o todas).</li>
222
- <li>Pulsa <b>▶️ Comenzar</b> para iniciar.</li>
223
- <li>Responde cada pregunta y avanza con <b>Siguiente</b>.</li>
224
- <li>Consulta tu <b>tasa de acierto</b> en tiempo real.</li>
225
  </ol>
226
-
227
- <h3>💡 Consejos</h3>
228
- <ul>
229
- <li>Lee el código línea a línea, especialmente condiciones.</li>
230
- <li>En diagramas, sigue el flujo paso a paso.</li>
231
- <li>Haz primero un examen rápido como entrenamiento.</li>
232
  </ul>
233
  </div>
234
  """, unsafe_allow_html=True)
235
 
236
- c1, c2 = st.columns(2)
 
237
  with c1:
238
- st.markdown("### 📊 Banco de preguntas")
239
- st.write(f"**Total:** {total}")
240
- st.dataframe(by_level, hide_index=True)
241
- st.dataframe(by_type, hide_index=True)
242
-
243
  with c2:
244
- st.markdown("### 🏷️ Temáticas")
245
- for t in topics:
246
- st.markdown(f"<span class='badge'>{html.escape(t)}</span>", unsafe_allow_html=True)
247
-
248
- # =====================================================
249
- # SIDEBAR
250
- # =====================================================
251
- with st.sidebar:
252
- st.header("⚙️ Configuración")
253
 
254
- if not st.session_state.exam_active:
255
- niveles = sorted(set(norm(q.get("nivel", "básico")) for q in questions))
256
- sel = st.multiselect("Dificultad:", niveles, default=niveles)
257
- mode = st.radio("Longitud:", ["Rápido (10)", "Estándar (25)", "Completo"])
258
-
259
- if st.button("▶️ Comenzar", use_container_width=True):
260
- filtered = [q for q in questions if norm(q.get("nivel", "básico")) in sel]
261
- random.shuffle(filtered)
262
- limit = 10 if "10" in mode else 25 if "25" in mode else len(filtered)
263
- st.session_state.exam_pool = filtered[:limit]
264
- st.session_state.exam_active = True
265
- st.session_state.start_time = time.time()
266
- st.session_state.current_idx = 0
267
- st.session_state.score = 0
268
- st.session_state.history = []
269
- st.session_state.answered_current = False
270
- st.experimental_rerun()
271
-
272
- else:
273
- total_q = len(st.session_state.exam_pool)
274
- current = st.session_state.current_idx
275
- st.metric("Pregunta", f"{current+1} / {total_q}")
276
- if current > 0:
277
- acc = st.session_state.score / current * 100
278
- st.metric("Acierto", f"{acc:.1f}%")
279
- if st.button("❌ Terminar"):
280
- st.session_state.current_idx = total_q
281
- st.experimental_rerun()
282
 
283
- # =====================================================
284
- # EXAMEN
285
- # =====================================================
286
  if st.session_state.exam_active and st.session_state.current_idx < len(st.session_state.exam_pool):
287
  q = st.session_state.exam_pool[st.session_state.current_idx]
288
- st.subheader(f"Pregunta {st.session_state.current_idx + 1}")
 
289
  render_content(q["question"])
290
 
291
- opts = list(enumerate(q["options"]))
292
- random.shuffle(opts)
293
- labels = [o[1] for o in opts]
294
-
295
- with st.form("answer"):
296
- ans = st.radio("Selecciona una opción:", labels)
297
- if st.form_submit_button("Responder"):
298
- idx = next(i for i, t in opts if t == ans)
299
- ok = idx == q["answer_index"]
300
- if ok:
301
- st.success("Correcto")
302
- st.session_state.score += 1
303
- else:
304
- st.error(f"Incorrecto. Respuesta correcta: {q['options'][q['answer_index']]}")
305
- st.session_state.history.append({
306
- "tipo": q.get("tipo", ""),
307
- "correct": ok
308
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  st.session_state.current_idx += 1
310
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
- # =====================================================
 
 
 
 
 
 
 
 
 
 
313
  # FINAL
314
- # =====================================================
315
  elif st.session_state.exam_active:
316
  st.balloons()
317
- st.header("Resultados")
 
318
  total_q = len(st.session_state.exam_pool)
319
  score = st.session_state.score
320
- st.metric("Nota", f"{score} / {total_q}")
321
- st.metric("Porcentaje", f"{score/total_q*100:.1f}%")
322
- st.metric("Tiempo", format_time(time.time() - st.session_state.start_time))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
- if st.button("🏠 Volver al inicio"):
 
325
  st.session_state.exam_active = False
326
- st.experimental_rerun()
327
 
328
  if __name__ == "__main__":
329
  main()
 
 
8
  import streamlit.components.v1 as components
9
 
10
  # =========================================================
11
+ # CONFIG
12
  # =========================================================
13
  st.set_page_config(
14
  page_title="Fundamentos de Programación y Computadores",
 
18
  )
19
 
20
  # =========================================================
21
+ # CSS: blanco limpio + tarjetas respuesta + colores feedback + código gris
22
  # =========================================================
23
  st.markdown("""
24
  <style>
25
  .stApp { background:#ffffff; color:#111827; }
26
+ .block-container { padding-top: 1.2rem; padding-bottom: 2.0rem; max-width: 1200px; }
27
+ html, body, [class*="css"] { font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial; }
28
 
29
+ [data-testid="stHeader"]{ background: rgba(255,255,255,0.96); border-bottom: 1px solid #e5e7eb; }
30
+ [data-testid="stSidebar"]{ background:#f8fafc; border-right:1px solid #e5e7eb; }
31
+ [data-testid="stSidebar"] > div { padding-top: 1rem; }
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ .info-card{
34
+ border: 1px solid #e5e7eb; border-radius: 16px; padding: 16px 18px;
35
+ background: #ffffff; margin-bottom: 16px;
 
36
  }
37
+ .muted { color:#475569; }
38
 
39
  /* Botones claros */
40
+ div.stButton > button, div.stFormSubmitButton > button {
41
+ background:#eef2ff !important; color:#3730a3 !important;
42
+ border:1px solid #c7d2fe !important; border-radius:12px !important;
43
+ font-weight:800 !important; padding:0.6rem 1rem !important;
 
 
 
 
44
  }
45
  button[kind="primary"]{
46
+ background:#dcfce7 !important; border:1px solid #86efac !important; color:#166534 !important;
 
 
 
 
 
 
 
 
 
 
47
  }
48
 
49
  /* Código estilo VS Code claro */
50
+ .stCodeBlock pre { background:#f3f4f6 !important; border:1px solid #e5e7eb !important; border-radius:12px !important; padding:14px !important; }
51
+ code { background:#f3f4f6 !important; border:1px solid #e5e7eb !important; border-radius:8px !important; padding:1px 6px !important; color:#111827 !important; }
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ /* Tarjetas de respuesta */
54
+ .answer-card{
55
  border: 1px solid #e5e7eb;
56
+ border-radius: 14px;
57
+ padding: 14px 14px;
58
  background: #ffffff;
59
+ cursor: pointer;
60
+ transition: transform 0.06s ease, box-shadow 0.15s ease, border-color 0.15s ease;
61
  }
62
+ .answer-card:hover{
63
+ transform: translateY(-1px);
64
+ box-shadow: 0 6px 18px rgba(15,23,42,0.06);
65
+ border-color: #c7d2fe;
66
+ }
67
+ .answer-card.selected{
68
+ border-color: #60a5fa;
69
+ box-shadow: 0 0 0 4px rgba(96,165,250,0.18);
70
+ }
71
+ .answer-card.correct{
72
+ border-color: #22c55e !important;
73
+ box-shadow: 0 0 0 4px rgba(34,197,94,0.15) !important;
74
+ background: #f0fdf4 !important;
75
+ }
76
+ .answer-card.wrong{
77
+ border-color: #ef4444 !important;
78
+ box-shadow: 0 0 0 4px rgba(239,68,68,0.12) !important;
79
+ background: #fef2f2 !important;
80
  }
81
+
82
+ /* Tabla de historial */
83
+ .small-muted { color:#6b7280; font-size:0.92rem; }
84
+ .badge { display:inline-block; padding: 2px 10px; border-radius:999px; border:1px solid #e5e7eb; background:#f8fafc; margin-right:6px; margin-bottom:6px; }
85
  </style>
86
  """, unsafe_allow_html=True)
87
 
88
  # =========================================================
89
+ # LOAD
90
  # =========================================================
91
  @st.cache_data
92
  def load_questions():
 
99
  return str(s).strip().lower()
100
 
101
  # =========================================================
102
+ # MERMAID + RENDER
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  # =========================================================
104
  def render_mermaid(mermaid_code):
105
  mermaid_code = html.escape(mermaid_code.strip())
106
  components.html(f"""
107
+ <div style="border:1px solid #e5e7eb;border-radius:12px;padding:14px;background:#ffffff;">
108
  <script type="module">
109
  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
110
  mermaid.initialize({{ startOnLoad: true }});
 
118
  for i, part in enumerate(parts):
119
  if i % 2 == 1:
120
  content = part.strip()
121
+ first_line = content.splitlines()[0].strip().lower() if content.splitlines() else ""
122
+ body = content[len(first_line):].lstrip("\n")
123
+ if first_line in ("python", "py"):
124
  st.code(body, language="python")
125
+ elif first_line == "mermaid":
126
  render_mermaid(body)
127
+ elif first_line in ("text","plaintext"):
128
+ st.code(body, language="plaintext")
129
  else:
130
  st.code(content, language="plaintext")
131
  else:
 
136
  m, s = divmod(int(sec), 60)
137
  return f"{m:02d}:{s:02d}"
138
 
139
+ # =========================================================
140
+ # STATS / TABLES
141
+ # =========================================================
142
+ def analyze_questions(questions):
143
+ df = pd.DataFrame(questions)
144
+ total = len(df)
145
+
146
+ df["nivel"] = df.get("nivel", "básico").map(norm)
147
+ df["tipo"] = df.get("tipo", "General").fillna("General").astype(str)
148
+ df["topic"] = df.get("topic", "General").fillna("General").astype(str)
149
+
150
+ by_level = df["nivel"].value_counts().reset_index()
151
+ by_level.columns = ["Dificultad", "Preguntas"]
152
+ by_level["%"] = (by_level["Preguntas"] / total * 100).round(1)
153
+
154
+ by_type = df["tipo"].value_counts().reset_index()
155
+ by_type.columns = ["Tipo", "Preguntas"]
156
+ by_type["%"] = (by_type["Preguntas"] / total * 100).round(1)
157
+
158
+ by_topic = df["topic"].value_counts().reset_index()
159
+ by_topic.columns = ["Temática (topic)", "Preguntas"]
160
+ by_topic["%"] = (by_topic["Preguntas"] / total * 100).round(1)
161
+
162
+ return total, by_level, by_type, by_topic
163
+
164
+ def perf_by_field(history, field="tipo"):
165
+ if not history:
166
+ return pd.DataFrame(columns=[field, "Respondidas", "Aciertos", "Tasa_%"])
167
+ df = pd.DataFrame(history)
168
+ if field not in df.columns:
169
+ return pd.DataFrame(columns=[field, "Respondidas", "Aciertos", "Tasa_%"])
170
+ g = df.groupby(field)["correct"].agg(Respondidas="count", Aciertos="sum").reset_index()
171
+ g["Tasa_%"] = (g["Aciertos"] / g["Respondidas"] * 100).round(1)
172
+ g = g.sort_values(["Tasa_%","Respondidas"], ascending=[True, False])
173
+ return g
174
+
175
+ # =========================================================
176
+ # ANSWER CARDS UI
177
+ # =========================================================
178
+ def pick_answer_cards(options, key_prefix="ans"):
179
+ """
180
+ options: list[str]
181
+ returns selected option index or None
182
+ """
183
+ if f"{key_prefix}_selected" not in st.session_state:
184
+ st.session_state[f"{key_prefix}_selected"] = None
185
+
186
+ cols = st.columns(1)
187
+ # 1 columna para que sea muy limpio; si quieres 2 columnas, lo hago luego.
188
+ for idx, opt in enumerate(options):
189
+ selected = (st.session_state[f"{key_prefix}_selected"] == idx)
190
+
191
+ # Render como botón pero con HTML card + botón transparente
192
+ card_class = "answer-card" + (" selected" if selected else "")
193
+ label = html.escape(opt)
194
+
195
+ clicked = st.button(f"{opt}", key=f"{key_prefix}_btn_{idx}", use_container_width=True)
196
+
197
+ # Si se hace click, guardamos selección
198
+ if clicked:
199
+ st.session_state[f"{key_prefix}_selected"] = idx
200
+
201
+ return st.session_state[f"{key_prefix}_selected"]
202
+
203
  # =========================================================
204
  # MAIN
205
  # =========================================================
 
209
  st.error("No se ha encontrado questions.json")
210
  return
211
 
212
+ total, by_level, by_type, by_topic = analyze_questions(questions)
213
 
214
+ # state init
215
  if "exam_active" not in st.session_state:
216
  st.session_state.exam_active = False
217
  st.session_state.exam_pool = []
 
220
  st.session_state.history = []
221
  st.session_state.start_time = None
222
  st.session_state.answered_current = False
223
+ st.session_state.last_result = None
224
+
225
+ # Header
226
+ st.title("Fundamentos de Programación y Computadores")
227
+ st.markdown("**Examen de prueba** para preparar el próximo examen oficial.")
228
+
229
+ st.markdown(
230
+ f"""
231
+ <span class="badge">📚 Total preguntas: <b>{total}</b></span>
232
+ <span class="badge">🎚️ Dificultades: <b>{len(by_level)}</b></span>
233
+ <span class="badge">🧩 Tipos: <b>{len(by_type)}</b></span>
234
+ <span class="badge">🏷️ Temáticas: <b>{len(by_topic)}</b></span>
235
+ """,
236
+ unsafe_allow_html=True
237
+ )
238
+
239
+ # Sidebar
240
+ with st.sidebar:
241
+ st.header("⚙️ Panel de control")
242
 
243
+ if not st.session_state.exam_active:
244
+ st.caption("📌 Resumen del banco")
245
+ st.dataframe(by_level, use_container_width=True, hide_index=True, height=180)
246
+ st.dataframe(by_type, use_container_width=True, hide_index=True, height=180)
247
+
248
+ with st.expander("🏷️ Temáticas (topic)"):
249
+ st.dataframe(by_topic.head(20), use_container_width=True, hide_index=True, height=320)
250
+
251
+ st.subheader("Configurar examen")
252
+ niveles = sorted(set(norm(q.get("nivel", "básico")) for q in questions))
253
+ sel = st.multiselect("Dificultad:", niveles, default=niveles)
254
+ mode = st.radio("Longitud:", ["Rápido (10)", "Estándar (25)", "Completo (Todas)"])
255
+
256
+ # preview count
257
+ filtered = [q for q in questions if norm(q.get("nivel", "básico")) in sel] if sel else []
258
+ limit = 10 if "10" in mode else 25 if "25" in mode else len(filtered)
259
+ st.caption(f"📄 Preguntas que saldrán: **{min(limit, len(filtered))}**")
260
+
261
+ if st.button("▶️ COMENZAR", use_container_width=True):
262
+ if not sel:
263
+ st.error("Selecciona al menos una dificultad.")
264
+ elif not filtered:
265
+ st.error("No hay preguntas con ese filtro.")
266
+ else:
267
+ random.shuffle(filtered)
268
+ st.session_state.exam_pool = filtered[:limit]
269
+ st.session_state.exam_active = True
270
+ st.session_state.start_time = time.time()
271
+ st.session_state.current_idx = 0
272
+ st.session_state.score = 0
273
+ st.session_state.history = []
274
+ st.session_state.answered_current = False
275
+ st.session_state.last_result = None
276
+ # reset selection key
277
+ st.session_state["card_selected"] = None
278
+ st.rerun()
279
+
280
+ else:
281
+ total_q = len(st.session_state.exam_pool)
282
+ current = st.session_state.current_idx
283
+
284
+ if st.session_state.start_time:
285
+ st.markdown(f"### ⏱️ {format_time(time.time() - st.session_state.start_time)}")
286
+
287
+ st.progress(min(current / max(total_q,1), 1.0))
288
+ st.metric("Pregunta", f"{current + 1} / {total_q}")
289
 
290
+ answered = current
291
+ if answered > 0:
292
+ acc = st.session_state.score / answered * 100
293
+ st.metric("Tasa de acierto", f"{acc:.1f}%")
294
+ else:
295
+ st.metric("Tasa de acierto", "—")
296
+
297
+ if st.session_state.history:
298
+ st.markdown("---")
299
+ st.subheader("📌 Rendimiento por tipo")
300
+ st.dataframe(perf_by_field(st.session_state.history, "tipo"),
301
+ use_container_width=True, hide_index=True, height=220)
302
+
303
+ st.markdown("---")
304
+ if st.button("⛔ Terminar examen", use_container_width=True):
305
+ st.session_state.current_idx = total_q
306
+ st.rerun()
307
+
308
+ # =========================
309
+ # PANTALLA INICIAL: consejos
310
+ # =========================
311
+ if not st.session_state.exam_active:
312
  st.markdown("""
313
  <div class="info-card">
314
+ <h3 style="margin:0;">✅ Cómo usar la aplicación</h3>
315
+ <ol style="margin-top:10px;">
316
+ <li><b>Elige la dificultad</b> y la <b>longitud</b> en el panel izquierdo.</li>
317
+ <li>Pulsa <b>▶️ COMENZAR</b>.</li>
318
+ <li>Selecciona una respuesta (tarjeta grande) y pulsa <b>Responder</b>.</li>
319
+ <li>Lee el feedback: si está bien/mal, la correcta y el comentario.</li>
320
+ <li>Pulsa <b>Siguiente</b> para avanzar.</li>
321
  </ol>
322
+ <h3 style="margin:18px 0 0 0;">💡 Consejos</h3>
323
+ <ul style="margin-top:10px;">
324
+ <li>En código: atención a <b>indentación</b>, condiciones y tipos.</li>
325
+ <li>En diagramas: sigue decisiones paso a paso.</li>
326
+ <li>Tu progreso queda guardado durante la sesión (historial abajo).</li>
 
327
  </ul>
328
  </div>
329
  """, unsafe_allow_html=True)
330
 
331
+ st.markdown("### 📊 Distribución del banco (exacta)")
332
+ c1, c2, c3 = st.columns(3)
333
  with c1:
334
+ st.caption("Dificultad")
335
+ st.dataframe(by_level, use_container_width=True, hide_index=True, height=220)
 
 
 
336
  with c2:
337
+ st.caption("Tipo")
338
+ st.dataframe(by_type, use_container_width=True, hide_index=True, height=220)
339
+ with c3:
340
+ st.caption("Temáticas (top 12)")
341
+ st.dataframe(by_topic.head(12), use_container_width=True, hide_index=True, height=220)
 
 
 
 
342
 
343
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
 
345
+ # =========================
346
+ # EXAMEN (con feedback y progreso)
347
+ # =========================
348
  if st.session_state.exam_active and st.session_state.current_idx < len(st.session_state.exam_pool):
349
  q = st.session_state.exam_pool[st.session_state.current_idx]
350
+
351
+ st.subheader(f"📝 Pregunta {st.session_state.current_idx + 1}")
352
  render_content(q["question"])
353
 
354
+ # Opciones barajadas (se mantienen)
355
+ if f"opts_{st.session_state.current_idx}" not in st.session_state:
356
+ opts = list(enumerate(q["options"]))
357
+ random.shuffle(opts)
358
+ st.session_state[f"opts_{st.session_state.current_idx}"] = opts
359
+ current_opts = st.session_state[f"opts_{st.session_state.current_idx}"]
360
+ labels = [o[1] for o in current_opts]
361
+
362
+ # Selection
363
+ if "card_selected" not in st.session_state:
364
+ st.session_state["card_selected"] = None
365
+
366
+ # Tarjetas clicables (usamos botones grandes)
367
+ st.markdown("### ✅ Respuestas (clic grande)")
368
+ for idx, label in enumerate(labels):
369
+ is_sel = (st.session_state["card_selected"] == idx)
370
+ # estilo visual usando markdown + estado, pero click con button
371
+ btn_label = ("✅ " if is_sel else "⬜ ") + label
372
+ if st.button(btn_label, key=f"card_{st.session_state.current_idx}_{idx}", use_container_width=True,
373
+ disabled=st.session_state.answered_current):
374
+ st.session_state["card_selected"] = idx
375
+
376
+ # Botón responder
377
+ st.write("")
378
+ if st.button("📩 Responder", use_container_width=True, disabled=st.session_state.answered_current):
379
+ sel_idx = st.session_state["card_selected"]
380
+ if sel_idx is None:
381
+ st.warning("Selecciona una opción antes de responder.")
382
+ else:
383
+ # map a índice original
384
+ orig_idx = current_opts[sel_idx][0]
385
+ correct_idx = q["answer_index"]
386
+ is_correct = (orig_idx == correct_idx)
387
+ correct_txt = q["options"][correct_idx]
388
+ user_txt = current_opts[sel_idx][1]
389
+
390
+ st.session_state.last_result = {
391
+ "ok": is_correct,
392
+ "corr": correct_txt,
393
+ "user": user_txt,
394
+ "expl": q.get("explanation", "—"),
395
+ "tipo": q.get("tipo", "General"),
396
+ "topic": q.get("topic", "General"),
397
+ "nivel": q.get("nivel", "básico"),
398
+ }
399
+
400
+ # Guardar progreso (historial)
401
+ if not st.session_state.answered_current:
402
+ if is_correct:
403
+ st.session_state.score += 1
404
+ st.session_state.history.append({
405
+ "n": st.session_state.current_idx + 1,
406
+ "nivel": q.get("nivel", "básico"),
407
+ "tipo": q.get("tipo", "General"),
408
+ "topic": q.get("topic", "General"),
409
+ "correct": is_correct,
410
+ "respuesta_alumno": user_txt,
411
+ "respuesta_correcta": correct_txt,
412
+ })
413
+ st.session_state.answered_current = True
414
+ st.rerun()
415
+
416
+ # FEEDBACK (si ya respondió)
417
+ if st.session_state.answered_current and st.session_state.last_result:
418
+ res = st.session_state.last_result
419
+
420
+ st.markdown("---")
421
+ if res["ok"]:
422
+ st.success("✅ Correcto")
423
+ else:
424
+ st.error("❌ Incorrecto")
425
+
426
+ st.markdown(f"**Tu respuesta:** {res['user']}")
427
+ st.markdown(f"**Respuesta correcta:** {res['corr']}")
428
+ st.markdown(f"**Comentario / explicación:** {res['expl']}")
429
+
430
+ # Botón siguiente
431
+ st.write("")
432
+ if st.button("➡️ Siguiente", type="primary", use_container_width=True):
433
  st.session_state.current_idx += 1
434
+ st.session_state.answered_current = False
435
+ st.session_state.last_result = None
436
+ st.session_state["card_selected"] = None
437
+ st.rerun()
438
+
439
+ # HISTORIAL ABAJO
440
+ st.markdown("---")
441
+ st.subheader("📌 Progreso del alumno (historial)")
442
+ if st.session_state.history:
443
+ dfh = pd.DataFrame(st.session_state.history)
444
+ # más legible: Sí/No
445
+ dfh["resultado"] = dfh["correct"].map(lambda x: "✅" if x else "❌")
446
+ show_cols = ["n", "resultado", "nivel", "tipo", "topic", "respuesta_alumno", "respuesta_correcta"]
447
+ show_cols = [c for c in show_cols if c in dfh.columns]
448
+ st.dataframe(dfh[show_cols], use_container_width=True, hide_index=True, height=320)
449
+ st.caption("Esto queda guardado durante la sesión del navegador (progreso del alumno).")
450
+ else:
451
+ st.caption("Aún no hay respuestas registradas.")
452
 
453
+ # Rendimiento por temática/tipo (aclaración)
454
+ st.markdown("### 📊 Rendimiento por tipo y temática")
455
+ c1, c2 = st.columns(2)
456
+ with c1:
457
+ st.caption("Por tipo (campo `tipo` del JSON)")
458
+ st.dataframe(perf_by_field(st.session_state.history, "tipo"), use_container_width=True, hide_index=True, height=240)
459
+ with c2:
460
+ st.caption("Por temática (campo `topic` del JSON)")
461
+ st.dataframe(perf_by_field(st.session_state.history, "topic"), use_container_width=True, hide_index=True, height=240)
462
+
463
+ # =========================
464
  # FINAL
465
+ # =========================
466
  elif st.session_state.exam_active:
467
  st.balloons()
468
+ st.header("✅ Resultados")
469
+
470
  total_q = len(st.session_state.exam_pool)
471
  score = st.session_state.score
472
+ perc = (score / total_q * 100) if total_q else 0
473
+ elapsed = format_time(time.time() - st.session_state.start_time) if st.session_state.start_time else "—"
474
+
475
+ c1, c2, c3 = st.columns(3)
476
+ c1.metric("Nota", f"{score} / {total_q}")
477
+ c2.metric("Porcentaje", f"{perc:.1f}%")
478
+ c3.metric("Tiempo", elapsed)
479
+
480
+ st.markdown("---")
481
+ st.subheader("📌 Historial completo")
482
+ if st.session_state.history:
483
+ dfh = pd.DataFrame(st.session_state.history)
484
+ dfh["resultado"] = dfh["correct"].map(lambda x: "✅" if x else "❌")
485
+ show_cols = ["n", "resultado", "nivel", "tipo", "topic", "respuesta_alumno", "respuesta_correcta"]
486
+ show_cols = [c for c in show_cols if c in dfh.columns]
487
+ st.dataframe(dfh[show_cols], use_container_width=True, hide_index=True, height=380)
488
+
489
+ st.subheader("📊 Rendimiento por tipo")
490
+ st.dataframe(perf_by_field(st.session_state.history, "tipo"),
491
+ use_container_width=True, hide_index=True, height=260)
492
+
493
+ st.subheader("📊 Rendimiento por temática (topic)")
494
+ st.dataframe(perf_by_field(st.session_state.history, "topic"),
495
+ use_container_width=True, hide_index=True, height=260)
496
+ else:
497
+ st.caption("No hay historial.")
498
 
499
+ st.markdown("---")
500
+ if st.button("🏠 Volver al inicio", use_container_width=True):
501
  st.session_state.exam_active = False
502
+ st.rerun()
503
 
504
  if __name__ == "__main__":
505
  main()
506
+