Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,255 +1,254 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Aplicacion Gradio para Hugging Face Spaces
|
| 3 |
-
Sistema RAG de ALIA Turismo con Salamandra 7B Instruct
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import gradio as gr
|
| 7 |
-
import os
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
import sys
|
| 10 |
-
import torch
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
|
| 13 |
-
# Configurar paths
|
| 14 |
-
ROOT_DIR = Path(__file__).parent
|
| 15 |
-
sys.path.insert(0, str(ROOT_DIR))
|
| 16 |
-
|
| 17 |
-
# Importar sistema RAG
|
| 18 |
-
from rag_system import RAGLLMSystem
|
| 19 |
-
|
| 20 |
-
# Inicializar sistema RAG (se carga una sola vez)
|
| 21 |
-
print("[ALIA] Inicializando sistema RAG...")
|
| 22 |
-
rag_system = RAGLLMSystem()
|
| 23 |
-
print("[ALIA] Sistema listo!")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def format_sources(sources):
|
| 27 |
-
"""Formatear fuentes para display."""
|
| 28 |
-
if not sources:
|
| 29 |
-
return ""
|
| 30 |
-
|
| 31 |
-
sources_text = "\n\n---\n\n### 📚 Fuentes Consultadas:\n\n"
|
| 32 |
-
for i, source in enumerate(sources, 1):
|
| 33 |
-
sources_text += f"**{i}. {source['filename']}**\n"
|
| 34 |
-
sources_text += f" - Categoría: {source['category']}\n"
|
| 35 |
-
sources_text += f" - Relevancia: {source['score']:.2%}\n\n"
|
| 36 |
-
|
| 37 |
-
return sources_text
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def query_rag(
|
| 41 |
-
question,
|
| 42 |
-
top_k,
|
| 43 |
-
score_threshold,
|
| 44 |
-
max_tokens,
|
| 45 |
-
temperature,
|
| 46 |
-
history
|
| 47 |
-
):
|
| 48 |
-
"""Procesar consulta RAG."""
|
| 49 |
-
|
| 50 |
-
if not question or not question.strip():
|
| 51 |
-
return history, ""
|
| 52 |
-
|
| 53 |
-
# Añadir pregunta del usuario al historial
|
| 54 |
-
history = history + [[question, None]]
|
| 55 |
-
|
| 56 |
-
# Procesar con RAG
|
| 57 |
-
try:
|
| 58 |
-
result = rag_system.query(
|
| 59 |
-
question=question,
|
| 60 |
-
top_k=int(top_k),
|
| 61 |
-
score_threshold=float(score_threshold),
|
| 62 |
-
max_new_tokens=int(max_tokens),
|
| 63 |
-
temperature=float(temperature)
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# Formatear respuesta con fuentes
|
| 67 |
-
answer = result.answer
|
| 68 |
-
sources = format_sources(result.sources)
|
| 69 |
-
full_response = answer + sources
|
| 70 |
-
|
| 71 |
-
# Añadir métricas
|
| 72 |
-
metrics = f"\n\n---\n\n⏱️ **Tiempos**: Búsqueda: {result.retrieval_time:.2f}s | Generación: {result.generation_time:.2f}s | Total: {result.total_time:.2f}s"
|
| 73 |
-
full_response += metrics
|
| 74 |
-
|
| 75 |
-
# Actualizar historial con respuesta
|
| 76 |
-
history[-1][1] = full_response
|
| 77 |
-
|
| 78 |
-
except Exception as e:
|
| 79 |
-
error_msg = f"❌ Error procesando consulta: {str(e)}"
|
| 80 |
-
history[-1][1] = error_msg
|
| 81 |
-
|
| 82 |
-
return history, ""
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def create_interface():
|
| 86 |
-
"""Crear interface Gradio."""
|
| 87 |
-
|
| 88 |
-
# Detectar dispositivo
|
| 89 |
-
device = "GPU" if torch.cuda.is_available() else "CPU"
|
| 90 |
-
if torch.cuda.is_available():
|
| 91 |
-
gpu_name = torch.cuda.get_device_name(0)
|
| 92 |
-
device_info = f"🟢 {device}: {gpu_name}"
|
| 93 |
-
else:
|
| 94 |
-
device_info = f"🟡 {device}"
|
| 95 |
-
|
| 96 |
-
# Tema personalizado
|
| 97 |
-
theme = gr.themes.Soft(
|
| 98 |
-
primary_hue="blue",
|
| 99 |
-
secondary_hue="green",
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
with gr.Blocks(
|
| 103 |
-
theme=theme,
|
| 104 |
-
title="ALIA Turismo - Asistente RAG",
|
| 105 |
-
css="""
|
| 106 |
-
.gradio-container {max-width: 1200px !important}
|
| 107 |
-
#title {text-align: center; color: #1976D2; font-size: 2.5em; font-weight: 700;}
|
| 108 |
-
#subtitle {text-align: center; color: #666; font-size: 1.1em; margin-bottom: 2em;}
|
| 109 |
-
#device-info {text-align: center; padding: 0.5em; background: #f0f0f0; border-radius: 8px;}
|
| 110 |
-
"""
|
| 111 |
-
) as demo:
|
| 112 |
-
|
| 113 |
-
# Header
|
| 114 |
-
gr.Markdown(
|
| 115 |
-
"""
|
| 116 |
-
<div id="title">🏛️ ALIA Turismo</div>
|
| 117 |
-
<div id="subtitle">Asistente de Planes Estratégicos de Turismo</div>
|
| 118 |
-
""",
|
| 119 |
-
elem_id="header"
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
gr.Markdown(
|
| 123 |
-
f"""
|
| 124 |
-
<div id="device-info">{device_info} | Salamandra 7B Instruct | 499 Documentos Indexados</div>
|
| 125 |
-
"""
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
with gr.Row():
|
| 129 |
-
with gr.Column(scale=3):
|
| 130 |
-
# Chat interface
|
| 131 |
-
chatbot = gr.Chatbot(
|
| 132 |
-
label="Conversación",
|
| 133 |
-
height=500,
|
| 134 |
-
show_label=False,
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
"¿
|
| 153 |
-
"¿
|
| 154 |
-
"¿
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
#
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
**
|
| 213 |
-
**
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
**
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
demo
|
| 250 |
-
demo.
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Aplicacion Gradio para Hugging Face Spaces
|
| 3 |
+
Sistema RAG de ALIA Turismo con Salamandra 7B Instruct
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import sys
|
| 10 |
+
import torch
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
# Configurar paths
|
| 14 |
+
ROOT_DIR = Path(__file__).parent
|
| 15 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 16 |
+
|
| 17 |
+
# Importar sistema RAG
|
| 18 |
+
from rag_system import RAGLLMSystem
|
| 19 |
+
|
| 20 |
+
# Inicializar sistema RAG (se carga una sola vez)
|
| 21 |
+
print("[ALIA] Inicializando sistema RAG...")
|
| 22 |
+
rag_system = RAGLLMSystem()
|
| 23 |
+
print("[ALIA] Sistema listo!")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def format_sources(sources):
|
| 27 |
+
"""Formatear fuentes para display."""
|
| 28 |
+
if not sources:
|
| 29 |
+
return ""
|
| 30 |
+
|
| 31 |
+
sources_text = "\n\n---\n\n### 📚 Fuentes Consultadas:\n\n"
|
| 32 |
+
for i, source in enumerate(sources, 1):
|
| 33 |
+
sources_text += f"**{i}. {source['filename']}**\n"
|
| 34 |
+
sources_text += f" - Categoría: {source['category']}\n"
|
| 35 |
+
sources_text += f" - Relevancia: {source['score']:.2%}\n\n"
|
| 36 |
+
|
| 37 |
+
return sources_text
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def query_rag(
|
| 41 |
+
question,
|
| 42 |
+
top_k,
|
| 43 |
+
score_threshold,
|
| 44 |
+
max_tokens,
|
| 45 |
+
temperature,
|
| 46 |
+
history
|
| 47 |
+
):
|
| 48 |
+
"""Procesar consulta RAG."""
|
| 49 |
+
|
| 50 |
+
if not question or not question.strip():
|
| 51 |
+
return history, ""
|
| 52 |
+
|
| 53 |
+
# Añadir pregunta del usuario al historial
|
| 54 |
+
history = history + [[question, None]]
|
| 55 |
+
|
| 56 |
+
# Procesar con RAG
|
| 57 |
+
try:
|
| 58 |
+
result = rag_system.query(
|
| 59 |
+
question=question,
|
| 60 |
+
top_k=int(top_k),
|
| 61 |
+
score_threshold=float(score_threshold),
|
| 62 |
+
max_new_tokens=int(max_tokens),
|
| 63 |
+
temperature=float(temperature)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Formatear respuesta con fuentes
|
| 67 |
+
answer = result.answer
|
| 68 |
+
sources = format_sources(result.sources)
|
| 69 |
+
full_response = answer + sources
|
| 70 |
+
|
| 71 |
+
# Añadir métricas
|
| 72 |
+
metrics = f"\n\n---\n\n⏱️ **Tiempos**: Búsqueda: {result.retrieval_time:.2f}s | Generación: {result.generation_time:.2f}s | Total: {result.total_time:.2f}s"
|
| 73 |
+
full_response += metrics
|
| 74 |
+
|
| 75 |
+
# Actualizar historial con respuesta
|
| 76 |
+
history[-1][1] = full_response
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
error_msg = f"❌ Error procesando consulta: {str(e)}"
|
| 80 |
+
history[-1][1] = error_msg
|
| 81 |
+
|
| 82 |
+
return history, ""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def create_interface():
|
| 86 |
+
"""Crear interface Gradio."""
|
| 87 |
+
|
| 88 |
+
# Detectar dispositivo
|
| 89 |
+
device = "GPU" if torch.cuda.is_available() else "CPU"
|
| 90 |
+
if torch.cuda.is_available():
|
| 91 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 92 |
+
device_info = f"🟢 {device}: {gpu_name}"
|
| 93 |
+
else:
|
| 94 |
+
device_info = f"🟡 {device}"
|
| 95 |
+
|
| 96 |
+
# Tema personalizado
|
| 97 |
+
theme = gr.themes.Soft(
|
| 98 |
+
primary_hue="blue",
|
| 99 |
+
secondary_hue="green",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
with gr.Blocks(
|
| 103 |
+
theme=theme,
|
| 104 |
+
title="ALIA Turismo - Asistente RAG",
|
| 105 |
+
css="""
|
| 106 |
+
.gradio-container {max-width: 1200px !important}
|
| 107 |
+
#title {text-align: center; color: #1976D2; font-size: 2.5em; font-weight: 700;}
|
| 108 |
+
#subtitle {text-align: center; color: #666; font-size: 1.1em; margin-bottom: 2em;}
|
| 109 |
+
#device-info {text-align: center; padding: 0.5em; background: #f0f0f0; border-radius: 8px;}
|
| 110 |
+
"""
|
| 111 |
+
) as demo:
|
| 112 |
+
|
| 113 |
+
# Header
|
| 114 |
+
gr.Markdown(
|
| 115 |
+
"""
|
| 116 |
+
<div id="title">🏛️ ALIA Turismo</div>
|
| 117 |
+
<div id="subtitle">Asistente de Planes Estratégicos de Turismo</div>
|
| 118 |
+
""",
|
| 119 |
+
elem_id="header"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
gr.Markdown(
|
| 123 |
+
f"""
|
| 124 |
+
<div id="device-info">{device_info} | Salamandra 7B Instruct | 499 Documentos Indexados</div>
|
| 125 |
+
"""
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
with gr.Row():
|
| 129 |
+
with gr.Column(scale=3):
|
| 130 |
+
# Chat interface
|
| 131 |
+
chatbot = gr.Chatbot(
|
| 132 |
+
label="Conversación",
|
| 133 |
+
height=500,
|
| 134 |
+
show_label=False,
|
| 135 |
+
bubble_full_width=False
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
with gr.Row():
|
| 139 |
+
with gr.Column(scale=9):
|
| 140 |
+
question_input = gr.Textbox(
|
| 141 |
+
placeholder="Escribe tu pregunta sobre planes turísticos...",
|
| 142 |
+
show_label=False,
|
| 143 |
+
container=False
|
| 144 |
+
)
|
| 145 |
+
with gr.Column(scale=1, min_width=80):
|
| 146 |
+
submit_btn = gr.Button("Enviar", variant="primary", size="sm")
|
| 147 |
+
|
| 148 |
+
# Ejemplos
|
| 149 |
+
gr.Examples(
|
| 150 |
+
examples=[
|
| 151 |
+
"¿Cuáles son las principales estrategias de turismo sostenible?",
|
| 152 |
+
"¿Cómo se implementa la gobernanza en destinos turísticos inteligentes?",
|
| 153 |
+
"¿Qué indicadores se usan para medir el éxito de los planes turísticos?",
|
| 154 |
+
"¿Cuáles son las mejores prácticas de marketing digital para destinos?",
|
| 155 |
+
],
|
| 156 |
+
inputs=question_input,
|
| 157 |
+
label="💡 Preguntas Sugeridas"
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
clear_btn = gr.Button("🔄 Nueva Conversación", size="sm")
|
| 161 |
+
|
| 162 |
+
with gr.Column(scale=1):
|
| 163 |
+
# Panel de configuración
|
| 164 |
+
gr.Markdown("### ⚙️ Configuración")
|
| 165 |
+
|
| 166 |
+
top_k = gr.Slider(
|
| 167 |
+
minimum=1,
|
| 168 |
+
maximum=10,
|
| 169 |
+
value=5,
|
| 170 |
+
step=1,
|
| 171 |
+
label="Documentos a recuperar",
|
| 172 |
+
info="Cuántos documentos consultar"
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
score_threshold = gr.Slider(
|
| 176 |
+
minimum=0.0,
|
| 177 |
+
maximum=1.0,
|
| 178 |
+
value=0.6,
|
| 179 |
+
step=0.05,
|
| 180 |
+
label="Umbral de relevancia",
|
| 181 |
+
info="Puntuación mínima (0-1)"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
max_tokens = gr.Slider(
|
| 185 |
+
minimum=256,
|
| 186 |
+
maximum=2048,
|
| 187 |
+
value=1024,
|
| 188 |
+
step=256,
|
| 189 |
+
label="Tokens máximos",
|
| 190 |
+
info="Longitud de respuesta"
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
temperature = gr.Slider(
|
| 194 |
+
minimum=0.0,
|
| 195 |
+
maximum=1.0,
|
| 196 |
+
value=0.7,
|
| 197 |
+
step=0.1,
|
| 198 |
+
label="Temperature",
|
| 199 |
+
info="Creatividad (0=conservador, 1=creativo)"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
gr.Markdown("---")
|
| 203 |
+
|
| 204 |
+
# Info
|
| 205 |
+
with gr.Accordion("ℹ️ Acerca de", open=False):
|
| 206 |
+
gr.Markdown(
|
| 207 |
+
"""
|
| 208 |
+
**ALIA Turismo** - Asistente inteligente para consultas sobre
|
| 209 |
+
planes estratégicos de turismo.
|
| 210 |
+
|
| 211 |
+
**Modelo:** Salamandra 7B Instruct (BSC)
|
| 212 |
+
**Documentos:** 499 planes turísticos
|
| 213 |
+
**Idioma:** Español/Catalán
|
| 214 |
+
|
| 215 |
+
**Versión:** 1.1.0
|
| 216 |
+
**Licencia:** Apache 2.0
|
| 217 |
+
|
| 218 |
+
Desarrollado por Barcelona Supercomputing Center
|
| 219 |
+
"""
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Event handlers
|
| 223 |
+
submit_event = submit_btn.click(
|
| 224 |
+
fn=query_rag,
|
| 225 |
+
inputs=[question_input, top_k, score_threshold, max_tokens, temperature, chatbot],
|
| 226 |
+
outputs=[chatbot, question_input],
|
| 227 |
+
queue=True
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
question_input.submit(
|
| 231 |
+
fn=query_rag,
|
| 232 |
+
inputs=[question_input, top_k, score_threshold, max_tokens, temperature, chatbot],
|
| 233 |
+
outputs=[chatbot, question_input],
|
| 234 |
+
queue=True
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
clear_btn.click(
|
| 238 |
+
fn=lambda: ([], ""),
|
| 239 |
+
outputs=[chatbot, question_input],
|
| 240 |
+
queue=False
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return demo
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Crear y lanzar interface
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
demo = create_interface()
|
| 249 |
+
demo.queue(max_size=10)
|
| 250 |
+
demo.launch(
|
| 251 |
+
server_name="0.0.0.0",
|
| 252 |
+
server_port=7860,
|
| 253 |
+
share=False
|
| 254 |
+
)
|
|
|