File size: 13,181 Bytes
d767722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Gradio UI for UPB RAG Career Exploration Assistant
Optimized for HuggingFace Spaces with better error handling
"""

import os
import gradio as gr
from pathlib import Path
import sys
from dotenv import load_dotenv

# Load environment variables from .env file (for local development)
# HuggingFace Spaces will use Secrets instead
load_dotenv()

# Validate required environment variables
REQUIRED_ENV_VARS = [
    "AZURE_OPENAI_API_KEY",
    "AZURE_OPENAI_ENDPOINT",
    "AZURE_OPENAI_DEPLOYMENT_NAME",
    "AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME",
]

missing_vars = [var for var in REQUIRED_ENV_VARS if not os.getenv(var)]
if missing_vars:
    error_msg = f"""
    ❌ Missing required environment variables: {', '.join(missing_vars)}
    
    Please configure these in HuggingFace Space Settings → Secrets:
    - AZURE_OPENAI_API_KEY
    - AZURE_OPENAI_ENDPOINT
    - AZURE_OPENAI_DEPLOYMENT_NAME
    - AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME
    - AZURE_OPENAI_API_VERSION (optional, defaults to 2024-02-15-preview)
    """
    print(error_msg)
    
    # Create a simple error UI
    def error_interface():
        with gr.Blocks() as demo:
            gr.Markdown("# ⚠️ Configuration Error")
            gr.Markdown(error_msg)
            gr.Markdown("""
            ## How to fix:
            1. Go to your Space settings: https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE/settings
            2. Click on "Secrets" in the left sidebar
            3. Add each required environment variable as a new secret
            4. The Space will automatically rebuild
            """)
        return demo
    
    demo = error_interface()
else:
    # Add src to path
    sys.path.insert(0, str(Path(__file__).parent / "src"))
    
    try:
        from setup_retrieval import setup_retrieval_system
        from rag.chain import UPBRAGChain
        
        # Initialize RAG system
        print("🚀 Initializing UPB RAG System...")
        print(f"📁 Current directory: {os.getcwd()}")
        print(f"🔑 Azure Endpoint: {os.getenv('AZURE_OPENAI_ENDPOINT')[:30]}...")
        
        retriever, vectorstore_manager, chunks = setup_retrieval_system()
        rag_chain = UPBRAGChain(retriever, retrieval_method="hybrid")
        print(f"✅ System ready! Loaded {len(chunks)} chunks from {len(set(doc.metadata.get('source') for doc in chunks if hasattr(doc, 'metadata')))} documents")
        
    except Exception as e:
        import traceback
        error_msg = f"""
        ❌ Error initializing RAG system:
        
        {str(e)}
        
        Full traceback:
        {traceback.format_exc()}
        """
        print(error_msg)
        
        def error_interface():
            with gr.Blocks() as demo:
                gr.Markdown("# ⚠️ Initialization Error")
                gr.Markdown(f"```\n{error_msg}\n```")
            return demo
        
        demo = error_interface()
        raise

    # Custom CSS for better UI
    custom_css = """
    .header {
        text-align: center;
        padding: 20px;
        background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
        color: white;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .header h1 {
        margin: 0;
        font-size: 2.5em;
        font-weight: bold;
    }

    .header p {
        margin: 10px 0 0 0;
        font-size: 1.2em;
        opacity: 0.9;
    }

    .disclaimer {
        background-color: #fef3c7;
        border-left: 4px solid #f59e0b;
        padding: 15px;
        margin: 15px 0;
        border-radius: 5px;
        font-size: 0.9em;
    }

    .footer {
        text-align: center;
        padding: 20px;
        color: #6b7280;
        font-size: 0.9em;
    }

    .chat-message {
        padding: 10px;
        border-radius: 8px;
        margin: 5px 0;
    }

    .source-box {
        background-color: #f3f4f6;
        border-left: 3px solid #3b82f6;
        padding: 10px;
        margin: 10px 0;
        border-radius: 5px;
        font-size: 0.85em;
    }
    """


    def format_sources(sources):
        """Format source citations nicely"""
        if not sources:
            return ""
        
        sources_text = "\n\n---\n\n### 📚 Fuentes consultadas:\n\n"
        
        seen = set()
        for source in sources:
            source_key = (source.get('category', ''), source.get('source', ''))
            if source_key not in seen:
                seen.add(source_key)
                category = source.get('category', 'general').title()
                source_name = source.get('source', 'N/A')
                sources_text += f"- **{category}**: `{source_name}`\n"
        
        return sources_text


    def chat_with_upb(message, history, include_sources):
        """
        Main chat function for Gradio interface
        
        Args:
            message: User's message
            history: Chat history (list of [user_msg, bot_msg] pairs)
            include_sources: Boolean to show source citations
            
        Returns:
            Updated chat history
        """
        if not message or not message.strip():
            return history
        
        try:
            # Get response from RAG chain
            response = rag_chain.invoke(message, include_sources=include_sources)
            
            # Format answer
            answer = response['answer']
            
            # Add sources if requested
            if include_sources and response.get('sources'):
                answer += format_sources(response['sources'])
            
            # Update history
            history.append([message, answer])
            
            return history
        
        except Exception as e:
            import traceback
            error_msg = f"⚠️ Lo siento, ocurrió un error: {str(e)}\n\n```\n{traceback.format_exc()}\n```\n\nPor favor, intenta reformular tu pregunta."
            history.append([message, error_msg])
            return history


    def clear_conversation():
        """Clear chat history"""
        rag_chain.clear_history()
        return []


    def get_example_questions():
        """Return example questions for quick start"""
        return [
            ["¿Qué ingenierías ofrece la UPB?"],
            ["¿Cuáles programas tienen acreditación ABET?"],
            ["Cuéntame sobre Ingeniería de Sistemas"],
            ["¿Qué becas están disponibles?"],
            ["¿Cómo puedo contactar a la UPB?"],
            ["¿Qué es la Ingeniería en Ciencia de Datos?"],
        ]


    # Create Gradio interface
    with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
        
        # Header
        gr.HTML("""
            <div class="header">
                <h1>🎓 UPB Careers Assistant</h1>
                <p>Asistente Virtual para Exploración de Carreras - Universidad Pontificia Bolivariana</p>
            </div>
        """)
        
        # Disclaimer
        gr.HTML("""
            <div class="disclaimer">
                <strong>⚠️ Nota importante:</strong> Este asistente proporciona información general sobre los programas de ingeniería de la UPB. 
                Para información específica sobre matrículas, fechas límite, o detalles particulares del plan de estudios, 
                por favor contacta directamente con la oficina de admisiones de la UPB.
            </div>
        """)
        
        # Main chat interface
        with gr.Row():
            with gr.Column(scale=4):
                chatbot = gr.Chatbot(
                    label="💬 Conversación",
                    height=500,
                    show_label=True,
                    avatar_images=(None, "🎓"),
                    bubble_full_width=False,
                )
                
                with gr.Row():
                    msg = gr.Textbox(
                        label="Tu pregunta",
                        placeholder="Escribe tu pregunta aquí... (ejemplo: ¿Qué ingenierías ofrece la UPB?)",
                        scale=4,
                        lines=2,
                    )
                    submit_btn = gr.Button("Enviar 📤", variant="primary", scale=1)
                
                with gr.Row():
                    clear_btn = gr.Button("🗑️ Limpiar conversación", variant="secondary")
                    sources_checkbox = gr.Checkbox(
                        label="📚 Mostrar fuentes",
                        value=True,
                        info="Incluir referencias a documentos fuente"
                    )
            
            with gr.Column(scale=1):
                gr.Markdown("### 💡 Preguntas de ejemplo")
                gr.Markdown("Haz clic en cualquier pregunta para probarla:")
                
                example_btns = []
                for example in get_example_questions():
                    btn = gr.Button(example[0], size="sm")
                    example_btns.append((btn, example[0]))
        
        # Information section
        with gr.Accordion("ℹ️ Información del Sistema", open=False):
            gr.Markdown(f"""
            ### Acerca de este asistente
            
            Este asistente utiliza **Retrieval-Augmented Generation (RAG)** para proporcionar información precisa 
            sobre los programas de ingeniería de la Universidad Pontificia Bolivariana.
            
            **Características:**
            - 🤖 **LLM**: Azure GPT-4o-mini (temperatura: 0.0 para máxima precisión)
            - 📊 **Base de conocimiento**: {len(chunks)} fragmentos de {len(set(doc.metadata.get('source') for doc in chunks if hasattr(doc, 'metadata')))} documentos
            - 🔍 **Método de búsqueda**: Híbrido (BM25 + Vector con RRF)
            - 📚 **Programas incluidos**: 12 ingenierías
            - ✅ **Información de acreditaciones**: ABET, Alta Calidad
            
            **Temas cubiertos:**
            - Información general sobre la UPB
            - 12 programas de ingeniería (descripción, plan de estudios, perfil profesional)
            - Procesos de inscripción y admisión
            - Becas y financiación
            - Información de contacto
            
            **Limitaciones:**
            - La información está basada en documentos curados manualmente
            - Para detalles específicos de fechas, costos exactos, o cambios recientes, consulta directamente con la UPB
            - El sistema puede no tener información sobre cursos muy específicos del plan de estudios
            
            **Consejos de uso:**
            - Haz preguntas específicas y claras
            - Puedes hacer preguntas de seguimiento (el sistema mantiene el contexto)
            - Usa el botón "Limpiar conversación" para empezar un tema nuevo
            """)
        
        # Statistics
        with gr.Accordion("📊 Estadísticas del Sistema", open=False):
            gr.Markdown(f"""
            - **Total de documentos cargados**: {len(set(doc.metadata.get('source') for doc in chunks if hasattr(doc, 'metadata')))}
            - **Total de fragmentos procesados**: {len(chunks)}
            - **Promedio de caracteres por fragmento**: {sum(len(doc.page_content) for doc in chunks) // len(chunks) if chunks else 0}
            - **Categorías disponibles**: Ingenierías, Información general, Becas, Inscripciones, Contacto
            - **Modelo de embeddings**: Azure text-embedding-3-small
            - **Vector store**: FAISS (CPU)
            """)
        
        # Footer
        gr.HTML("""
            <div class="footer">
                <p>
                    💻 Desarrollado con LangChain, FAISS, y Gradio | 
                    🚀 Desplegado en HuggingFace Spaces | 
                    📧 Universidad Pontificia Bolivariana
                </p>
                <p style="font-size: 0.8em; color: #9ca3af;">
                    Versión 1.0 | Octubre 2025
                </p>
            </div>
        """)
        
        # Event handlers
        def submit_message(message, history, sources):
            return "", chat_with_upb(message, history, sources)
        
        # Submit button
        submit_btn.click(
            submit_message,
            inputs=[msg, chatbot, sources_checkbox],
            outputs=[msg, chatbot],
        )
        
        # Enter key
        msg.submit(
            submit_message,
            inputs=[msg, chatbot, sources_checkbox],
            outputs=[msg, chatbot],
        )
        
        # Clear button
        clear_btn.click(
            clear_conversation,
            outputs=chatbot,
        )
        
        # Example buttons
        for btn, text in example_btns:
            btn.click(
                lambda t=text: (t, ""),
                outputs=[msg, msg],
            ).then(
                submit_message,
                inputs=[msg, chatbot, sources_checkbox],
                outputs=[msg, chatbot],
            )

# Launch configuration
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
    )