File size: 8,010 Bytes
cfdde66
30e793f
 
3be0f14
462e4d6
30e793f
 
 
 
462e4d6
30e793f
 
 
 
462e4d6
 
 
30e793f
 
462e4d6
 
30e793f
 
462e4d6
30e793f
 
 
 
 
 
 
 
462e4d6
30e793f
462e4d6
30e793f
462e4d6
30e793f
462e4d6
 
30e793f
 
 
 
 
 
 
 
 
462e4d6
30e793f
 
 
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
462e4d6
30e793f
 
462e4d6
30e793f
 
 
 
 
3be0f14
462e4d6
 
 
30e793f
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
 
3be0f14
462e4d6
 
 
30e793f
462e4d6
 
 
30e793f
462e4d6
 
30e793f
 
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
462e4d6
 
 
 
30e793f
462e4d6
 
30e793f
462e4d6
 
 
30e793f
462e4d6
 
 
30e793f
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
 
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
462e4d6
 
 
 
 
 
 
30e793f
462e4d6
 
 
 
 
 
30e793f
462e4d6
 
 
 
 
 
 
 
 
 
30e793f
462e4d6
30e793f
462e4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
30e793f
 
 
462e4d6
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
import os
import tempfile
import gradio as gr
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer

import google.generativeai as genai
import fitz  # PyMuPDF
import traceback

# Initialize embedding model
sbert_model = SentenceTransformer('all-MiniLM-L6-v2')

# Get API key from environment
GEMINI_API_KEY = os.getenv('GAPI')

# Data storage
chunks = []
faiss_index = None
embedding_dimension = 384  # all-MiniLM-L6-v2 embedding dimension

def extract_text_from_pdf(pdf_file_path, start_page=None, end_page=None):
    """Extract text from PDF file, optionally from a specific page range."""
    doc = fitz.open(pdf_file_path)
    text = ""
    num_pages_in_doc = doc.page_count

    if start_page is not None and end_page is not None:
        start_idx = start_page - 1
        end_idx = end_page - 1
        if 0 <= start_idx <= end_idx < num_pages_in_doc:
            pages_to_process = range(start_idx, end_idx + 1)
        else:
            pages_to_process = range(num_pages_in_doc)
    else:
        pages_to_process = range(num_pages_in_doc)

    for i in pages_to_process:
        text += doc.load_page(i).get_text()

    doc.close()
    return text, num_pages_in_doc

def chunk_text(text, chunk_size=1000, overlap=200):
    """Split text into overlapping chunks"""
    doc_chunks = []
    for i in range(0, len(text), chunk_size - overlap):
        chunk = text[i:i + chunk_size]
        if len(chunk) > 100:
            doc_chunks.append(chunk)
    return doc_chunks

def create_faiss_index(embeddings):
    """Create FAISS index for fast similarity search."""
    global embedding_dimension
    
    # Normalize embeddings for cosine similarity
    faiss.normalize_L2(embeddings)
    
    # Create index - using IndexFlatIP for cosine similarity
    index = faiss.IndexFlatIP(embedding_dimension)
    index.add(embeddings)
    
    return index

def process_pdf(pdf_file_obj):
    """Process PDF and create FAISS index."""
    global chunks, faiss_index

    if not GEMINI_API_KEY:
        return None, [["System", "⚠️ GAPI environment variable not set. Please configure your Gemini API key."]]
    
    if pdf_file_obj is None:
        return None, [["System", "πŸ“„ Please upload a PDF file."]]

    try:
        # Save uploaded file temporarily
        with open(pdf_file_obj.name, "rb") as f_in:
            pdf_bytes = f_in.read()
        with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp:
            tmp.write(pdf_bytes)
            tmp_path = tmp.name

        # Extract text
        text, total_pages = extract_text_from_pdf(tmp_path)
        
        if not text.strip():
            return None, [["System", "⚠️ No text found in the PDF. Please try a different file."]]

        # Create chunks
        current_chunks = chunk_text(text)
        if not current_chunks:
            return None, [["System", "⚠️ Could not create text chunks from the PDF."]]

        # Generate embeddings
        current_embeddings = sbert_model.encode(current_chunks)
        current_embeddings = np.array(current_embeddings, dtype=np.float32)
        
        # Create FAISS index
        current_index = create_faiss_index(current_embeddings)
        
        # Update global storage
        chunks = current_chunks
        faiss_index = current_index

        pdf_name = os.path.basename(pdf_file_obj.name)
        success_msg = f"βœ… Successfully processed '{pdf_name}' ({total_pages} pages, {len(chunks)} chunks). FAISS index created! You can now ask questions!"
        
        # Clean up
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)
            
        return None, [["System", success_msg]]

    except Exception as e:
        chunks = []
        faiss_index = None
        error_msg = f"❌ Error processing PDF: {str(e)}"
        return None, [["System", error_msg]]

