Download app.py from GALEAlab/GALEA: direct link, hf CLI and curl.
- Browser
- Download file 26.9 kB
-
https://huggingface.co/spaces/GALEAlab/GALEA/resolve/main/app.py
- Command line
-
hf download hf://spaces/GALEAlab/GALEA/app.py
-
curl -L -o app.py https://huggingface.co/spaces/GALEAlab/GALEA/resolve/main/app.py
26.9 kB
| import streamlit as st | |
| import pandas as pd | |
| import os | |
| import re | |
| import math | |
| import json | |
| import datetime | |
| import urllib.parse | |
| from collections import Counter | |
| from openai import OpenAI | |
| # ───────────────────────────────────────────── | |
| # CONFIGURACIÓN | |
| # ───────────────────────────────────────────── | |
| st.set_page_config(page_title="GALEA – UIS", page_icon="🎓", layout="centered") | |
| def _get_secret(key): | |
| try: | |
| if key in st.secrets: | |
| return st.secrets[key] | |
| except Exception: | |
| pass | |
| return os.getenv(key) | |
| groq_key = _get_secret("GROQ_API_KEY") | |
| if not groq_key: | |
| st.error("⚠️ No se encontró 'GROQ_API_KEY'. Agrégalo en Settings > Variables and secrets.") | |
| st.stop() | |
| # ───────────────────────────────────────────── | |
| # GOOGLE CALENDAR – ENLACE SIMPLE (sin API, sin Cloud Console) | |
| # ───────────────────────────────────────────── | |
| def generar_link_calendar(nombre_ludica, fecha, hora_inicio, duracion_min, | |
| participantes, nombre_docente, correo_docente, | |
| materia, notas=""): | |
| """Genera un enlace 'Añadir a Google Calendar' con los datos prellenados. | |
| El profesor debe abrirlo y hacer clic en 'Guardar' para que el evento se cree | |
| de verdad — no ocurre nada en el servidor hasta que él lo confirma. | |
| Si guarda el evento, Google invita automáticamente a coordinación | |
| (si GALEA_COORDINACION_EMAIL está configurado), porque queda como invitado real.""" | |
| tz = "America/Bogota" | |
| start_dt = datetime.datetime.combine(fecha, hora_inicio) | |
| end_dt = start_dt + datetime.timedelta(minutes=int(duracion_min)) | |
| fmt = "%Y%m%dT%H%M%S" | |
| dates_param = f"{start_dt.strftime(fmt)}/{end_dt.strftime(fmt)}" | |
| detalles = ( | |
| f"Lúdica: {nombre_ludica}\n" | |
| f"Docente: {nombre_docente}\n" | |
| f"Materia / curso: {materia}\n" | |
| f"Participantes: {participantes}\n" | |
| f"Notas: {notas or '—'}\n\n" | |
| f"Agendado desde el Asistente GALEA." | |
| ) | |
| correo_coordinacion = _get_secret("GALEA_COORDINACION_EMAIL") | |
| invitados = [correo_docente] | |
| if correo_coordinacion: | |
| invitados.append(correo_coordinacion) | |
| params = { | |
| "action": "TEMPLATE", | |
| "text": f"Lúdica GALEA: {nombre_ludica} — {materia} — {nombre_docente}", | |
| "dates": dates_param, | |
| "details": detalles, | |
| "ctz": tz, | |
| "add": ",".join(invitados), | |
| } | |
| return "https://calendar.google.com/calendar/render?" + urllib.parse.urlencode(params) | |
| # ───────────────────────────────────────────── | |
| # RAG: CARGA E ÍNDICE TF-IDF | |
| # ───────────────────────────────────────────── | |
| def tokenize(text: str) -> list: | |
| text = text.lower() | |
| text = re.sub(r"[^a-záéíóúüñ0-9\s]", " ", text) | |
| return [t for t in text.split() if len(t) > 2] | |
| def load_and_index(path="GALEAt.xlsx"): | |
| df = pd.read_excel(path) | |
| def build_doc(row): | |
| fields = [ | |
| row.get("NOMBRE_LUDICA", ""), | |
| row.get("TEMA_PRINCIPAL", ""), | |
| row.get("OBJETIVO_ENSENANZA", ""), | |
| row.get("COMPETENCIAS_ESPECIFICAS", ""), | |
| row.get("CONCEPTOS_CLAVE", ""), | |
| row.get("METADATOS_BUSQUEDA", ""), | |
| row.get("RESUMEN_METODOLOGIA", ""), | |
| row.get("RECOMENDACIONES_DOCENTE", ""), | |
| row.get("PARTICIPANTES", ""), | |
| row.get("TIEMPO_TOTAL", ""), | |
| ] | |
| return " ".join(str(f) for f in fields if pd.notna(f)) | |
| docs = [build_doc(row) for _, row in df.iterrows()] | |
| tokenized = [tokenize(d) for d in docs] | |
| N = len(tokenized) | |
| df_count = Counter() | |
| for tokens in tokenized: | |
| for t in set(tokens): | |
| df_count[t] += 1 | |
| idf = {t: math.log((N + 1) / (c + 1)) + 1 for t, c in df_count.items()} | |
| def tfidf_vec(tokens): | |
| tf = Counter(tokens) | |
| total = len(tokens) or 1 | |
| return {t: (c / total) * idf.get(t, 1) for t, c in tf.items()} | |
| vectors = [tfidf_vec(t) for t in tokenized] | |
| return df, vectors, idf | |
| df_galea, vectors, idf = load_and_index() | |
| # ───────────────────────────────────────────── | |
| # RAG: PLAN DE ESTUDIOS (MATERIAS) — índice independiente | |
| # ───────────────────────────────────────────── | |
| def load_and_index_materias(path="MATERIAS.xlsx"): | |
| df = pd.read_excel(path) | |
| def build_doc_materia(row): | |
| fields = [ | |
| row.get("materia", ""), | |
| row.get("objetivo", ""), | |
| row.get("contenido/temas", ""), | |
| row.get("metodologias", ""), | |
| row.get("competencias", ""), | |
| row.get("areas", ""), | |
| row.get("observaciones", ""), | |
| ] | |
| return " ".join(str(f) for f in fields if pd.notna(f)) | |
| docs = [build_doc_materia(row) for _, row in df.iterrows()] | |
| tokenized = [tokenize(d) for d in docs] | |
| N = len(tokenized) | |
| df_count = Counter() | |
| for tokens in tokenized: | |
| for t in set(tokens): | |
| df_count[t] += 1 | |
| idf_m = {t: math.log((N + 1) / (c + 1)) + 1 for t, c in df_count.items()} | |
| def tfidf_vec(tokens): | |
| tf = Counter(tokens) | |
| total = len(tokens) or 1 | |
| return {t: (c / total) * idf_m.get(t, 1) for t, c in tf.items()} | |
| vectors_m = [tfidf_vec(t) for t in tokenized] | |
| return df, vectors_m, idf_m | |
| try: | |
| df_materias, vectors_materias, idf_materias = load_and_index_materias() | |
| MATERIAS_DISPONIBLES = True | |
| except Exception: | |
| df_materias, vectors_materias, idf_materias = None, None, None | |
| MATERIAS_DISPONIBLES = False | |
| def retrieve_materias(query: str, top_k: int = 2, threshold: float = 0.06): | |
| """A diferencia de retrieve() para lúdicas, aquí NO forzamos un resultado | |
| de respaldo: si ninguna materia supera el umbral, devolvemos una lista vacía | |
| para no meter contexto irrelevante en preguntas que no son sobre materias.""" | |
| if not MATERIAS_DISPONIBLES: | |
| return [] | |
| q_tokens = tokenize(query) | |
| if not q_tokens: | |
| return [] | |
| tf = Counter(q_tokens) | |
| total = len(q_tokens) | |
| q_vec = {t: (c / total) * idf_materias.get(t, 1) for t, c in tf.items()} | |
| scores = sorted( | |
| enumerate(vectors_materias), key=lambda x: cosine_sim(q_vec, x[1]), reverse=True | |
| ) | |
| return [i for i, _ in scores if cosine_sim(q_vec, vectors_materias[i]) >= threshold][:top_k] | |
| def format_materia(row) -> str: | |
| return ( | |
| f"MATERIA: {row['materia']}\n" | |
| f"Objetivo: {row['objetivo']}\n" | |
| f"Temas: {row['contenido/temas']}\n" | |
| f"Metodologías: {row['metodologias']}\n" | |
| f"Competencias: {row['competencias']}\n" | |
| f"Áreas: {row['areas']}\n" | |
| f"Observaciones (solo contexto pedagógico, NO son lúdicas reales del catálogo): " | |
| f"{row['observaciones']}\n" | |
| ) | |
| def build_materias_context(query: str, top_k: int = 2): | |
| """Devuelve (bloque_de_texto, nombres) o (None, []) si no hay materias relevantes.""" | |
| if not MATERIAS_DISPONIBLES: | |
| return None, [] | |
| indices = retrieve_materias(query, top_k=top_k) | |
| if not indices: | |
| return None, [] | |
| nombres = [df_materias.iloc[i]["materia"] for i in indices] | |
| bloques = [format_materia(df_materias.iloc[i]) for i in indices] | |
| ctx = ( | |
| f"MATERIAS DEL PLAN DE ESTUDIOS RELACIONADAS CON LA CONSULTA " | |
| f"({len(indices)} de {len(df_materias)}):\n\n" | |
| + "\n---\n".join(bloques) | |
| + "\n\nADVERTENCIA: El campo 'Observaciones' de estas materias puede mencionar " | |
| "nombres de juegos o simuladores de ejemplo (como 'Beer Game', 'ProModel', etc.) " | |
| "que NO existen en el catálogo real de GALEA. Ignóralos como posibles lúdicas — " | |
| "solo puedes recomendar lúdicas del bloque LÚDICAS RECUPERADAS." | |
| ) | |
| return ctx, nombres | |
| def cosine_sim(a, b): | |
| common = set(a) & set(b) | |
| if not common: | |
| return 0.0 | |
| dot = sum(a[k] * b[k] for k in common) | |
| na = math.sqrt(sum(v * v for v in a.values())) | |
| nb = math.sqrt(sum(v * v for v in b.values())) | |
| return dot / (na * nb) if na * nb > 0 else 0.0 | |
| def retrieve(query: str, top_k: int = 3, threshold: float = 0.04): | |
| q_tokens = tokenize(query) | |
| if not q_tokens: | |
| return list(range(min(top_k, len(df_galea)))) | |
| tf = Counter(q_tokens) | |
| total = len(q_tokens) | |
| q_vec = {t: (c / total) * idf.get(t, 1) for t, c in tf.items()} | |
| scores = sorted(enumerate(vectors), key=lambda x: cosine_sim(q_vec, x[1]), reverse=True) | |
| result = [i for i, _ in scores if cosine_sim(q_vec, vectors[i]) >= threshold][:top_k] | |
| return result if result else [scores[0][0]] | |
| def format_ludica(row) -> str: | |
| return ( | |
| f"LÚDICA: {row['NOMBRE_LUDICA']}\n" | |
| f"Tema: {row['TEMA_PRINCIPAL']}\n" | |
| f"Objetivo: {row['OBJETIVO_ENSENANZA']}\n" | |
| f"Competencias: {row['COMPETENCIAS_ESPECIFICAS']}\n" | |
| f"Participantes: {row['PARTICIPANTES']} | Roles: {row['ROLES_CLAVES']}\n" | |
| f"Duración: {row['TIEMPO_TOTAL']}\n" | |
| f"Materiales: {row['MATERIALES_DETALLADOS']}\n" | |
| f"Metodología: {row['RESUMEN_METODOLOGIA']}\n" | |
| f"Conceptos clave: {row['CONCEPTOS_CLAVE']}\n" | |
| f"Recomendaciones docente: {row['RECOMENDACIONES_DOCENTE']}\n" | |
| f"Dificultades comunes: {row['DIFICULTADES_COMUNES']}\n" | |
| f"Preguntas de retroalimentación: {row['PREGUNTAS_RETROALIMENTACION']}\n" | |
| f"Observaciones logísticas: {row['OBSERVACIONES_LOGISTICAS']}\n" | |
| ) | |
| def build_rag_context(query: str, top_k: int = 3): | |
| indices = retrieve(query, top_k=top_k) | |
| nombres = [df_galea.iloc[i]["NOMBRE_LUDICA"] for i in indices] | |
| bloques = [format_ludica(df_galea.iloc[i]) for i in indices] | |
| todos_los_nombres = df_galea["NOMBRE_LUDICA"].tolist() | |
| ctx = ( | |
| f"CATÁLOGO COMPLETO GALEA (ÚNICOS NOMBRES VÁLIDOS — no existen otras lúdicas):\n" | |
| + ", ".join(todos_los_nombres) | |
| + f"\n\nLÚDICAS RECUPERADAS PARA ESTA CONSULTA ({len(indices)} de {len(df_galea)}):\n\n" | |
| + "\n---\n".join(bloques) | |
| + "\n\nADVERTENCIA: Solo puedes recomendar lúdicas de la lista CATÁLOGO COMPLETO GALEA." | |
| ) | |
| return ctx, nombres | |
| def validar_respuesta(respuesta: str, nombres_validos: list, prompt_usuario: str = "") -> str: | |
| if len(prompt_usuario.strip()) < 15: | |
| return respuesta | |
| nombres_upper = [n.upper() for n in nombres_validos] | |
| texto_upper = respuesta.upper() | |
| entre_comillas = re.findall(r'["\']([ A-ZÁÉÍÓÚÜÑ0-9]{4,})["\']', texto_upper) | |
| tras_verbo = re.findall( | |
| r'(?:ES EL |ES LA |SE LLAMA |LLAMADA |LLAMADO |TITULADA |TITULADO )([A-ZÁÉÍÓÚÜÑ][A-ZÁÉÍÓÚÜÑ ]{3,})', | |
| texto_upper | |
| ) | |
| candidatos = [c.strip() for c in entre_comillas + tras_verbo if len(c.strip()) > 4] | |
| for candidato in candidatos: | |
| if not any(candidato in n or n in candidato for n in nombres_upper): | |
| return ( | |
| "\u26a0\ufe0f No encontr\u00e9 una l\u00fadica en el cat\u00e1logo GALEA " | |
| "que cubra ese tema.\n\n" | |
| "En este piloto las l\u00fadicas disponibles son:\n" | |
| "- **KANBAN** \u2014 manufactura esbelta y gesti\u00f3n visual\n" | |
| "- **CONTROLA MI TIEMPO** \u2014 gesti\u00f3n del tiempo y productividad\n" | |
| "- **JOB SHOP** \u2014 programaci\u00f3n y secuenciaci\u00f3n de producci\u00f3n\n\n" | |
| "\u00bfTu clase se relaciona con alguno de estos temas?" | |
| ) | |
| return respuesta | |
| # ───────────────────────────────────────────── | |
| # SYSTEM PROMPT | |
| # ───────────────────────────────────────────── | |
| SYSTEM_PROMPT = """Eres el Asistente de Lúdicas Pedagógicas GALEA de la UIS. | |
| Ayudas a docentes a seleccionar y aplicar lúdicas educativas. | |
| IDENTIDAD: | |
| - Lenguaje profesional y cercano. Trata al docente de "tú". | |
| - Respuestas CONCISAS y directas. Máximo 1000 palabras salvo que pidan detalle completo. | |
| - No repitas información ya dada en la conversación. | |
| LÚDICAS DEL PILOTO — ÚNICO CATÁLOGO DISPONIBLE: | |
| Las únicas lúdicas que existen en este sistema son exactamente estas tres: | |
| 1. KANBAN | |
| 2. CONTROLA MI TIEMPO | |
| 3. JOB SHOP | |
| No menciones ninguna otra lúdica bajo ninguna circunstancia. | |
| REGLA ABSOLUTA — INVENTAR ESTÁ PROHIBIDO: | |
| - SOLO puedes mencionar lúdicas que aparezcan textualmente en el bloque LÚDICAS RECUPERADAS. | |
| - Si el tema consultado NO tiene una lúdica recuperada que lo cubra, responde exactamente: | |
| "No encontré una lúdica en GALEA que cubra ese tema. Puedes intentar buscar por: [sugiere 2-3 términos alternativos relacionados con las lúdicas disponibles]." | |
| - NUNCA menciones lúdicas con nombres que no estén en el bloque LÚDICAS RECUPERADAS. | |
| - NUNCA uses frases como "podría adaptarse", "no está en la lista pero", "una opción sería". | |
| - Si tienes duda de si una lúdica existe, NO la menciones. | |
| OPERACIÓN: | |
| - Usa SOLO los datos del bloque LÚDICAS RECUPERADAS que recibirás en cada mensaje. | |
| - Si la pregunta es ambigua, haz UNA sola pregunta de aclaración. | |
| CAPACIDADES: | |
| 1. BÚSQUEDA: filtra por tema, participantes, duración o competencia. | |
| 2. RECOMENDACIÓN: sugiere la lúdica más adecuada con 2-3 líneas de justificación. | |
| 3. DETALLE: solo cuando lo pidan explícitamente, usa este formato: | |
| 📌 **Nombre** | 🎯 **Objetivo** | 🧠 **Competencias** | 👥 **Participantes** | |
| ⏱️ **Duración** | 🧰 **Materiales** | 📋 **Metodología** | |
| 💡 **Recomendaciones** | ⚠️ **Dificultades** | ❓ **Preguntas de cierre** | |
| 4. APOYO: checklist de preparación, tips de facilitación o preguntas de cierre según lo que pidan. | |
| 5. COMPARACIÓN: tabla breve de diferencias + recomendación final. | |
| 6. AGENDAMIENTO: Si el docente pregunta cómo reservar, agendar, solicitar o usar una lúdica, | |
| responde SIEMPRE exactamente esto: | |
| "¡Puedes agendarla directamente aquí! 📅 Abre el formulario **'Agendar una lúdica'** que | |
| aparece debajo de este chat, indica la lúdica, el día, la hora, tu nombre, correo y materia. | |
| Se generará un botón para añadirlo a tu Google Calendar — solo confirma con 'Guardar' | |
| ahí y coordinación quedará notificada automáticamente." | |
| 7. MATERIAS DEL PLAN DE ESTUDIOS: Si recibes un bloque "MATERIAS DEL PLAN DE ESTUDIOS | |
| RELACIONADAS", úsalo para responder preguntas sobre materias específicas de Ingeniería | |
| Industrial (objetivo, temas, competencias, área). Si el docente pregunta qué lúdica | |
| recomiendas para una materia puntual, cruza la información de esa materia (temas, | |
| competencias, áreas) con las LÚDICAS RECUPERADAS y justifica la conexión. | |
| REGLA CRÍTICA: el campo "Observaciones" de una materia puede mencionar juegos o | |
| simuladores de ejemplo que NO son lúdicas reales del catálogo GALEA (por ejemplo | |
| "Beer Game" o "ProModel"). NUNCA los presentes como si fueran lúdicas disponibles. | |
| Si ninguna lúdica del catálogo real conecta bien con esa materia, dilo con honestidad: | |
| "Para [materia] no encontré una lúdica de GALEA que encaje directamente. Las lúdicas | |
| disponibles actualmente son KANBAN, CONTROLA MI TIEMPO y JOB SHOP." | |
| """ | |
| # ───────────────────────────────────────────── | |
| # CLIENTE LLM (Groq — capa gratuita generosa) | |
| # ───────────────────────────────────────────── | |
| GROQ_MODEL = "openai/gpt-oss-120b" | |
| def get_client(): | |
| return OpenAI( | |
| base_url="https://api.groq.com/openai/v1", | |
| api_key=groq_key, | |
| ) | |
| client = get_client() | |
| # ───────────────────────────────────────────── | |
| # INTERFAZ | |
| # ───────────────────────────────────────────── | |
| st.title("🎓 Asistente GALEA – UIS") | |
| st.caption( | |
| f"**{len(df_galea)} lúdicas disponibles** · Búsqueda semántica (RAG) automática · " | |
| "Pregunta por tema, competencia, número de estudiantes o lúdica específica." | |
| ) | |
| # ── SIDEBAR ────────────────────────────────── | |
| with st.sidebar: | |
| st.header("📚 Catálogo GALEA") | |
| st.caption("Clic para consultar cualquier lúdica:") | |
| for nombre in df_galea["NOMBRE_LUDICA"]: | |
| if st.button(nombre, key=f"btn_{nombre}", use_container_width=True): | |
| st.session_state["pregunta_rapida"] = f"Explícame en detalle la lúdica '{nombre}'" | |
| st.divider() | |
| st.markdown("**Consultas de ejemplo:**") | |
| sugerencias = [ | |
| "¿Qué lúdica recomiendas para manufactura esbelta?", | |
| "¿Cómo funciona la lúdica KANBAN?", | |
| "¿Qué materiales necesito para JOB SHOP?", | |
| "¿Cómo cierro la sesión de CONTROLA MI TIEMPO?", | |
| "¿Qué hago si un equipo termina muy rápido?", | |
| "Compara KANBAN con JOB SHOP", | |
| "¿Cómo agendo una lúdica?", | |
| "¿Qué lúdica recomiendas para Dirección de Operaciones 2?", | |
| ] | |
| for s in sugerencias: | |
| if st.button(s, key=f"sug_{s}", use_container_width=True): | |
| st.session_state["pregunta_rapida"] = s | |
| st.divider() | |
| top_k = st.slider( | |
| "Lúdicas a recuperar por consulta", | |
| min_value=1, max_value=6, value=3, | |
| help="El RAG selecciona las N más relevantes antes de enviar al modelo. " | |
| "Más lúdicas = más contexto pero mayor latencia." | |
| ) | |
| # ── HISTORIAL ──────────────────────────────── | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [ | |
| { | |
| "role": "assistant", | |
| "content": ( | |
| "¡Hola! Soy el Asistente de Lúdicas Pedagógicas GALEA de la UIS. 🎓\n\n" | |
| "Puedo ayudarte a:\n" | |
| "- 🔍 **Buscar** lúdicas por tema, competencia, participantes o duración\n" | |
| "- 💡 **Recomendar** la más adecuada con justificación pedagógica\n" | |
| "- 📋 **Detallar** materiales, metodología y pasos completos\n" | |
| "- 🏫 **Apoyarte** antes, durante y después de la actividad\n" | |
| "- ⚖️ **Comparar** dos lúdicas para decidir cuál usar\n\n" | |
| "📅 Cuando quieras reservar una sesión, solo escribe la palabra " | |
| "**AGENDAR** y aquí abajo aparecerá el formulario para hacerlo.\n\n" | |
| "¿Sobre qué tema o situación de clase me consultas hoy?" | |
| ), | |
| } | |
| ] | |
| if "mostrar_agendamiento" not in st.session_state: | |
| st.session_state.mostrar_agendamiento = False | |
| if "mostrar_agendar" not in st.session_state: | |
| st.session_state["mostrar_agendar"] = False | |
| for msg in st.session_state.messages: | |
| with st.chat_message(msg["role"]): | |
| st.markdown(msg["content"]) | |
| if msg.get("retrieved"): | |
| with st.expander("🔍 Lúdicas recuperadas por el RAG", expanded=False): | |
| st.caption(" · ".join(msg["retrieved"])) | |
| if msg.get("materias"): | |
| with st.expander("📘 Materias del plan de estudios relacionadas", expanded=False): | |
| st.caption(" · ".join(msg["materias"])) | |
| # ── ENTRADA ────────────────────────────────── | |
| default_input = st.session_state.pop("pregunta_rapida", "") | |
| prompt = st.chat_input( | |
| "Ej: ¿Qué lúdica recomiendas para enseñar cadena de suministro con 25 estudiantes?" | |
| ) or default_input | |
| if prompt: | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| if re.search(r"\bagendar\b", prompt, re.IGNORECASE): | |
| st.session_state.mostrar_agendamiento = True | |
| recent_query = " ".join( | |
| m["content"] for m in st.session_state.messages[-5:] | |
| if m["role"] == "user" | |
| ) | |
| rag_context, retrieved_names = build_rag_context(recent_query, top_k=top_k) | |
| materias_context, materias_encontradas = build_materias_context(recent_query, top_k=2) | |
| all_history = [ | |
| m for m in st.session_state.messages[1:-1] | |
| if m["role"] in ("user", "assistant") | |
| ] | |
| history = [] | |
| char_budget = 2000 | |
| for m in reversed(all_history): | |
| if char_budget <= 0: | |
| break | |
| history.insert(0, m) | |
| char_budget -= len(m["content"]) | |
| contexto_completo = rag_context | |
| if materias_context: | |
| contexto_completo += "\n\n" + materias_context | |
| api_messages = ( | |
| [{"role": "system", "content": SYSTEM_PROMPT}] | |
| + [{"role": m["role"], "content": m["content"]} for m in history] | |
| + [{ | |
| "role": "user", | |
| "content": f"{contexto_completo}\n\nPREGUNTA DEL DOCENTE:\n{prompt}" | |
| }] | |
| ) | |
| with st.chat_message("assistant"): | |
| placeholder = st.empty() | |
| response = "" | |
| try: | |
| stream = client.chat.completions.create( | |
| model=GROQ_MODEL, | |
| messages=api_messages, | |
| temperature=0.2, | |
| stream=True, | |
| ) | |
| for chunk in stream: | |
| if not chunk.choices: | |
| continue | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| response += delta | |
| placeholder.markdown(response + "▌") | |
| response = validar_respuesta(response, df_galea["NOMBRE_LUDICA"].tolist(), prompt) | |
| placeholder.markdown(response) | |
| with st.expander("🔍 Lúdicas recuperadas por el RAG", expanded=False): | |
| st.caption(" · ".join(retrieved_names)) | |
| if materias_encontradas: | |
| with st.expander("📘 Materias del plan de estudios relacionadas", expanded=False): | |
| st.caption(" · ".join(materias_encontradas)) | |
| except Exception as e: | |
| response = f"❌ Error al conectar con el modelo: {e}" | |
| placeholder.error(response) | |
| st.session_state.messages.append({ | |
| "role": "assistant", | |
| "content": response, | |
| "retrieved": retrieved_names, | |
| "materias": materias_encontradas, | |
| }) | |
| # ── LIMPIAR ────────────────────────────────── | |
| if len(st.session_state.messages) > 1: | |
| if st.button("🗑️ Limpiar conversación", type="secondary"): | |
| st.session_state.messages = st.session_state.messages[:1] | |
| st.session_state.mostrar_agendamiento = False | |
| st.rerun() | |
| # ───────────────────────────────────────────── | |
| # FORMULARIO DE AGENDAMIENTO (solo si el docente escribió "AGENDAR") | |
| # ───────────────────────────────────────────── | |
| if st.session_state.mostrar_agendamiento: | |
| st.divider() | |
| st.subheader("📅 Agendar una lúdica") | |
| st.caption( | |
| "Completa los datos y genera el evento. Se abrirá Google Calendar con todo " | |
| "prellenado — solo debes hacer clic en **Guardar** ahí para confirmarlo." | |
| ) | |
| with st.form("form_agendar"): | |
| nombre_ludica_sel = st.selectbox("Lúdica", df_galea["NOMBRE_LUDICA"].tolist()) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| fecha_sel = st.date_input("Día", min_value=datetime.date.today()) | |
| with col2: | |
| hora_sel = st.time_input("Hora de inicio", value=datetime.time(8, 0)) | |
| duracion_sel = st.number_input( | |
| "Duración (minutos)", min_value=15, max_value=480, value=90, step=15 | |
| ) | |
| participantes_sel = st.number_input( | |
| "Número de participantes", min_value=1, max_value=200, value=20 | |
| ) | |
| nombre_docente_sel = st.text_input("Nombre del profesor") | |
| correo_docente_sel = st.text_input("Correo institucional") | |
| materia_sel = st.text_input("Materia o curso") | |
| notas_sel = st.text_area("Notas adicionales (opcional)") | |
| enviado = st.form_submit_button("📅 Generar agendamiento") | |
| if enviado: | |
| if not nombre_docente_sel or not correo_docente_sel or not materia_sel: | |
| st.error("Por favor completa el nombre del profesor, correo y materia.") | |
| elif "@" not in correo_docente_sel: | |
| st.error("Ingresa un correo válido.") | |
| else: | |
| link = generar_link_calendar( | |
| nombre_ludica_sel, fecha_sel, hora_sel, duracion_sel, | |
| participantes_sel, nombre_docente_sel, correo_docente_sel, | |
| materia_sel, notas_sel | |
| ) | |
| st.success( | |
| f"✅ Listo. Haz clic abajo y luego en **Guardar** dentro de Google " | |
| f"Calendar para confirmar **{nombre_ludica_sel}** el " | |
| f"{fecha_sel.strftime('%d/%m/%Y')} a las {hora_sel.strftime('%H:%M')}." | |
| ) | |
| st.link_button("📅 Añadir a Google Calendar", link, use_container_width=True) | |
| with st.expander("📋 Resumen para enviar a coordinación GALEA"): | |
| st.code( | |
| f"Lúdica: {nombre_ludica_sel}\n" | |
| f"Día: {fecha_sel.strftime('%d/%m/%Y')}\n" | |
| f"Hora: {hora_sel.strftime('%H:%M')}\n" | |
| f"Duración: {duracion_sel} min\n" | |
| f"Profesor: {nombre_docente_sel}\n" | |
| f"Correo: {correo_docente_sel}\n" | |
| f"Materia: {materia_sel}\n" | |
| f"Participantes: {participantes_sel}\n" | |
| f"Notas: {notas_sel or '—'}", | |
| language=None, | |
| ) | |
| st.caption( | |
| "Si el profesor guarda el evento en Google Calendar, coordinación " | |
| "recibirá la invitación automáticamente como invitado del evento." | |
| ) |