JACINTO VELASCO commited on
Commit
18c4048
·
verified ·
1 Parent(s): 674a729

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -50
app.py CHANGED
@@ -1,53 +1,72 @@
1
  import streamlit as st
2
  import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- # Cargar las preguntas desde un archivo JSON
5
- with open('questions.json', 'r', encoding='utf-8') as f:
6
- questions = json.load(f)
7
-
8
- # Inicializar estado si no existe
9
- if 'current_question' not in st.session_state:
10
- st.session_state.current_question = 0
11
- st.session_state.score = 0
12
- st.session_state.results = [] # Lista booleana de aciertos por pregunta
13
-
14
- # Si aún hay preguntas por responder
15
- if st.session_state.current_question < len(questions):
16
- q_index = st.session_state.current_question
17
- q = questions[q_index]
18
-
19
- # Mostrar enunciado de la pregunta
20
- st.markdown(f"**Pregunta {q_index + 1}:** {q['question']}")
21
- # Mostrar opciones como botones de radio
22
- choice = st.radio("Seleccione una opción:", q['options'], key=str(q_index))
23
- # Botón para enviar respuesta
24
- if st.button("Responder"):
25
- # Verificar respuesta seleccionada
26
- if q['options'].index(choice) == q['answer_index']:
27
- st.session_state.score += 1
28
- st.session_state.results.append(True)
29
- else:
30
- st.session_state.results.append(False)
31
- # Avanzar a la siguiente pregunta
32
- st.session_state.current_question += 1
33
- st.experimental_rerun()
34
- else:
35
- # Quiz finalizado: mostrar puntuación y resumen de resultados
36
- total = len(questions)
37
- score = st.session_state.score
38
- st.write(f"**Quiz finalizado. Puntuación: {score} de {total}**")
39
- st.write("---")
40
- # Listar resultado de cada pregunta con símbolo de correcto/incorrecto
41
- for idx, correcto in enumerate(st.session_state.results):
42
- pregunta = questions[idx]
43
- if correcto:
44
- st.write(f"Pregunta {idx+1}: **Correcta** ✅")
45
- else:
46
- respuesta_correcta = pregunta['options'][pregunta['answer_index']]
47
- st.write(f"Pregunta {idx+1}: **Incorrecta** ❌ (Respuesta correcta: **{respuesta_correcta}**)")
48
- # Botón para reiniciar el cuestionario
49
- if st.button("Reiniciar quiz"):
50
- st.session_state.current_question = 0
51
- st.session_state.score = 0
52
- st.session_state.results = []
53
- st.experimental_rerun()
 
1
  import streamlit as st
2
  import json
3
+ from pygments import highlight
4
+ from pygments.lexers import PythonLexer
5
+ from pygments.formatters import HtmlFormatter
6
+
7
+ # Cargar preguntas desde archivo JSON
8
+ @st.cache_data
9
+ def load_questions():
10
+ with open("questions.json", "r", encoding="utf-8") as f:
11
+ return json.load(f)
12
+
13
+ def render_code_snippet(code):
14
+ formatter = HtmlFormatter(style="monokai", full=False, noclasses=True)
15
+ highlighted_code = highlight(code, PythonLexer(), formatter)
16
+ st.markdown(f"<div style='background-color:#272822;padding:10px;border-radius:8px'>{highlighted_code}</div>", unsafe_allow_html=True)
17
+
18
+ def show_question(q, index):
19
+ st.subheader(f"Pregunta {index+1}:")
20
+ if "```python" in q["question"]:
21
+ question_text = q["question"].split("```python")
22
+ st.markdown(question_text[0])
23
+ render_code_snippet(question_text[1].strip("`"))
24
+ else:
25
+ st.markdown(q["question"])
26
+ user_answer = st.radio("Selecciona una opción:", q['options'], key=index)
27
+ return user_answer
28
+
29
+ def main():
30
+ st.set_page_config(page_title="Test Python + TIC", layout="wide")
31
+ st.title("🧠 Test Interactivo de Python y TIC")
32
+ questions = load_questions()
33
+
34
+ if 'answers' not in st.session_state:
35
+ st.session_state.answers = {}
36
+ st.session_state.correct_count = 0
37
+ st.session_state.current = 0
38
+
39
+ with st.sidebar:
40
+ st.markdown("## Progreso")
41
+ st.metric("Respuestas correctas", st.session_state.correct_count)
42
+ st.metric("Total respondidas", len(st.session_state.answers))
43
+ st.markdown("---")
44
+ st.progress(len(st.session_state.answers) / len(questions))
45
+
46
+ if st.session_state.current < len(questions):
47
+ q = questions[st.session_state.current]
48
+ user_answer = show_question(q, st.session_state.current)
49
+ if st.button("Responder", key=f"submit_{st.session_state.current}"):
50
+ st.session_state.answers[st.session_state.current] = user_answer
51
+ if user_answer == q['options'][q['answer_index']]:
52
+ st.session_state.correct_count += 1
53
+ st.session_state.current += 1
54
+ st.rerun()
55
+ else:
56
+ st.success(f"Test finalizado. Obtuviste {st.session_state.correct_count} de {len(questions)} respuestas correctas.")
57
+ for i, q in enumerate(questions):
58
+ st.markdown(f"**Pregunta {i+1}:** {q['question']}")
59
+ st.markdown(f"Tu respuesta: {st.session_state.answers.get(i)}")
60
+ st.markdown(f"Respuesta correcta: {q['options'][q['answer_index']]}")
61
+ st.markdown(f"_Explicación:_ {q['explanation']}")
62
+ correct = st.session_state.answers.get(i) == q['options'][q['answer_index']]
63
+ st.markdown("✅ Correcto" if correct else "❌ Incorrecto")
64
+ st.markdown("---")
65
+ if st.button("Reiniciar"):
66
+ for key in ["answers", "correct_count", "current"]:
67
+ del st.session_state[key]
68
+ st.rerun()
69
+
70
+ if __name__ == "__main__":
71
+ main()
72