Download app.py from auriolar/giara: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/spaces/auriolar/giara/resolve/main/app.py
- Command line
-
hf download hf://spaces/auriolar/giara/app.py
-
curl -L -o app.py https://huggingface.co/spaces/auriolar/giara/resolve/main/app.py
12.7 kB
| import os | |
| import json | |
| import gradio as gr | |
| import pandas as pd | |
| from datetime import datetime | |
| # --- 1. ZEROGPU --- | |
| try: | |
| import spaces | |
| except ImportError: | |
| class spaces: | |
| def GPU(func): | |
| return func | |
| def inicializar_entorno_gpu(): | |
| print("[INFO] Entorno ZeroGPU verificado.") | |
| return True | |
| inicializar_entorno_gpu() | |
| # --- 2. DETECCIÓN DE PROVEEDORES --- | |
| PROVEEDORES_DISPONIBLES = [] | |
| if os.getenv("GEMINI_API_KEY"): | |
| try: | |
| from google import genai # noqa: F401 | |
| PROVEEDORES_DISPONIBLES.append("Google (Gemini 2.5 Flash)") | |
| except ImportError: | |
| pass | |
| if os.getenv("GROQ_API_KEY"): | |
| try: | |
| from groq import Groq # noqa: F401 | |
| PROVEEDORES_DISPONIBLES.append("Groq (GPT-OSS 120B)") | |
| except ImportError: | |
| pass | |
| if os.getenv("MISTRAL_API_KEY"): | |
| try: | |
| from mistralai import Mistral # noqa: F401 | |
| PROVEEDORES_DISPONIBLES.append("Mistral AI (Mistral Large)") | |
| except ImportError: | |
| pass | |
| if os.getenv("ANTHROPIC_API_KEY"): | |
| try: | |
| from anthropic import Anthropic # noqa: F401 | |
| PROVEEDORES_DISPONIBLES.append("Anthropic (Claude-3.5-Haiku)") | |
| except ImportError: | |
| pass | |
| if os.getenv("OPENAI_API_KEY"): | |
| try: | |
| from openai import OpenAI # noqa: F401 | |
| PROVEEDORES_DISPONIBLES.append("OpenAI (GPT-4o-mini)") | |
| except ImportError: | |
| pass | |
| if not PROVEEDORES_DISPONIBLES: | |
| PROVEEDORES_DISPONIBLES.append("Sin proveedores configurados") | |
| # --- 3. CACHÉ DE CLIENTES (lazy) --- | |
| _CLIENTES = {} | |
| def obtener_cliente(proveedor): | |
| if proveedor in _CLIENTES: | |
| return _CLIENTES[proveedor] | |
| if proveedor == "Google (Gemini 2.5 Flash)": | |
| from google import genai | |
| _CLIENTES[proveedor] = genai.Client() | |
| elif proveedor == "Groq (GPT-OSS 120B)": | |
| from groq import Groq | |
| _CLIENTES[proveedor] = Groq(api_key=os.getenv("GROQ_API_KEY")) | |
| elif proveedor == "Mistral AI (Mistral Large)": | |
| from mistralai import Mistral | |
| _CLIENTES[proveedor] = Mistral(api_key=os.getenv("MISTRAL_API_KEY")) | |
| elif proveedor == "Anthropic (Claude-3.5-Haiku)": | |
| from anthropic import Anthropic | |
| _CLIENTES[proveedor] = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) | |
| elif proveedor == "OpenAI (GPT-4o-mini)": | |
| from openai import OpenAI | |
| _CLIENTES[proveedor] = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| else: | |
| raise ValueError(f"Proveedor desconocido: {proveedor}") | |
| return _CLIENTES[proveedor] | |
| # --- 4. SECRETOS --- | |
| try: | |
| USUARIOS_PERMITIDOS = json.loads(os.getenv("LISTA_ALUMNOS", "{}")) | |
| except Exception as e: | |
| print(f"Error al leer LISTA_ALUMNOS: {e}") | |
| USUARIOS_PERMITIDOS = {} | |
| try: | |
| PERMISOS_USUARIO = json.loads(os.getenv("PERMISOS_USUARIO", "{}")) | |
| except Exception as e: | |
| print(f"Error al leer PERMISOS_USUARIO: {e}") | |
| PERMISOS_USUARIO = {} | |
| try: | |
| ADMIN_USERS = set(json.loads(os.getenv("ADMIN_USERS", "[]"))) | |
| except Exception as e: | |
| print(f"Error al leer ADMIN_USERS: {e}") | |
| ADMIN_USERS = set() | |
| # --- 5. LOG DE USO --- | |
| RUTA_LOG = "/data/usage_log.json" | |
| def cargar_log(): | |
| if not os.path.exists(RUTA_LOG): | |
| return [] | |
| try: | |
| with open(RUTA_LOG, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| except Exception as e: | |
| print(f"Error al cargar log: {e}") | |
| return [] | |
| def guardar_log(log): | |
| try: | |
| os.makedirs(os.path.dirname(RUTA_LOG), exist_ok=True) | |
| with open(RUTA_LOG, "w", encoding="utf-8") as f: | |
| json.dump(log, f, ensure_ascii=False, indent=2) | |
| except Exception as e: | |
| print(f"Error al guardar log: {e}") | |
| def registrar_uso(usuario, proveedor, tokens_in, tokens_out): | |
| log = cargar_log() | |
| log.append({ | |
| "timestamp": datetime.utcnow().isoformat() + "Z", | |
| "user": usuario, | |
| "provider": proveedor, | |
| "tokens_input": tokens_in, | |
| "tokens_output": tokens_out, | |
| }) | |
| guardar_log(log) | |
| # --- 6. LÓGICA DE AUTENTICACIÓN CON VISIBILIDAD DINÁMICA --- | |
| # Los outputs siguen siempre este orden: | |
| # [estado_usuario, lbl_estado, grupo_btn_login, grupo_formulario, grupo_logout, txt_user, txt_pass] | |
| def mostrar_formulario(): | |
| return gr.update(visible=False), gr.update(visible=True) | |
| def cancelar_formulario(): | |
| return gr.update(visible=True), gr.update(visible=False) | |
| def autenticar(usuario, contrasena): | |
| usuario = (usuario or "").strip() | |
| contrasena = (contrasena or "").strip() | |
| if not usuario or not contrasena: | |
| return ( | |
| None, | |
| "⚠️ Introduce usuario y contraseña.", | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(), | |
| gr.update(), | |
| ) | |
| if USUARIOS_PERMITIDOS.get(usuario) != contrasena: | |
| return ( | |
| None, | |
| "❌ Credenciales incorrectas. Revisa tu usuario o pide tu clave al profesor.", | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(), | |
| gr.update(), | |
| ) | |
| return ( | |
| usuario, | |
| f"✅ Bienvenido/a, **{usuario}**.", | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(value=""), | |
| gr.update(value=""), | |
| ) | |
| def cerrar_sesion(): | |
| return ( | |
| None, | |
| "🔒 Sesión cerrada.", | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| gr.update(value=""), | |
| gr.update(value=""), | |
| ) | |
| # --- 7. CHAT --- | |
| def responder_chat(mensaje, historial, proveedor, usuario_autenticado): | |
| if usuario_autenticado is None: | |
| return "⚠️ Debes iniciar sesión antes de chatear." | |
| if usuario_autenticado not in PERMISOS_USUARIO: | |
| return "❌ No tienes permisos configurados. Contacta con el profesor." | |
| if proveedor not in PERMISOS_USUARIO[usuario_autenticado]: | |
| permitidos = ", ".join(PERMISOS_USUARIO[usuario_autenticado]) | |
| return ( | |
| f"❌ No tienes acceso al proveedor '{proveedor}'. " | |
| f"Tus proveedores permitidos: {permitidos}." | |
| ) | |
| try: | |
| cliente = obtener_cliente(proveedor) | |
| if proveedor == "Google (Gemini 2.5 Flash)": | |
| respuesta = cliente.models.generate_content( | |
| model="gemini-2.5-flash", | |
| contents=mensaje, | |
| ) | |
| texto = respuesta.text | |
| tokens_in = respuesta.usage_metadata.prompt_token_count | |
| tokens_out = respuesta.usage_metadata.candidates_token_count | |
| registrar_uso(usuario_autenticado, "Gemini", tokens_in, tokens_out) | |
| return texto | |
| elif proveedor == "Groq (GPT-OSS 120B)": | |
| respuesta = cliente.chat.completions.create( | |
| model="openai/gpt-oss-120b", | |
| messages=[{"role": "user", "content": mensaje}], | |
| ) | |
| texto = respuesta.choices[0].message.content | |
| tokens_in = getattr(respuesta.usage, "prompt_tokens", 0) if hasattr(respuesta, "usage") else 0 | |
| tokens_out = getattr(respuesta.usage, "completion_tokens", 0) if hasattr(respuesta, "usage") else 0 | |
| registrar_uso(usuario_autenticado, "Groq", tokens_in, tokens_out) | |
| return texto | |
| elif proveedor == "Mistral AI (Mistral Large)": | |
| respuesta = cliente.chat.complete( | |
| model="mistral-large-latest", | |
| messages=[{"role": "user", "content": mensaje}], | |
| ) | |
| texto = respuesta.choices[0].message.content | |
| tokens_in = respuesta.usage.prompt_tokens | |
| tokens_out = respuesta.usage.completion_tokens | |
| registrar_uso(usuario_autenticado, "Mistral", tokens_in, tokens_out) | |
| return texto | |
| elif proveedor == "Anthropic (Claude-3.5-Haiku)": | |
| respuesta = cliente.messages.create( | |
| model="claude-3-5-haiku-20241022", | |
| max_tokens=1000, | |
| messages=[{"role": "user", "content": mensaje}], | |
| ) | |
| texto = respuesta.content[0].text | |
| tokens_in = respuesta.usage.input_tokens | |
| tokens_out = respuesta.usage.output_tokens | |
| registrar_uso(usuario_autenticado, "Anthropic", tokens_in, tokens_out) | |
| return texto | |
| elif proveedor == "OpenAI (GPT-4o-mini)": | |
| respuesta = cliente.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[{"role": "user", "content": mensaje}], | |
| ) | |
| texto = respuesta.choices[0].message.content | |
| tokens_in = respuesta.usage.prompt_tokens | |
| tokens_out = respuesta.usage.completion_tokens | |
| registrar_uso(usuario_autenticado, "OpenAI", tokens_in, tokens_out) | |
| return texto | |
| else: | |
| return "❌ Proveedor no disponible." | |
| except Exception as e: | |
| return f"Error al conectar con la IA ({proveedor}): {str(e)}" | |
| # --- 8. INFORME --- | |
| def mostrar_informe(usuario_autenticado): | |
| if usuario_autenticado is None: | |
| return pd.DataFrame({"Aviso": ["Debes iniciar sesión para ver el informe."]}) | |
| if usuario_autenticado not in ADMIN_USERS: | |
| return pd.DataFrame({"Aviso": ["No tienes permisos de administrador."]}) | |
| log = cargar_log() | |
| if not log: | |
| return pd.DataFrame({"Aviso": ["Aún no hay registros de uso."]}) | |
| df = pd.DataFrame(log) | |
| columnas = ["timestamp", "user", "provider", "tokens_input", "tokens_output"] | |
| df = df[[c for c in columnas if c in df.columns]] | |
| return df | |
| # --- 9. INTERFAZ --- | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| estado_usuario = gr.State(None) | |
| gr.Markdown("# 🤖 Laboratorio de IA - Bachillerato") | |
| # 9.1 Grupo A: botón de login (visible al inicio) | |
| with gr.Group(visible=True) as grupo_btn_login: | |
| btn_mostrar_login = gr.Button("🔓 Iniciar sesión", variant="primary", scale=0) | |
| # 9.2 Grupo B: formulario de login (oculto al inicio) | |
| with gr.Group(visible=False) as grupo_formulario: | |
| with gr.Row(): | |
| txt_user = gr.Textbox(label="Usuario", placeholder="ej. alumno1") | |
| txt_pass = gr.Textbox(label="Contraseña", type="password", placeholder="Tu clave secreta") | |
| with gr.Row(): | |
| btn_entrar = gr.Button("Entrar", variant="primary") | |
| btn_cancelar = gr.Button("Cancelar") | |
| # 9.3 Grupo C: sesión activa (oculto al inicio) | |
| with gr.Group(visible=False) as grupo_logout: | |
| btn_logout = gr.Button("🔒 Cerrar sesión") | |
| # Estado / mensajes | |
| lbl_estado = gr.Markdown("🔒 No autenticado") | |
| # --- Eventos de visibilidad --- | |
| btn_mostrar_login.click( | |
| mostrar_formulario, | |
| inputs=[], | |
| outputs=[grupo_btn_login, grupo_formulario], | |
| ) | |
| btn_cancelar.click( | |
| cancelar_formulario, | |
| inputs=[], | |
| outputs=[grupo_btn_login, grupo_formulario], | |
| ) | |
| # --- Autenticación --- | |
| btn_entrar.click( | |
| autenticar, | |
| inputs=[txt_user, txt_pass], | |
| outputs=[ | |
| estado_usuario, | |
| lbl_estado, | |
| grupo_btn_login, | |
| grupo_formulario, | |
| grupo_logout, | |
| txt_user, | |
| txt_pass, | |
| ], | |
| ) | |
| # --- Cierre de sesión --- | |
| btn_logout.click( | |
| cerrar_sesion, | |
| inputs=[], | |
| outputs=[ | |
| estado_usuario, | |
| lbl_estado, | |
| grupo_btn_login, | |
| grupo_formulario, | |
| grupo_logout, | |
| txt_user, | |
| txt_pass, | |
| ], | |
| ) | |
| # --- Pestañas --- | |
| with gr.Tabs(): | |
| with gr.TabItem("💬 Chat"): | |
| selector_ia = gr.Dropdown( | |
| choices=PROVEEDORES_DISPONIBLES, | |
| value=( | |
| PROVEEDORES_DISPONIBLES[0] | |
| if PROVEEDORES_DISPONIBLES != ["Sin proveedores configurados"] | |
| else None | |
| ), | |
| label="Proveedor de IA", | |
| ) | |
| gr.ChatInterface( | |
| fn=responder_chat, | |
| additional_inputs=[selector_ia, estado_usuario], | |
| ) | |
| with gr.TabItem("📊 Administración"): | |
| gr.Markdown("### Informe de consumo (solo administradores)") | |
| btn_refresh = gr.Button("🔄 Actualizar informe") | |
| tabla = gr.Dataframe(label="Registros de uso", interactive=False, wrap=True) | |
| btn_refresh.click(mostrar_informe, [estado_usuario], tabla) | |
| demo.launch() |