"""Piezas compartidas por «Clase guiada» y «Diagramas → código». - Estilo UAX y cabecera. - Trazado real de los ejemplos (se ejecutan con sys.settrace; nada está escrito a mano). - Un único componente HTML autocontenido: código | diagrama Mermaid + animación paso a paso. """ import html import io import json import keyword import os import re import shutil import sys import tempfile import threading import tokenize import types import streamlit as st import streamlit.components.v1 as components DARK = "#101820" BLUE = "#009FE3" TRACE_FILE = "" MAX_EVENTS = 4000 _RUN_LOCK = threading.Lock() BUILTINS = {"print", "input", "range", "int", "float", "str", "len", "bool", "list", "dict"} STAGES = ["entrada", "proceso", "decision", "bucle", "salida"] # --------------------------------------------------------------------------- estilo def page_style(): st.markdown( f""" """, unsafe_allow_html=True, ) def hero(title, subtitle): st.markdown( f"""

{html.escape(title)}

{html.escape(subtitle)}

""", unsafe_allow_html=True, ) def topic(number, title): st.markdown( f'
{number}{html.escape(title)}
', unsafe_allow_html=True, ) def label(text): st.markdown(f'
{html.escape(text)}
', unsafe_allow_html=True) def example_title(text): st.markdown(f'
{html.escape(text)}
', unsafe_allow_html=True) # --------------------------------------------------------------------------- utilidades de código def highlight_lines(code): """Devuelve una lista con el HTML coloreado de cada línea (sin dependencias externas).""" lines = code.splitlines() spans = [[] for _ in lines] try: for tok in tokenize.generate_tokens(io.StringIO(code + "\n").readline): name = tokenize.tok_name[tok.type] if name == "COMMENT": cls = "c" elif name == "STRING" or name.startswith("FSTRING"): cls = "s" elif name == "NUMBER": cls = "n" elif name == "NAME" and keyword.iskeyword(tok.string): cls = "k" elif name == "NAME" and tok.string in BUILTINS: cls = "b" else: continue (row, start), (end_row, end) = tok.start, tok.end if row == end_row and row <= len(lines) and end > start: spans[row - 1].append((start, end, cls)) except (tokenize.TokenError, IndentationError): pass result = [] for line, line_spans in zip(lines, spans): out, pos = [], 0 for start, end, cls in sorted(line_spans): if start < pos: continue out.append(html.escape(line[pos:start])) out.append(f'{html.escape(line[start:end])}') pos = end out.append(html.escape(line[pos:])) result.append("".join(out)) return result def _lookup(mapping, line_number, text): """Busca por número de línea o por el primer fragmento contenido en la línea.""" if not mapping: return None if line_number in mapping: return mapping[line_number] for key, value in mapping.items(): if isinstance(key, str) and key in text: return value return None def _indent(text): return len(text) - len(text.lstrip()) def _code(text): return f"{html.escape(str(text))}" def line_kind(text): clean = text.strip() if "input(" in clean: return "entrada" if clean.startswith(("if ", "elif ", "else", "except")): return "decision" if clean.startswith(("for ", "while ")) or clean in ("break", "continue"): return "bucle" if clean.startswith("print("): return "salida" return "proceso" # --------------------------------------------------------------------------- trazado real def _short(text, limit=320): return text if len(text) <= limit else text[:limit] + " …" def _snapshot(env, frame): values = {} def add(name, value): if isinstance(value, (types.ModuleType, types.FunctionType, types.MethodType, type)): return if type(value).__module__ == "__main__" and hasattr(value, "__dict__"): values[name] = f"objeto {type(value).__name__}" for attr, attr_value in vars(value).items(): values[f"{name}.{attr}"] = _short(repr(attr_value)) else: text = repr(value) if not (text.startswith("<") and text.endswith(">")): # ficheros abiertos y similares values[name] = _short(text) for name, value in env.items(): if not name.startswith("__") and name not in ("print", "input"): add(name, value) if frame is not None and frame.f_code.co_flags & 0x1: # dentro de una función o método for name, value in frame.f_locals.items(): add(name, value) return values def _changes_text(changed, before, after): parts = [] for name in changed[:4]: if name in before: parts.append(f"{_code(name)}: {_code(before[name])} → {_code(after[name])}") else: parts.append(f"{_code(name)} = {_code(after[name])}") return "; ".join(parts) @st.cache_data(show_spinner=False) def trace_program(code, inputs=()): """Ejecuta el ejemplo y devuelve (pasos, salida completa, variables finales).""" lines = code.splitlines() out, pending, events, errors = [], list(inputs), [], {} def fake_print(*args, sep=" ", end="\n", **_): out.append(sep.join(str(a) for a in args) + end) def fake_input(prompt=""): value = pending.pop(0) if pending else "" out.append(f"{prompt}{value}\n") return value env = {"__name__": "__main__", "print": fake_print, "input": fake_input} def tracer(frame, event, arg): if frame.f_code.co_filename != TRACE_FILE: return None if len(events) > MAX_EVENTS: raise RuntimeError("El ejemplo tiene demasiados pasos.") is_function = bool(frame.f_code.co_flags & 0x1) if event == "line": events.append(("line", frame.f_lineno, id(frame), frame.f_code.co_name, is_function, _snapshot(env, frame), "".join(out))) elif event == "exception" and events: errors[len(events) - 1] = arg[0].__name__ elif event == "return": back = frame.f_back caller = back.f_lineno if back is not None and back.f_code.co_filename == TRACE_FILE else None events.append(("return", caller if is_function else None, id(frame), frame.f_code.co_name, is_function, _snapshot(env, frame), "".join(out))) return tracer # Los ejemplos que crean ficheros trabajan en una carpeta temporal propia. with _RUN_LOCK: previous, home, workdir = sys.gettrace(), os.getcwd(), tempfile.mkdtemp(prefix="aula_") os.chdir(workdir) sys.settrace(tracer) try: exec(compile(code, TRACE_FILE, "exec"), env) except Exception as error: # el ejemplo se muestra igualmente, con su error out.append(f"{type(error).__name__}: {error}\n") finally: sys.settrace(previous) os.chdir(home) shutil.rmtree(workdir, ignore_errors=True) final_vars, final_out = _snapshot(env, None), "".join(out) steps = [] for index, (etype, line, frame_id, func, _is_fn, before, out_before) in enumerate(events): if line is None: continue if index + 1 < len(events): nxt = events[index + 1] after, out_after = nxt[5], nxt[6] else: nxt, after, out_after = None, final_vars, final_out changed = [name for name, value in after.items() if before.get(name) != value] printed = out_after[len(out_before):] text = lines[line - 1] clean = text.strip() next_line = next((e for e in events[index + 1:] if e[0] == "line"), None) between = lines[line:next_line[1]] if next_line is not None and next_line[1] > line else [] entered = ( bool(between) and next_line[2] == frame_id and all(_indent(row) > _indent(text) for row in between if row.strip() and not row.strip().startswith("#")) ) if clean.startswith("class ") and steps and steps[-1]["line"] == line: continue # la línea «class» genera dos eventos; basta con uno kind = line_kind(text) change_text = _changes_text(changed, before, after) if etype == "return": if not changed: continue kind = "proceso" note = f"Termina {_code(func)} y el programa vuelve a la línea {line}. {change_text}" elif (next_line is not None and next_line[2] == frame_id and not clean.startswith("except") and lines[next_line[1] - 1].strip().startswith("except") and index in errors): kind = "proceso" note = (f"Error. Esta línea falla con {_code(errors[index])}: Python abandona el " "try y busca un except que lo recoja.") elif clean == "try:": note = "Empieza el bloque try: Python vigila si alguna de sus líneas produce un error." elif clean.startswith("except"): name = clean[6:].rstrip(":").strip() or "cualquiera" note = (f"Decisión. ¿El error es de tipo {_code(name)}? → {'Sí' if entered else 'No'}. " + ("Se ejecuta este bloque." if entered else "Se prueba el siguiente except.")) elif clean.startswith("with "): note = ("with abre el recurso al entrar en el bloque y lo cierra " "automáticamente al salir.") elif "input(" in clean: note = f"Entrada. El programa pide un dato y el usuario escribe. {change_text}" elif clean.startswith(("if ", "elif ")): cond = clean.split(" ", 1)[1].rstrip(":") note = (f"Decisión. ¿{_code(cond)}? → {'Sí' if entered else 'No'}. " + ("Se ejecuta el bloque de esta rama." if entered else "Se salta este bloque.")) elif clean.startswith("for "): if entered: note = f"Bucle. Queda un elemento por recorrer: {change_text}. Se ejecuta el cuerpo." else: note = "Bucle. No quedan elementos: el for termina y el programa sigue." elif clean.startswith("while "): cond = clean[6:].rstrip(":") note = (f"Bucle. ¿{_code(cond)}? → {'Sí' if entered else 'No'}. " + ("Se repite el cuerpo." if entered else "El while termina.")) elif clean == "break": note = "break. Se sale del bucle inmediatamente." elif clean.startswith("class "): note = (f"Se define la clase {_code(clean[6:].rstrip(':'))}: es el molde. " "Todavía no existe ningún objeto.") elif clean.startswith("def "): note = (f"Se define {_code(clean[4:].split('(')[0])}. Su código queda guardado; " "no se ejecuta hasta que alguien lo llame.") elif nxt is not None and nxt[0] == "line" and nxt[2] != frame_id and nxt[4]: kind = "proceso" note = f"Llamada. El programa salta al código de {_code(nxt[3])}. {change_text}" elif clean.startswith("print("): note = f"Salida. Se escribe en pantalla: {_code(printed.rstrip())}" elif change_text: note = f"Proceso. {change_text}" else: note = "Proceso. Se ejecuta la instrucción." steps.append({ "line": line, "kind": kind, "note": note, "out": out_after, "vars": [[name, value, name in changed] for name, value in after.items()], }) return steps, final_out, final_vars def build_steps(code, notes): """Pasos en orden de escritura (para construir el programa línea a línea).""" steps = [] for number, text in enumerate(code.splitlines(), 1): clean = text.strip() if not clean or clean.startswith("#"): continue note = _lookup(notes, number, text) or "Esta línea traduce el siguiente símbolo del diagrama." steps.append({"line": number, "kind": line_kind(text), "note": note, "out": "", "vars": []}) return steps # --------------------------------------------------------------------------- componente visual def player(example, mode, flow_first=False): """mode: 'static' (código + diagrama), 'build' (línea a línea) o 'run' (ejecución animada).""" code = example["code"] lines = code.splitlines() nodes = example.get("nodes", {}) hints = example.get("hints", {}) if mode == "run": steps, _, _ = trace_program(code, tuple(example.get("inputs", ()))) steps = [dict(step) for step in steps] for step in steps: hint = _lookup(hints, step["line"], lines[step["line"] - 1]) if hint: step["note"] += f' {hint}' steps.append({"line": None, "kind": None, "node": "F", "out": steps[-1]["out"] if steps else "", "note": "Fin del programa. Debajo tienes la salida completa y la explicación.", "vars": [[n, v, False] for n, v, _ in steps[-1]["vars"]] if steps else []}) elif mode == "build": steps = build_steps(code, example.get("build_notes", {})) else: steps = [] last_node = "S" for step in steps: if "node" not in step: step["node"] = _lookup(nodes, step["line"], lines[step["line"] - 1]) or last_node last_node = step["node"] rows = example.get("rows") or len(set(re.findall(r"(\w+)(?:\(\[|\[|\{)", example["flow"]))) or 6 scroll = rows > 13 # diagramas grandes: tamaño legible con desplazamiento panel = max(300, min(820, max(len(lines) * 22 + 70, 640 if scroll else rows * 66 + 70))) extra = {"static": 0, "build": 215, "run": 425}[mode] longest = max((len(row) for row in lines), default=0) data = { "mode": mode, "lines": highlight_lines(code), "flow": example["flow"], "steps": steps, "panel": panel, "font": 14.5 if longest <= 62 else 13 if longest <= 74 else 12, "flowFirst": flow_first, "stages": STAGES, "scroll": scroll, } payload = json.dumps(data, ensure_ascii=False).replace(" * { box-sizing: border-box; } [hidden] { display: none !important; } body { margin: 0; font-family: "Segoe UI", Arial, sans-serif; color: #101820; background: transparent; } .grid { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); gap: 14px; } .panel { border-radius: 12px; overflow: hidden; display: flex; flex-direction: column; } .panel h3 { margin: 0; padding: 9px 14px; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; } .code { background: #101820; } .code h3 { color: #8FD3F2; border-bottom: 1px solid #26333F; } .flow { background: #fff; border: 1px solid #D5E0E8; } .flow h3 { color: #4A5B68; border-bottom: 1px solid #E3EBF0; } .src { flex: 1; padding: 10px 0; font: 14.5px/22px Consolas, "Cascadia Mono", Menlo, monospace; color: #D7E6F0; overflow: auto; } .ln { display: flex; white-space: pre; border-left: 4px solid transparent; padding-right: 12px; } .ln .no { width: 34px; text-align: right; color: #5E7384; padding-right: 12px; user-select: none; flex: none; } .ln.cur { background: rgba(0,159,227,.30); border-left-color: #009FE3; } .ln.cur .no { color: #fff; font-weight: 700; } .ln.hid .tx { visibility: hidden; } .k { color: #C99BE0; } .s { color: #E3A27F; } .n { color: #B9D8A6; } .c { color: #7FAE6B; } .b { color: #E6DC9A; } #flow { flex: 1; display: flex; align-items: center; justify-content: center; padding: 10px; min-height: 0; } #flow svg { max-width: 100% !important; width: 100%; height: 100%; } #flow.scroll { display: block; overflow: auto; } #flow.scroll svg { height: auto; } #flow .msg { color: #7A8B97; font-size: 14px; text-align: center; } #flow .node.done rect, #flow .node.done polygon, #flow .node.done path { fill: #D6F0FB !important; } #flow .node.active rect, #flow .node.active polygon, #flow .node.active path { fill: #009FE3 !important; stroke: #101820 !important; stroke-width: 3px !important; } #flow .node.active .nodeLabel, #flow .node.active text { color: #fff !important; fill: #fff !important; } #flow .node.active { animation: pop 1s ease-in-out infinite; transform-box: fill-box; transform-origin: center; } @keyframes pop { 50% { filter: drop-shadow(0 0 7px rgba(0,159,227,.9)); } } .player { margin-top: 14px; background: #fff; border: 1px solid #D5E0E8; border-radius: 12px; padding: 12px 14px; } .bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } button { font: 600 14px "Segoe UI", Arial, sans-serif; padding: 7px 13px; border-radius: 8px; cursor: pointer; border: 1px solid #B9C8D3; background: #fff; color: #101820; } button:hover:not(:disabled) { border-color: #009FE3; color: #007DB3; } button:disabled { opacity: .4; cursor: default; } button.main { background: #009FE3; border-color: #009FE3; color: #fff; } button.main:hover:not(:disabled) { background: #0088C4; color: #fff; } .count { margin-left: auto; color: #4A5B68; font-size: 13px; font-weight: 600; } .stages { display: flex; gap: 6px; margin-top: 11px; flex-wrap: wrap; } .stage { flex: 1; min-width: 86px; text-align: center; padding: 7px 6px; border-radius: 8px; font-size: 13px; font-weight: 700; background: #EDF2F5; color: #7A8B97; transition: all .25s; } .stage.on { background: #101820; color: #fff; box-shadow: inset 0 -4px 0 #009FE3; } .note { margin-top: 11px; background: #E6F5FC; border-left: 5px solid #009FE3; border-radius: 8px; padding: 10px 13px; font-size: 15px; line-height: 1.5; min-height: 66px; } .note code, td code { font-family: Consolas, Menlo, monospace; background: rgba(16,24,32,.08); padding: 1px 5px; border-radius: 4px; font-size: 13.5px; } .note .hint { display: block; margin-top: 4px; color: #33505F; } .state { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 11px; } .box { border: 1px solid #D5E0E8; border-radius: 8px; height: 190px; display: flex; flex-direction: column; overflow: hidden; } .box h4 { margin: 0; padding: 6px 10px; font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: #4A5B68; background: #F1F5F8; } .box .body { flex: 1; overflow: auto; } table { width: 100%; border-collapse: collapse; font-size: 13.5px; } td { padding: 4px 10px; border-bottom: 1px solid #EEF2F5; vertical-align: top; } td:first-child { width: 42%; white-space: nowrap; } td code { white-space: pre-wrap; word-break: break-word; } tr.chg td { background: #FFF4CC; } tr.chg td:first-child::after { content: " ● cambia"; color: #B26A00; font-size: 11px; font-weight: 700; } pre.out { margin: 0; padding: 8px 10px; font: 13.5px/19px Consolas, Menlo, monospace; background: #101820; color: #E4EEF4; min-height: 100%; white-space: pre-wrap; } .empty { color: #8A9AA6; padding: 10px; font-size: 13px; } @media (max-width: 760px) { .grid, .state { grid-template-columns: 1fr; } }

Código Python

Diagrama de flujo

Cargando diagrama…
"""