File size: 14,501 Bytes
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
8f04eb5
a809248
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
2688667
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2688667
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f04eb5
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2688667
a809248
 
 
 
 
 
8f04eb5
 
 
 
a809248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""
Gradio Web UI for Multimodal RAG System.
Provides a visual interface for document upload and Q&A.
"""

import gradio as gr
import tempfile
import shutil
from pathlib import Path
from typing import List, Tuple, Generator

# Add parent to path
import sys
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from src.preprocessing import PDFParser, TextChunker
from src.embeddings import CustomEmbedder
from src.retrieval import FAISSVectorStore, Document, HybridRetriever, RAGPipeline
from src.utils import get_logger

logger = get_logger(__name__)

# Global state
vector_store = None
rag_pipeline = None
embedder = None

def initialize_system(model_name: str = "qwen2") -> str:
    """Initialize the RAG system components."""
    global vector_store, rag_pipeline, embedder
    
    try:
        embedder = CustomEmbedder()
        vector_store = FAISSVectorStore(embedding_dim=embedder.embedding_dim)
        
        retriever = HybridRetriever(
            dense_retriever=vector_store,
            embedder=embedder
        )
        
        rag_pipeline = RAGPipeline(
            retriever=retriever,
            model_name=model_name
        )
        
        return f"[OK] System initialized with model: {model_name}"
    except Exception as e:
        return f"[ERROR] Initialization failed: {str(e)}"


def ingest_documents(files: List[tempfile.SpooledTemporaryFile]) -> str:
    """Process uploaded documents."""
    global vector_store, embedder, rag_pipeline
    
    # Auto-initialize if not done
    if vector_store is None or embedder is None:
        embedder = CustomEmbedder()
        vector_store = FAISSVectorStore(embedding_dim=embedder.embedding_dim)
    
    if not files:
        return "[ERROR] No files uploaded!"
    
    try:
        pdf_parser = PDFParser()
        chunker = TextChunker(chunk_size=512, chunk_overlap=50)
        all_chunks = []
        
        for file in files:
            file_path = Path(file.name)
            
            if file_path.suffix.lower() == ".pdf":
                doc = pdf_parser.parse(file_path)
                for page in doc.pages:
                    chunks = chunker.chunk(page.text)
                    for chunk in chunks:
                        chunk.metadata["source_file"] = file_path.name
                        chunk.metadata["page_number"] = page.page_number
                        all_chunks.append(chunk)
        
        if not all_chunks:
            return "[ERROR] No text extracted from documents!"
        
        # Generate embeddings
        texts = [c.text for c in all_chunks]
        embeddings = embedder.encode(texts, show_progress=True)
        
        # Create documents
        documents = [
            Document(
                id=c.chunk_id,
                text=c.text,
                embedding=embeddings[i],
                metadata=c.metadata
            )
            for i, c in enumerate(all_chunks)
        ]
        
        vector_store.add_documents(documents)
        
        # Auto-initialize RAG pipeline
        from src.retrieval import SparseRetriever, DenseRetriever
        
        # Wrap vector_store with DenseRetriever
        dense_retriever = DenseRetriever(vector_store=vector_store, embedder=embedder)
        
        sparse_retriever = SparseRetriever()
        sparse_retriever.index_documents(documents)
        
        retriever = HybridRetriever(
            dense_retriever=dense_retriever,
            sparse_retriever=sparse_retriever
        )
        
        rag_pipeline = RAGPipeline(
            retriever=retriever,
            model_name="llama3"
        )
        
        return f"[OK] Ingested {len(documents)} chunks from {len(files)} file(s) - Ready to chat!"
        
    except Exception as e:
        logger.error(f"Ingestion error: {e}")
        return f"[ERROR] Error: {str(e)}"


def query_rag(
    message: str,
    history: List[Tuple[str, str]],
    top_k: int = 5
) -> str:
    """Query the RAG system."""
    global rag_pipeline
    
    if rag_pipeline is None:
        return "[ERROR] Please load an index first (Documents tab → Load Index)!"
    
    if not message.strip():
        return "[ERROR] Please enter a question!"
    
    try:
        logger.info(f"Processing query: {message}")
        
        # Query RAG pipeline
        response = rag_pipeline.query(message, top_k=top_k)
        
        # Format answer with sources
        answer = response.answer
        
        # Add source citations (RAGResponse uses 'citations')
        if response.citations:
            answer += "\n\n---\n**Sources:**\n"
            for i, citation in enumerate(response.citations[:3], 1):
                text_preview = citation.text_snippet[:150].replace("\n", " ") if citation.text_snippet else ""
                source = citation.source_file
                if citation.page:
                    source += f" (p.{citation.page})"
                answer += f"\n[{i}] **{source}**: {text_preview}..."
        
        return answer
        
    except Exception as e:
        import traceback
        logger.error(f"Query error: {e}")
        logger.error(traceback.format_exc())
        return f"[ERROR] Error: {str(e)}"


def query_rag_streaming(
    message: str,
    history: List[Tuple[str, str]],
    top_k: int = 5
) -> Generator[str, None, None]:
    """Query the RAG system with streaming response."""
    global rag_pipeline
    
    if rag_pipeline is None:
        yield "[ERROR] Please load an index first (Documents tab → Load Index)!"
        return
    
    if not message.strip():
        yield "[ERROR] Please enter a question!"
        return
    
    try:
        logger.info(f"Processing streaming query: {message}")
        
        # Show thinking indicator
        yield "Searching documents..."
        
        # Get response (we simulate streaming by yielding partial content)
        response = rag_pipeline.query(message, top_k=top_k)
        
        # Stream the answer word by word for effect
        answer = response.answer
        words = answer.split()
        partial = ""
        
        for i, word in enumerate(words):
            partial += word + " "
            if i % 5 == 0:  # Update every 5 words
                yield partial
        
        # Add sources at the end
        if response.citations:
            sources = "\n\n---\n**Sources:**\n"
            for i, citation in enumerate(response.citations[:3], 1):
                text_preview = citation.text_snippet[:150].replace("\n", " ") if citation.text_snippet else ""
                source = citation.source_file
                if citation.page:
                    source += f" (p.{citation.page})"
                sources += f"\n[{i}] **{source}**: {text_preview}..."
            
            yield partial + sources
        else:
            yield partial
            
    except Exception as e:
        logger.error(f"Streaming query error: {e}")
        yield f"[ERROR] Error: {str(e)}"


def export_conversation(history: List[dict]) -> str:
    """Export conversation history to markdown."""
    if not history:
        return "No conversation to export."
    
    markdown = "# RAG Conversation Export\n\n"
    markdown += f"*Exported on: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M')}*\n\n"
    markdown += "---\n\n"
    
    for msg in history:
        role = msg.get("role", "unknown")
        content = msg.get("content", "")
        
        if role == "user":
            markdown += f"## Question\n\n{content}\n\n"
        else:
            markdown += f"## Answer\n\n{content}\n\n"
        
        markdown += "---\n\n"
    
    return markdown


def save_export(history: List[dict]) -> str:
    """Save conversation export to file."""
    import tempfile
    from datetime import datetime
    
    markdown = export_conversation(history)
    
    filename = f"rag_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
    filepath = Path(tempfile.gettempdir()) / filename
    
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(markdown)
    
    return str(filepath)


def load_existing_index(index_path: str) -> str:
    """Load an existing FAISS index."""
    global vector_store, rag_pipeline, embedder
    
    try:
        path = Path(index_path)
        if not path.exists():
            return f"[ERROR] Index path not found: {index_path}"
        
        embedder = CustomEmbedder()
        vector_store = FAISSVectorStore(embedding_dim=embedder.embedding_dim)
        vector_store.load(index_path)
        
        # Import SparseRetriever for hybrid search
        from src.retrieval import SparseRetriever, DenseRetriever
        
        # Wrap vector_store with DenseRetriever
        dense_retriever = DenseRetriever(vector_store=vector_store, embedder=embedder)
        
        # Get documents for sparse indexing
        docs = vector_store.get_all_documents()
        sparse_retriever = SparseRetriever()
        sparse_retriever.index_documents(docs)
        
        retriever = HybridRetriever(
            dense_retriever=dense_retriever,
            sparse_retriever=sparse_retriever
        )
        
        rag_pipeline = RAGPipeline(
            retriever=retriever,
            model_name="llama3"
        )
        
        # PRELOAD the LLM to avoid threading issues during query
        logger.info("Preloading LLM (this takes 30-60 seconds)...")
        rag_pipeline._load_llm()
        logger.info("LLM preloaded successfully!")
        
        return f"[OK] Loaded index from {index_path} ({vector_store.count} documents) - Ready to chat!"
        
    except Exception as e:
        import traceback
        logger.error(traceback.format_exc())
        return f"[ERROR] Error loading index: {str(e)}"


# Create Gradio interface
def create_ui():
    """Create the Gradio interface."""
    
    with gr.Blocks(
        title="Multimodal RAG System"
    ) as demo:
        gr.Markdown("""
        # Multimodal RAG System
        ### Intelligent Document Q&A with Citations
        """)
        
        with gr.Tab("Chat"):
            with gr.Row():
                with gr.Column(scale=3):
                    chatbot = gr.Chatbot(
                        label="Conversation",
                        height=500
                    )
                    msg = gr.Textbox(
                        label="Your Question",
                        placeholder="Ask a question about your documents...",
                        lines=2
                    )
                    with gr.Row():
                        submit_btn = gr.Button("Send", variant="primary")
                        clear_btn = gr.Button("Clear")
                
                with gr.Column(scale=1):
                    gr.Markdown("### Settings")
                    top_k = gr.Slider(
                        minimum=1,
                        maximum=10,
                        value=5,
                        step=1,
                        label="Number of Sources"
                    )
                    model_select = gr.Dropdown(
                        choices=["llama3", "mistral", "qwen2", "phi3", "flan-t5"],
                        value="llama3",
                        label="LLM Model"
                    )
                    init_btn = gr.Button("Initialize System", variant="secondary")
                    init_status = gr.Textbox(label="Status", interactive=False)
            
            # Chat handlers (Gradio 6.x format)
            def respond(message, chat_history, top_k):
                chat_history = chat_history or []
                response = query_rag(message, chat_history, top_k)
                # Gradio 6.x uses dict format
                chat_history.append({"role": "user", "content": message})
                chat_history.append({"role": "assistant", "content": response})
                return "", chat_history
            
            submit_btn.click(respond, [msg, chatbot, top_k], [msg, chatbot])
            msg.submit(respond, [msg, chatbot, top_k], [msg, chatbot])
            clear_btn.click(lambda: [], None, chatbot)
            init_btn.click(initialize_system, [model_select], [init_status])
        
        with gr.Tab("Documents"):
            gr.Markdown("### Upload Documents")
            
            file_upload = gr.File(
                label="Upload PDFs",
                file_types=[".pdf"],
                file_count="multiple"
            )
            upload_btn = gr.Button("Process Documents", variant="primary")
            upload_status = gr.Textbox(label="Upload Status", interactive=False)
            
            upload_btn.click(ingest_documents, [file_upload], [upload_status])
            
            gr.Markdown("---")
            gr.Markdown("### Or Load Existing Index")
            
            index_path = gr.Textbox(
                label="Index Path",
                value="artifacts/index",
                placeholder="Path to saved FAISS index"
            )
            load_btn = gr.Button("Load Index")
            load_status = gr.Textbox(label="Load Status", interactive=False)
            
            load_btn.click(load_existing_index, [index_path], [load_status])
        
        with gr.Tab("About"):
            gr.Markdown("""
            ## About This System
            
            This is a **Multimodal RAG (Retrieval-Augmented Generation)** system for document intelligence.
            
            ### Features
            - **PDF Document Processing** - Extract text from PDFs
            - **Hybrid Search** - Combines dense vectors + BM25
            - **LLM-Powered Answers** - Generates responses with citations
            - **GPU Accelerated** - Fast inference with CUDA
            
            ### How to Use
            1. Go to **Documents** tab and upload PDFs (or load existing index)
            2. Click **Initialize System** in the Chat tab
            3. Ask questions about your documents!
            
            ### Models
            - **Qwen2** (1.5B) - Fast, good quality
            - **Phi-3** (3.8B) - Better quality, slower
            - **Flan-T5** - Lightweight option
            """)
    
    return demo


if __name__ == "__main__":
    demo = create_ui()
    # Enable queue for long-running tasks (LLM loading takes ~30s)
    demo.queue(default_concurrency_limit=1)
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )