Spaces:
Running

pythontest / app.py
JACINTO VELASCO
Update app.py
29656d5 verified
Raw History Blame
5.19 kB
import streamlit as st
import json
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import pandas as pd
import matplotlib.pyplot as plt
from fpdf import FPDF
import tempfile
# Cargar preguntas desde archivo JSON
@st.cache_data
def load_questions():
with open("questions.json", "r", encoding="utf-8") as f:
return json.load(f)
def render_code_snippet(code):
formatter = HtmlFormatter(style="monokai", full=False, noclasses=True)
highlighted_code = highlight(code, PythonLexer(), formatter)
st.markdown(f"<div style='background-color:#272822;padding:10px;border-radius:8px;overflow-x:auto'>{highlighted_code}</div>", unsafe_allow_html=True)
def show_question(q, index):
st.subheader(f"Pregunta {index+1}:")
if "```python" in q["question"]:
parts = q["question"].split("```python")
st.markdown(parts[0])
render_code_snippet(parts[1].strip("` "))
else:
st.markdown(q["question"])
user_answer = st.radio("Selecciona una opción:", q['options'], key=f"q_{index}")
if st.button("Responder", key=f"submit_{index}"):
st.session_state.answers[index] = user_answer
is_correct = user_answer == q['options'][q['answer_index']]
if is_correct:
st.session_state.correct_count += 1
st.session_state.history.append({
"tipo": q["tipo"],
"correcto": is_correct,
"pregunta": q["question"].split("```python")[0].strip(),
"respuesta": user_answer,
"correcta": q['options'][q['answer_index']]
})
st.markdown("✅ Correcto" if is_correct else "❌ Incorrecto")
st.markdown(f"_Explicación:_ {q['explanation']}")
df_temp = pd.DataFrame(st.session_state.history)
if not df_temp.empty:
df_temp["incorrecto"] = ~df_temp["correcto"]
resumen["total"] = resumen["correcto"] + resumen["incorrecto"]
resumen["% acierto"] = (resumen["correcto"] / resumen["total"] * 100).round(1)
resumen["% error"] = (resumen["incorrecto"] / resumen["total"] * 100).round(1)
st.markdown("### Estadísticas parciales")
st.markdown("#### Resumen por tipo (pequeño)")
st.dataframe(resumen if st.button("Siguiente", key=f"next_{index}"):
st.session_state.current += 1
st.rerun()
def mostrar_estadisticas(history):
df = pd.DataFrame(history)
df["incorrecto"] = ~df["correcto"]
resumen = df.groupby("tipo")["correcto", "incorrecto"].sum()
resumen["total"] = resumen["correcto"] + resumen["incorrecto"]
resumen["% acierto"] = (resumen["correcto"] / resumen["total"] * 100).round(1)
resumen["% error"] = (resumen["incorrecto"] / resumen["total"] * 100).round(1)
st.markdown("### 📊 Estadísticas por tipo de pregunta")
st.dataframe(resumen[["correcto", "incorrecto", "% acierto", "% error"]])
fig, ax = plt.subplots()
resumen[["% acierto", "% error"]].plot(kind="bar", stacked=False, ax=ax)
plt.ylabel("Porcentaje")
plt.title("Porcentaje de aciertos y errores por tipo")
st.pyplot(fig)
return df
def exportar_pdf(df):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Resumen del test", ln=1, align='C')
for i, row in df.iterrows():
texto = f"{i+1}. {row['pregunta']}\nRespuesta: {row['respuesta']} | Correcta: {row['correcta']} | {'✅' if row['correcto'] else '❌'}"
pdf.multi_cell(0, 10, txt=texto)
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
pdf.output(tmp.name)
with open(tmp.name, "rb") as file:
st.download_button(
label="📄 Descargar resumen en PDF",
data=file,
file_name="resumen_test.pdf",
mime="application/pdf"
)
def main():
st.set_page_config(page_title="Test Python + TIC", layout="wide")
st.title("🧠 Test Interactivo de Python y TIC")
questions = load_questions()
if 'answers' not in st.session_state:
st.session_state.answers = {}
st.session_state.correct_count = 0
st.session_state.current = 0
st.session_state.history = []
with st.sidebar:
st.markdown("## Progreso")
st.metric("Respuestas correctas", st.session_state.correct_count)
st.metric("Respondidas", len(st.session_state.answers))
st.markdown("---")
st.progress(len(st.session_state.answers) / len(questions))
if st.session_state.current < len(questions):
q = questions[st.session_state.current]
show_question(q, st.session_state.current)
else:
st.success(f"Test finalizado. Obtuviste {st.session_state.correct_count} de {len(questions)} respuestas correctas.")
df = mostrar_estadisticas(st.session_state.history)
exportar_pdf(df)
if st.button("Reiniciar"):
for key in ["answers", "correct_count", "current", "history"]:
del st.session_state[key]
st.rerun()
if __name__ == "__main__":
main()