Spaces:
Sleeping
Sleeping
Add PPT-guided teaching flow and animated diagram-to-code steps
Browse files- .gitattributes +2 -0
- assets/ppt_100.png +0 -0
- assets/ppt_101.png +0 -0
- assets/ppt_102.png +0 -0
- assets/ppt_105.png +0 -0
- assets/ppt_106.png +0 -0
- assets/ppt_46.png +0 -0
- assets/ppt_48.png +3 -0
- assets/ppt_50.png +3 -0
- assets/ppt_51.png +0 -0
- assets/ppt_60.png +0 -0
- assets/ppt_64.png +0 -0
- assets/ppt_89.png +0 -0
- assets/ppt_90.png +0 -0
- assets/ppt_91.png +0 -0
- assets/ppt_93.png +0 -0
- assets/ppt_95.png +0 -0
- assets/ppt_97.png +0 -0
- pages/3_Clase_guiada.py +84 -113
- pages/4_Diagramas_a_codigo.py +100 -67
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
assets/ppt_48.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/ppt_50.png filter=lfs diff=lfs merge=lfs -text
|
assets/ppt_100.png
ADDED
|
assets/ppt_101.png
ADDED
|
assets/ppt_102.png
ADDED
|
assets/ppt_105.png
ADDED
|
assets/ppt_106.png
ADDED
|
assets/ppt_46.png
ADDED
|
assets/ppt_48.png
ADDED
|
Git LFS Details
|
assets/ppt_50.png
ADDED
|
Git LFS Details
|
assets/ppt_51.png
ADDED
|
assets/ppt_60.png
ADDED
|
assets/ppt_64.png
ADDED
|
assets/ppt_89.png
ADDED
|
assets/ppt_90.png
ADDED
|
assets/ppt_91.png
ADDED
|
assets/ppt_93.png
ADDED
|
assets/ppt_95.png
ADDED
|
assets/ppt_97.png
ADDED
|
pages/3_Clase_guiada.py
CHANGED
|
@@ -1,127 +1,98 @@
|
|
| 1 |
import math
|
|
|
|
| 2 |
|
| 3 |
import streamlit as st
|
| 4 |
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
st.markdown(
|
| 9 |
-
"""
|
| 10 |
-
<style>
|
| 11 |
-
.stApp { background: linear-gradient(145deg, #f8fafc 0%, #eef6ff 55%, #fffbea 100%); }
|
| 12 |
-
.block-container { max-width: 1180px; padding-top: 2.2rem; }
|
| 13 |
-
.hero { background:#101820; color:white; padding:2rem 2.2rem; border-radius:22px;
|
| 14 |
-
border-left:9px solid #009fe3; margin-bottom:1.5rem; }
|
| 15 |
-
.hero h1 { margin:0; color:white; font-size:2.3rem; }
|
| 16 |
-
.hero p { margin:.55rem 0 0; color:#d7e9f3; font-size:1.05rem; }
|
| 17 |
-
.panel { background:rgba(255,255,255,.94); padding:1.25rem; border-radius:16px;
|
| 18 |
-
border:1px solid #dbe5ed; min-height:285px; }
|
| 19 |
-
.explain { background:#e8f6fc; border-left:5px solid #009fe3; border-radius:10px;
|
| 20 |
-
padding:1rem 1.1rem; line-height:1.6; }
|
| 21 |
-
.stCodeBlock { border-radius:12px; }
|
| 22 |
-
div.stButton > button { border-radius:10px; font-weight:750; }
|
| 23 |
-
</style>
|
| 24 |
-
<div class="hero">
|
| 25 |
-
<div style="float:right;font-size:28px;font-weight:800">UA<span style="color:#009fe3">X</span></div>
|
| 26 |
-
<h1>Clase guiada de Python</h1>
|
| 27 |
-
<p>Introduce datos, ejecuta la lógica y entiende por qué aparece cada resultado.</p>
|
| 28 |
-
</div>
|
| 29 |
-
""",
|
| 30 |
-
unsafe_allow_html=True,
|
| 31 |
-
)
|
| 32 |
|
| 33 |
-
st.
|
| 34 |
|
| 35 |
-
|
| 36 |
-
"
|
| 37 |
-
|
| 38 |
-
"
|
| 39 |
-
"
|
| 40 |
-
"
|
| 41 |
-
"
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
else:
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
st.code(""
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
st.code(
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
]
|
| 75 |
-
for producto in productos:
|
| 76 |
-
print(producto["nombre"], producto["stock"])""", language="python", line_numbers=True)
|
| 77 |
-
else:
|
| 78 |
-
st.code("""def area_cilindro(radio, altura):
|
| 79 |
-
area_base = math.pi * radio**2
|
| 80 |
-
area_lateral = 2 * math.pi * radio * altura
|
| 81 |
-
return 2 * area_base + area_lateral""", language="python", line_numbers=True)
|
| 82 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
| 83 |
-
|
| 84 |
-
with right:
|
| 85 |
-
st.markdown('<div class="panel">', unsafe_allow_html=True)
|
| 86 |
-
st.subheader("Pruébalo")
|
| 87 |
-
|
| 88 |
-
if activity.startswith("1"):
|
| 89 |
-
precio = st.number_input("Precio unitario (€)", min_value=0.0, value=12.50, step=0.50)
|
| 90 |
-
unidades = st.number_input("Unidades", min_value=0, value=4, step=1)
|
| 91 |
-
importe = precio * unidades
|
| 92 |
-
st.success(f"Importe: {importe:.2f} €")
|
| 93 |
-
explanation = f"Python multiplica {precio:.2f} por {unidades}. El resultado se guarda en `importe`, por eso se muestra {importe:.2f} € con dos decimales."
|
| 94 |
-
elif activity.startswith("2"):
|
| 95 |
-
nota = st.number_input("Nota", min_value=0.0, max_value=10.0, value=7.5, step=0.5)
|
| 96 |
-
resultado = "Sobresaliente" if nota >= 9 else "Aprobado" if nota >= 5 else "Suspenso"
|
| 97 |
-
st.success(resultado)
|
| 98 |
-
explanation = f"La nota es {nota:g}. " + ("Cumple `nota >= 9`." if nota >= 9 else "No alcanza 9, pero sí cumple `nota >= 5`." if nota >= 5 else "No cumple `nota >= 5`.") + f" Por ello Python selecciona la rama que devuelve «{resultado}»."
|
| 99 |
-
elif activity.startswith("3"):
|
| 100 |
-
n = st.number_input("Número entero no negativo", min_value=0, max_value=12, value=5, step=1)
|
| 101 |
-
factorial = 1
|
| 102 |
-
for i in range(1, n + 1):
|
| 103 |
-
factorial *= i
|
| 104 |
-
st.success(f"{n}! = {factorial}")
|
| 105 |
-
explanation = f"El bucle recorre los enteros de 1 a {n}. El acumulador empieza en 1 y se multiplica en cada vuelta; el producto final es {factorial}."
|
| 106 |
-
elif activity.startswith("4"):
|
| 107 |
-
stock_teclado = st.number_input("Stock de teclados", min_value=0, value=12, step=1)
|
| 108 |
-
stock_raton = st.number_input("Stock de ratones", min_value=0, value=3, step=1)
|
| 109 |
-
productos = [{"Producto": "Teclado", "Stock": stock_teclado}, {"Producto": "Ratón", "Stock": stock_raton}]
|
| 110 |
-
st.dataframe(productos, hide_index=True, width="stretch")
|
| 111 |
-
bajos = [p["Producto"] for p in productos if p["Stock"] < 5]
|
| 112 |
-
aviso = ", ".join(bajos) if bajos else "ninguno"
|
| 113 |
-
st.info(f"Productos con reposición necesaria: {aviso}.")
|
| 114 |
-
explanation = "La lista guarda diccionarios en memoria. El recorrido comprueba cada `Stock`; solo se añaden al aviso los productos con menos de cinco unidades."
|
| 115 |
-
else:
|
| 116 |
-
radio = st.number_input("Radio", min_value=0.1, value=2.5, step=0.1)
|
| 117 |
-
altura = st.number_input("Altura", min_value=0.1, value=8.0, step=0.1)
|
| 118 |
-
area = 2 * math.pi * radio**2 + 2 * math.pi * radio * altura
|
| 119 |
-
st.success(f"Área total: {area:.2f} u²")
|
| 120 |
-
explanation = f"La función calcula dos bases y la superficie lateral. Con radio {radio:g} y altura {altura:g}, la fórmula produce {area:.2f} unidades cuadradas."
|
| 121 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
| 122 |
-
|
| 123 |
-
st.markdown("### Después de ejecutar")
|
| 124 |
-
st.markdown(f'<div class="explain">{explanation}</div>', unsafe_allow_html=True)
|
| 125 |
|
| 126 |
st.divider()
|
| 127 |
if st.button("← Volver al inicio"):
|
|
|
|
| 1 |
import math
|
| 2 |
+
from pathlib import Path
|
| 3 |
|
| 4 |
import streamlit as st
|
| 5 |
|
| 6 |
|
| 7 |
+
APP_DIR = Path(__file__).resolve().parent.parent
|
| 8 |
+
ASSETS = APP_DIR / "assets"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
st.set_page_config(page_title="Clase guiada · Python", page_icon="🐍", layout="wide")
|
| 11 |
|
| 12 |
+
LESSONS = {
|
| 13 |
+
"1 · Variables y tipos": {
|
| 14 |
+
"slide": 89,
|
| 15 |
+
"theory": "Una variable almacena un valor. Python identifica automáticamente si ese valor es un entero, decimal, texto o booleano.",
|
| 16 |
+
"code": """x = 10\nnombre = \"Carlos\"\nedad = 25\naltura = 1.75\nes_estudiante = True\n\nprint(type(x).__name__)\nprint(type(nombre).__name__)""",
|
| 17 |
+
"activity": "Cambia los valores de nombre, edad y altura. Antes de ejecutar, predice qué tipos mostrará Python.",
|
| 18 |
+
"run": lambda: ("int, str", "10 es un entero y Carlos es texto. Python asigna los tipos `int` y `str` automáticamente."),
|
| 19 |
+
},
|
| 20 |
+
"2 · Listas": {
|
| 21 |
+
"slide": 91,
|
| 22 |
+
"theory": "Una lista conserva varios valores en orden. Sus posiciones comienzan en 0 y puede modificarse con asignación, append, insert o remove.",
|
| 23 |
+
"code": """frutas = ['manzana', 'banana', 'cereza']\nprint(frutas[0])\nfrutas[1] = 'naranja'\nfrutas.append('kiwi')\nfrutas.insert(1, 'mango')\nfrutas.remove('cereza')\n\nfor fruta in frutas:\n print(fruta)""",
|
| 24 |
+
"activity": "Escribe una fruta nueva y predice la lista final antes de revelar la solución.",
|
| 25 |
+
"run": lambda: ("manzana\nmango\nnaranja\nkiwi", "El índice 0 muestra manzana. Después se reemplaza banana, se añaden kiwi y mango y se elimina cereza. El for recorre la lista resultante."),
|
| 26 |
+
},
|
| 27 |
+
"3 · Diccionarios": {
|
| 28 |
+
"slide": 93,
|
| 29 |
+
"theory": "Un diccionario almacena pares clave–valor. Se consulta o modifica un dato usando su clave entre corchetes.",
|
| 30 |
+
"code": """persona = {'nombre': 'Juan', 'edad': 30, 'ciudad': 'Madrid'}\nprint(persona['nombre'])\npersona['edad'] = 31\npersona['profesion'] = 'Ingeniero'\nprint(persona)""",
|
| 31 |
+
"activity": "Indica qué clave usarías para consultar la edad y qué líneas modifican el diccionario.",
|
| 32 |
+
"run": lambda: ("Juan\n{'nombre': 'Juan', 'edad': 31, 'ciudad': 'Madrid', 'profesion': 'Ingeniero'}", "La clave nombre devuelve Juan. La edad se sustituye por 31 y profesión se incorpora como una nueva clave."),
|
| 33 |
+
},
|
| 34 |
+
"4 · Condicionales": {
|
| 35 |
+
"slide": 100,
|
| 36 |
+
"theory": "if evalúa una condición; elif se prueba si la anterior fue falsa; else cubre el resto de situaciones. La sangría determina el bloque ejecutado.",
|
| 37 |
+
"code": """nota = 85\nif nota >= 90:\n print('Sobresaliente')\nelif nota >= 70:\n print('Aprobado')\nelse:\n print('Reprobado')""",
|
| 38 |
+
"activity": "Cambia la nota. Decide qué condición será la primera verdadera y predice el mensaje.",
|
| 39 |
+
"run": lambda: ("Aprobado", "85 no alcanza 90, por eso se descarta la primera rama. Sí cumple `nota >= 70`; se imprime Aprobado y no se evalúa else."),
|
| 40 |
+
},
|
| 41 |
+
"5 · Bucles for y while": {
|
| 42 |
+
"slide": 101,
|
| 43 |
+
"theory": "for recorre una secuencia conocida. while repite un bloque mientras una condición sea verdadera y necesita que algún valor cambie para poder terminar.",
|
| 44 |
+
"code": """numeros = [1, 2, 3, 4, 5]\nfor num in numeros:\n print(num)\n\nx = 0\nwhile x < 3:\n print(f'vuelta {x}')\n x += 1""",
|
| 45 |
+
"activity": "Cuenta cuántas líneas se imprimirán y localiza qué instrucción evita el bucle infinito.",
|
| 46 |
+
"run": lambda: ("1\n2\n3\n4\n5\nvuelta 0\nvuelta 1\nvuelta 2", "El for realiza una vuelta por cada elemento. En while, `x += 1` cambia x; al alcanzar 3, `x < 3` es falso y el bucle termina."),
|
| 47 |
+
},
|
| 48 |
+
"6 · Clases y objetos": {
|
| 49 |
+
"slide": 97,
|
| 50 |
+
"theory": "Una clase es una plantilla. Un objeto guarda atributos y puede ejecutar métodos que modifican su propio estado mediante self.",
|
| 51 |
+
"code": """class Coche:\n def __init__(self, marca, velocidad):\n self.marca = marca\n self.velocidad = velocidad\n\n def acelerar(self):\n self.velocidad += 10\n print(f'El coche {self.marca} ha acelerado a {self.velocidad} km/h.')\n\ncoche1 = Coche('Toyota', 100)\ncoche1.acelerar()""",
|
| 52 |
+
"activity": "Identifica los atributos iniciales del coche y anticipa el valor de velocidad después de llamar a acelerar.",
|
| 53 |
+
"run": lambda: ("El coche Toyota ha acelerado a 110 km/h.", "El constructor asigna Toyota y 100. `self.velocidad += 10` actualiza la velocidad del mismo objeto a 110."),
|
| 54 |
+
},
|
| 55 |
+
}
|
| 56 |
|
| 57 |
+
st.markdown("""<style>
|
| 58 |
+
.stApp{background:linear-gradient(145deg,#f7fafc,#eaf5ff)} .block-container{max-width:1180px;padding-top:2rem}
|
| 59 |
+
.hero{background:#101820;border-left:9px solid #009fe3;border-radius:20px;padding:1.8rem 2rem;color:white}.hero h1{margin:0;color:white}.hero p{color:#dbeaf2;margin:.5rem 0 0}
|
| 60 |
+
.card{background:white;border:1px solid #d8e3eb;border-radius:16px;padding:1.3rem}.explain{background:#e8f6fc;border-left:5px solid #009fe3;border-radius:10px;padding:1rem;line-height:1.65}
|
| 61 |
+
</style><div class='hero'><div style='float:right;font-size:27px;font-weight:800'>UA<span style='color:#009fe3'>X</span></div><h1>Clase guiada de Python</h1><p>Teoría original → actividad del alumno → solución del profesor → explicación del resultado.</p></div>""", unsafe_allow_html=True)
|
| 62 |
|
| 63 |
+
lesson_name = st.selectbox("Selecciona el bloque de clase", list(LESSONS))
|
| 64 |
+
lesson = LESSONS[lesson_name]
|
| 65 |
+
phase = st.radio("Control de la sesión", ["1 · Teoría", "2 · Actividad", "3 · Solución explicada"], horizontal=True)
|
| 66 |
|
| 67 |
+
if phase == "1 · Teoría":
|
| 68 |
+
st.subheader("Teoría de clase")
|
| 69 |
+
st.image(str(ASSETS / f"ppt_{lesson['slide']}.png"), use_container_width=True)
|
| 70 |
+
st.info(lesson["theory"])
|
| 71 |
+
st.caption("El profesor presenta la diapositiva y plantea preguntas antes de mostrar el código.")
|
| 72 |
+
elif phase == "2 · Actividad":
|
| 73 |
+
left, right = st.columns(2, gap="large")
|
| 74 |
+
with left:
|
| 75 |
+
st.markdown("<div class='card'><h3>Enunciado para el alumno</h3>", unsafe_allow_html=True)
|
| 76 |
+
st.write(lesson["activity"])
|
| 77 |
+
st.text_area("Escribe tu razonamiento o la salida que esperas", height=210, key=f"answer_{lesson_name}")
|
| 78 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 79 |
+
with right:
|
| 80 |
+
st.markdown("<div class='card'><h3>Pista visual</h3>", unsafe_allow_html=True)
|
| 81 |
+
st.image(str(ASSETS / f"ppt_{lesson['slide']}.png"), use_container_width=True)
|
| 82 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 83 |
+
st.warning("El profesor mantiene el código oculto mientras se debate la respuesta.")
|
| 84 |
else:
|
| 85 |
+
left, right = st.columns([1.15, .85], gap="large")
|
| 86 |
+
with left:
|
| 87 |
+
st.markdown("<div class='card'><h3>Solución de clase</h3>", unsafe_allow_html=True)
|
| 88 |
+
st.code(lesson["code"], language="python", line_numbers=True)
|
| 89 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 90 |
+
with right:
|
| 91 |
+
output, explanation = lesson["run"]()
|
| 92 |
+
st.markdown("<div class='card'><h3>Resultado al ejecutar</h3>", unsafe_allow_html=True)
|
| 93 |
+
st.code(output, language="text")
|
| 94 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 95 |
+
st.markdown(f"<div class='explain'><b>¿Por qué sale este resultado?</b><br>{explanation}</div>", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
st.divider()
|
| 98 |
if st.button("← Volver al inicio"):
|
pages/4_Diagramas_a_codigo.py
CHANGED
|
@@ -7,94 +7,127 @@ import streamlit.components.v1 as components
|
|
| 7 |
|
| 8 |
|
| 9 |
APP_DIR = Path(__file__).resolve().parent.parent
|
| 10 |
-
DATA_FILE = APP_DIR / "
|
|
|
|
| 11 |
|
| 12 |
-
st.set_page_config(page_title="
|
| 13 |
|
| 14 |
|
| 15 |
@st.cache_data
|
| 16 |
-
def
|
| 17 |
with DATA_FILE.open("r", encoding="utf-8") as file:
|
| 18 |
-
return [
|
| 19 |
|
| 20 |
|
| 21 |
def render_mermaid(source):
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
components.html(
|
| 24 |
f"""
|
| 25 |
<style>
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
</style>
|
| 32 |
-
<div class=
|
| 33 |
-
|
| 34 |
-
mermaid.initialize({{startOnLoad:true, theme:"neutral", flowchart:{{curve:"linear"}}}});
|
| 35 |
-
</script><pre class="mermaid">{safe_source}</pre></div>
|
| 36 |
""",
|
| 37 |
-
height=
|
| 38 |
)
|
| 39 |
|
| 40 |
|
| 41 |
-
st.markdown(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"Selecciona un caso",
|
| 65 |
-
range(len(exercises)),
|
| 66 |
-
format_func=lambda i: f"{i + 1}. {exercises[i]['title']} · {exercises[i]['level']}",
|
| 67 |
-
)
|
| 68 |
-
st.session_state.flow_index = selected
|
| 69 |
-
exercise = exercises[selected]
|
| 70 |
-
|
| 71 |
-
st.info(exercise["prompt"])
|
| 72 |
-
diagram_col, editor_col = st.columns([1, 1], gap="large")
|
| 73 |
-
|
| 74 |
-
with diagram_col:
|
| 75 |
-
st.markdown('<div class="panel"><h3>1. Lee el diagrama</h3>', unsafe_allow_html=True)
|
| 76 |
-
render_mermaid(exercise["diagram"])
|
| 77 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 78 |
|
| 79 |
-
with
|
| 80 |
-
st.markdown(
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
| 88 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
st.
|
| 93 |
-
st.
|
| 94 |
-
elif answer.strip():
|
| 95 |
-
st.markdown('<div class="hint"><b>Antes de comparar:</b> revisa que tengas las entradas, la condición o el bucle necesario y una salida con <code>print</code>.</div>', unsafe_allow_html=True)
|
| 96 |
else:
|
| 97 |
-
st.caption("
|
| 98 |
|
| 99 |
st.divider()
|
| 100 |
if st.button("← Volver al inicio"):
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
APP_DIR = Path(__file__).resolve().parent.parent
|
| 10 |
+
DATA_FILE = APP_DIR / "class_exercises.json"
|
| 11 |
+
ASSETS = APP_DIR / "assets"
|
| 12 |
|
| 13 |
+
st.set_page_config(page_title="Diagrama a código · Clase", page_icon="🔀", layout="wide")
|
| 14 |
|
| 15 |
|
| 16 |
@st.cache_data
|
| 17 |
+
def load_cases():
|
| 18 |
with DATA_FILE.open("r", encoding="utf-8") as file:
|
| 19 |
+
return [case for case in json.load(file) if case["category"] == "diagram_to_code"]
|
| 20 |
|
| 21 |
|
| 22 |
def render_mermaid(source):
|
| 23 |
+
source = html.escape(source.strip())
|
| 24 |
+
components.html(
|
| 25 |
+
f"""
|
| 26 |
+
<style>body{{margin:0;background:white}}.box{{height:500px;display:flex;align-items:center;justify-content:center;border:1px solid #d9e4eb;border-radius:14px;padding:12px}}.mermaid{{width:100%;text-align:center}}.mermaid svg{{max-height:450px;max-width:100%}}</style>
|
| 27 |
+
<div class="box"><script type="module">import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";mermaid.initialize({{startOnLoad:true,theme:"neutral",flowchart:{{curve:"linear"}}}});</script><pre class="mermaid">{source}</pre></div>
|
| 28 |
+
""",
|
| 29 |
+
height=525,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def explain_line(line):
|
| 34 |
+
clean = line.strip()
|
| 35 |
+
if clean.startswith("input") or "input(" in clean:
|
| 36 |
+
return "Entrada: se solicita un dato al usuario y se guarda en una variable."
|
| 37 |
+
if clean.startswith("if "):
|
| 38 |
+
return "Decisión: esta condición corresponde al rombo del diagrama; determina la rama que continúa."
|
| 39 |
+
if clean.startswith("else"):
|
| 40 |
+
return "Rama alternativa: se ejecuta si la condición anterior fue falsa."
|
| 41 |
+
if clean.startswith("for ") or clean.startswith("while "):
|
| 42 |
+
return "Repetición: esta línea representa la flecha que vuelve en el diagrama hasta que se cumple la condición de salida."
|
| 43 |
+
if clean.startswith("print"):
|
| 44 |
+
return "Salida: se muestra al usuario el valor que ha calculado el algoritmo."
|
| 45 |
+
if "=" in clean:
|
| 46 |
+
return "Proceso/asignación: Python calcula la expresión de la derecha y guarda el resultado en la variable de la izquierda."
|
| 47 |
+
return "Esta línea forma parte de la traducción directa del diagrama a Python."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def flow_stage(line):
|
| 51 |
+
clean = line.strip()
|
| 52 |
+
if "input(" in clean:
|
| 53 |
+
return "Entrada", "El programa recibe un dato y lo guarda en una variable."
|
| 54 |
+
if clean.startswith("if ") or clean.startswith("elif "):
|
| 55 |
+
return "Decisión", "Python evalúa una pregunta y elige una de las ramas."
|
| 56 |
+
if clean.startswith("for ") or clean.startswith("while "):
|
| 57 |
+
return "Bucle", "El flujo vuelve a repetirse mientras queden elementos o se cumpla la condición."
|
| 58 |
+
if clean.startswith("print"):
|
| 59 |
+
return "Salida", "El resultado calculado se comunica al usuario."
|
| 60 |
+
return "Proceso", "Se realiza una operación o se actualiza una variable."
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def render_animation(stage, line_number, total, detail):
|
| 64 |
+
stages = ["Entrada", "Proceso", "Decisión", "Bucle", "Salida"]
|
| 65 |
+
cards = "".join(
|
| 66 |
+
f"<div class='node {'active' if name == stage else ''}'>{'⚡ ' if name == stage else ''}{name}</div>"
|
| 67 |
+
for name in stages
|
| 68 |
+
)
|
| 69 |
components.html(
|
| 70 |
f"""
|
| 71 |
<style>
|
| 72 |
+
body{{margin:0;background:transparent;font-family:Arial,sans-serif}}
|
| 73 |
+
.trace{{background:#101820;color:white;border-radius:13px;padding:16px}}
|
| 74 |
+
.row{{display:flex;gap:7px;align-items:center;justify-content:space-between;flex-wrap:wrap}}
|
| 75 |
+
.node{{padding:8px 10px;border-radius:9px;background:#26333f;color:#b8c7d2;font-size:13px;font-weight:700}}
|
| 76 |
+
.active{{background:#009fe3;color:#06131a;animation:pulse 1.2s ease-in-out infinite}}
|
| 77 |
+
.arrow{{color:#6d8798}} .detail{{margin-top:12px;color:#d9edf7;font-size:14px}}
|
| 78 |
+
@keyframes pulse{{50%{{transform:scale(1.06);box-shadow:0 0 0 6px rgba(0,159,227,.18)}}}}
|
| 79 |
</style>
|
| 80 |
+
<div class='trace'><div style='font-size:13px;color:#91cce8;margin-bottom:10px'>ANIMACIÓN · línea {line_number}/{total}</div>
|
| 81 |
+
<div class='row'>{cards}</div><div class='detail'><b>Ahora:</b> {detail}</div></div>
|
|
|
|
|
|
|
| 82 |
""",
|
| 83 |
+
height=142,
|
| 84 |
)
|
| 85 |
|
| 86 |
|
| 87 |
+
st.markdown("""<style>
|
| 88 |
+
.stApp{background:linear-gradient(145deg,#f7fafc,#eaf5ff)}.block-container{max-width:1220px;padding-top:2rem}
|
| 89 |
+
.hero{background:#101820;border-left:9px solid #009fe3;border-radius:20px;padding:1.8rem 2rem;color:white}.hero h1{color:white;margin:0}.hero p{color:#dbeaf2;margin:.5rem 0 0}
|
| 90 |
+
.card{background:white;border:1px solid #d8e3eb;border-radius:16px;padding:1.1rem}.explain{background:#e8f6fc;border-left:5px solid #009fe3;border-radius:10px;padding:1rem;line-height:1.65}
|
| 91 |
+
</style><div class='hero'><div style='float:right;font-size:27px;font-weight:800'>UA<span style='color:#009fe3'>X</span></div><h1>Del diagrama de flujo al código</h1><p>Herramienta de explicación en directo: primero se observa el flujo; después se construye Python línea a línea.</p></div>""", unsafe_allow_html=True)
|
| 92 |
+
|
| 93 |
+
with st.expander("Teoría visual para presentar antes del caso", expanded=True):
|
| 94 |
+
col1, col2 = st.columns(2)
|
| 95 |
+
with col1:
|
| 96 |
+
st.image(str(ASSETS / "ppt_46.png"), caption="Símbolos y lectura de un diagrama de flujo", use_container_width=True)
|
| 97 |
+
with col2:
|
| 98 |
+
st.image(str(ASSETS / "ppt_48.png"), caption="La condición y sus dos ramas", use_container_width=True)
|
| 99 |
+
|
| 100 |
+
cases = load_cases()
|
| 101 |
+
case_index = st.selectbox("Caso que se va a explicar", range(len(cases)), format_func=lambda i: cases[i]["title"])
|
| 102 |
+
case = cases[case_index]
|
| 103 |
+
lines = case["solution_code"].splitlines()
|
| 104 |
+
|
| 105 |
+
st.info(case["prompt"])
|
| 106 |
+
flow_col, code_col = st.columns([1, 1], gap="large")
|
| 107 |
+
with flow_col:
|
| 108 |
+
st.markdown("<div class='card'><h3>1. Diagrama: razonamiento</h3>", unsafe_allow_html=True)
|
| 109 |
+
render_mermaid(case["diagram"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 111 |
|
| 112 |
+
with code_col:
|
| 113 |
+
st.markdown("<div class='card'><h3>2. Python: construcción paso a paso</h3>", unsafe_allow_html=True)
|
| 114 |
+
step = st.slider("Paso que revela el profesor", min_value=0, max_value=len(lines), value=0, help="Empieza en 0 para que el alumnado analice el diagrama. Aumenta un paso después de cada explicación.")
|
| 115 |
+
if step == 0:
|
| 116 |
+
st.warning("Aún no se muestra el código: pide al alumnado que identifique entrada, proceso, decisión y salida.")
|
| 117 |
+
else:
|
| 118 |
+
visible = "\n".join(lines[:step])
|
| 119 |
+
st.code(visible, language="python", line_numbers=True)
|
| 120 |
+
st.markdown(f"<div class='explain'><b>Línea {step}:</b> {explain_line(lines[step - 1])}</div>", unsafe_allow_html=True)
|
| 121 |
+
stage, detail = flow_stage(lines[step - 1])
|
| 122 |
+
render_animation(stage, step, len(lines), detail)
|
| 123 |
st.markdown("</div>", unsafe_allow_html=True)
|
| 124 |
|
| 125 |
+
if step == len(lines):
|
| 126 |
+
st.markdown("### 3. Solución completa y explicación final")
|
| 127 |
+
st.success(case["explanation"])
|
| 128 |
+
st.caption("El profesor puede ahora ejecutar este código en Jupyter o usarlo como base para una variación con datos distintos.")
|
|
|
|
|
|
|
| 129 |
else:
|
| 130 |
+
st.caption("Dinámica recomendada: pregunta al alumnado qué bloque de Python corresponde al siguiente símbolo del diagrama; después mueve el control un paso.")
|
| 131 |
|
| 132 |
st.divider()
|
| 133 |
if st.button("← Volver al inicio"):
|