def retrieve_relevant_chunks(query, top_k=3):
    """Retrieve most relevant chunks using FAISS search."""
    global chunks, faiss_index

    if not chunks or faiss_index is None:
        return []

    try:
        # Encode query
        query_embedding = sbert_model.encode([query])
        query_embedding = np.array(query_embedding, dtype=np.float32)
        
        # Normalize for cosine similarity
        faiss.normalize_L2(query_embedding)
        
        # Search using FAISS
        scores, indices = faiss_index.search(query_embedding, top_k)
        
        # Get top chunks
        top_chunks = []
        for idx in indices[0]:
            if idx < len(chunks):  # Safety check
                top_chunks.append(chunks[idx])
        
        return top_chunks
    
    except Exception as e:
        print(f"Error in FAISS search: {str(e)}")
        return []

def chat_fn(message, history):
    """Handle chat interaction."""
    if not message.strip():
        return history, ""

    # Add user message to history
    history = history + [[message, None]]

    if not GEMINI_API_KEY:
        history[-1][1] = "⚠️ GAPI environment variable not set. Please configure your Gemini API key."
        return history, ""

    if not chunks or faiss_index is None:
        history[-1][1] = "πŸ“„ Please upload and process a PDF document first."
        return history, ""

    try:
        # Configure Gemini
        genai.configure(api_key=GEMINI_API_KEY)
        
        # Get relevant context using FAISS
        context_chunks = retrieve_relevant_chunks(message, top_k=5)
        if not context_chunks:
            history[-1][1] = "❌ Could not find relevant information in the document."
            return history, ""

        # Generate response
        context = "\n\n".join(context_chunks)
        prompt = f"""Based on the following context from the document, answer the user's question.
Context:
{context}
Question: {message}
Please provide a clear, accurate answer based only on the information in the context. If the context doesn't contain enough information to answer the question, say so."""

        model = genai.GenerativeModel('gemini-1.5-flash-latest')
        response = model.generate_content(prompt)
        
        history[-1][1] = response.text

    except Exception as e:
        history[-1][1] = f"❌ Error: {str(e)}"

    return history, ""

# Custom CSS for better chat appearance
css = """
.gradio-container {
    max-width: 800px !important;
    margin: auto !important;
}
.chat-message {
    padding: 10px !important;
    margin: 5px 0 !important;
    border-radius: 10px !important;
}
"""

with gr.Blocks(css=css, title="πŸ“š Chat with Your PDF") as demo:
    
    gr.Markdown(f"""
    # πŸ“š Chat with Your PDF (FAISS-Powered)
    Upload a PDF document and chat with it naturally. Now with FAISS for faster vector search!
    
    {"βœ… API Key: Configured from environment" if GEMINI_API_KEY else "❌ API Key: Not found in GAPI environment variable"}
    """)
    
    pdf_input = gr.File(
        label="πŸ“„ Upload PDF", 
        file_types=['.pdf']
    )
    
    # Chat interface
    chatbot = gr.Chatbot(
        label="πŸ’¬ Chat",
        height=500,
        show_label=False,
        bubble_full_width=False
    )
    
    msg_input = gr.Textbox(
        label="Message",
        placeholder="Ask anything about your PDF...",
        show_label=False,
        container=False
    )
    
    with gr.Row():
        submit_btn = gr.Button("Send πŸ’¬", variant="primary")
        clear_btn = gr.Button("Clear Chat πŸ—‘οΈ")
    
    # Event handlers
    pdf_input.upload(
        fn=process_pdf,
        inputs=[pdf_input],
        outputs=[msg_input, chatbot]
    )
    
    submit_btn.click(
        fn=chat_fn,
        inputs=[msg_input, chatbot],
        outputs=[chatbot, msg_input]
    )
    
    msg_input.submit(
        fn=chat_fn,
        inputs=[msg_input, chatbot],
        outputs=[chatbot, msg_input]
    )
    
    clear_btn.click(
        fn=lambda: ([], ""),
        outputs=[chatbot, msg_input]
    )

if __name__ == "__main__":
    demo.launch(share=True)