File size: 10,515 Bytes
963962a
8b82322
6bf8cf3
8b82322
8e70260
 
 
 
2a69036
121c583
8b82322
121c583
ed78dae
6bf8cf3
8b82322
8e70260
5d2bfd3
8e70260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121c583
8e70260
 
 
 
 
 
ed78dae
8e70260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b82322
8e70260
 
 
 
 
3c7eba3
8e70260
 
 
d0a482b
8e70260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121c583
 
 
 
ed78dae
121c583
 
5d2bfd3
121c583
 
8b82322
121c583
 
6bf8cf3
121c583
 
5d2bfd3
121c583
 
 
 
 
 
 
 
8e70260
121c583
963962a
8e70260
121c583
8b82322
121c583
8e70260
121c583
5d2bfd3
121c583
5d2bfd3
121c583
 
 
5d2bfd3
80ff9dd
8e70260
8b82322
 
8e70260
3c7eba3
8e70260
121c583
8e70260
 
8b82322
121c583
8e70260
 
121c583
8e70260
d0a482b
8e70260
121c583
 
 
 
 
 
 
 
8e70260
121c583
8e70260
 
121c583
 
 
d0a482b
8e70260
 
121c583
 
8e70260
 
121c583
8e70260
121c583
8e70260
80ff9dd
 
 
 
 
 
 
 
 
 
 
8b82322
8e70260
 
 
 
 
 
 
121c583
8e70260
 
 
 
 
 
121c583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b82322
6bf8cf3
d0a482b
121c583
d0a482b
8e70260
121c583
 
 
 
 
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
import gradio as gr
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss
import os
import PyPDF2
import docx
import pandas as pd

class PureRAGBot:
    def __init__(self):
        # Embedding model for document search
        self.embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
        self.documents = []
        self.index = None
        self.is_ready = False

    def load_file_content(self, file):
        """Load content from various file types"""
        try:
            if file is None:
                return "Please select a file first."
            
            file_path = file.name
            file_extension = os.path.splitext(file_path)[1].lower()
            
            if file_extension == '.txt':
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                chunks = self.split_text_into_chunks(content)
                
            elif file_extension == '.csv':
                df = pd.read_csv(file_path)
                chunks = self.dataframe_to_chunks(df)
                
            elif file_extension == '.pdf':
                chunks = self.pdf_to_chunks(file_path)
                
            elif file_extension in ['.docx', '.doc']:
                chunks = self.docx_to_chunks(file_path)
                
            else:
                return "Unsupported file format. Please upload TXT, CSV, PDF, or DOCX files."
            
            # Create FAISS index
            if chunks:
                embeddings = self.embedder.encode(chunks)
                self.index = faiss.IndexFlatIP(embeddings.shape[1])
                self.index.add(embeddings.astype('float32'))
                self.documents = chunks
                self.is_ready = True
                return f"βœ… Document successfully loaded! {len(chunks)} content sections indexed. You can now ask questions about this document."
            else:
                return "❌ No readable content found in the file."
                
        except Exception as e:
            return f"❌ Error processing file: {str(e)}"
    
    def split_text_into_chunks(self, text, chunk_size=300):
        """Split text into manageable chunks"""
        sentences = text.split('.')
        chunks = []
        current_chunk = ""
        
        for sentence in sentences:
            sentence = sentence.strip()
            if not sentence:
                continue
                
            if len(current_chunk) + len(sentence) < chunk_size:
                current_chunk += sentence + '. '
            else:
                if current_chunk:
                    chunks.append(current_chunk.strip())
                current_chunk = sentence + '. '
        
        if current_chunk:
            chunks.append(current_chunk.strip())
        
        return chunks if chunks else [text[:500]]
    
    def dataframe_to_chunks(self, df):
        """Convert DataFrame to text chunks"""
        chunks = []
        for idx, row in df.iterrows():
            row_text = " | ".join([str(cell) for cell in row if pd.notna(cell)])
            if len(row_text) > 500:
                row_text = row_text[:500] + "..."
            chunks.append(f"Row {idx+1}: {row_text}")
        return chunks
    
    def pdf_to_chunks(self, file_path):
        """Extract text from PDF"""
        try:
            with open(file_path, 'rb') as file:
                reader = PyPDF2.PdfReader(file)
                text = ""
                for page in reader.pages:
                    text += page.extract_text() + "\n"
                return self.split_text_into_chunks(text)
        except Exception as e:
            return [f"Error reading PDF: {str(e)}"]
    
    def docx_to_chunks(self, file_path):
        """Extract text from DOCX"""
        try:
            doc = docx.Document(file_path)
            text = ""
            for paragraph in doc.paragraphs:
                if paragraph.text.strip():
                    text += paragraph.text + "\n"
            return self.split_text_into_chunks(text)
        except Exception as e:
            return [f"Error reading DOCX: {str(e)}"]
    
    def search_documents(self, query, k=3):
        """Search for relevant documents"""
        if not self.is_ready:
            return []
        
        try:
            query_embedding = self.embedder.encode([query])
            distances, indices = self.index.search(query_embedding.astype('float32'), k)
            
            results = []
            for i, idx in enumerate(indices[0]):
                if idx < len(self.documents):
                    results.append({
                        'content': self.documents[idx],
                        'score': float(distances[0][i])
                    })
            return results
        except Exception as e:
            print(f"Search error: {e}")
            return []
    
    def generate_rag_response(self, query):
        """Generate response purely from document content"""
        if not self.is_ready:
            return "❌ Please upload a document file first to ask questions about its content."
        
        # Search for relevant content
        results = self.search_documents(query)
        
        if not results:
            return f"❌ I couldn't find any information about '{query}' in the uploaded document. Please try rephrasing your question or ask about different content from the document."
        
        # Filter relevant results
        relevant_results = [r for r in results if r['score'] > 0.3]
        
        if not relevant_results:
            return f"❌ The document contains some text, but nothing specifically relevant to '{query}'. Please ask about content that might be in the document."
        
        # Build response from document content
        response = "πŸ“š **Based on your document:**\n\n"
        
        for i, result in enumerate(relevant_results[:3]):  # Show top 3 results
            response += f"**β€’ Section {i+1}:** {result['content']}\n\n"
        
        # Add suggestions
        response += "πŸ’‘ **Tip:** You can ask about:\n- Key topics in the document\n- Specific information you're looking for\n- Summaries of sections\n- Explanations of concepts mentioned"
        
        return response

def create_interface():
    bot = PureRAGBot()
    
    with gr.Blocks(theme=gr.themes.Soft(), title="Document RAG Assistant") as demo:
        gr.Markdown("""
        # πŸ“š Document RAG Assistant
        
        **Pure Document-Based Question Answering**
        
        - **πŸ” Semantic Search**: Find relevant content in your documents
        - **πŸ“– Content-Based Answers**: All answers come directly from your uploaded files
        - **🎯 Precision**: Only answers based on document content
        
        **Note**: This bot only answers questions based on your uploaded documents.
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### πŸ“ Upload Document")
                file_input = gr.File(
                    label="Upload your document",
                    file_types=[".txt", ".csv", ".pdf", ".docx", ".doc"],
                    type="filepath"
                )
                upload_btn = gr.Button("Process Document", variant="primary")
                status = gr.Textbox(
                    label="Status",
                    value="Please upload a document to begin...",
                    interactive=False
                )
                
                gr.Markdown("""
                ### ℹ️ How It Works
                1. Upload any document (TXT, PDF, CSV, DOCX)
                2. Ask questions about the content
                3. Get answers directly from the document
                4. No general knowledge - only document content
                """)
                
            with gr.Column(scale=2):
                gr.Markdown("### πŸ’¬ Ask About Your Document")
                chatbot = gr.Chatbot(
                    height=400,
                    label="Document Q&A",
                    show_copy_button=True,
                    placeholder="Ask questions about your uploaded document content..."
                )
                with gr.Row():
                    question_input = gr.Textbox(
                        label="Your question about the document",
                        placeholder="What would you like to know about this document?",
                        scale=4
                    )
                    send_btn = gr.Button("Search Document", variant="primary", scale=1)
                
                clear_btn = gr.Button("Clear Conversation", variant="secondary")
                
                # gr.Markdown("""
                # ### πŸ’‘ Example Questions:
                # **After uploading a document, try:**
                # - "What is the main topic of this document?"
                # - "Summarize the key points"
                # - "What are the main findings?"
                # - "Explain the methodology used"
                # - "What solutions are proposed?"
                # - "List the key recommendations"
                # - "What data is presented in this report?"
                # """)
        
        def process_file(file):
            return bot.load_file_content(file)
        
        def respond(message, chat_history):
            if not message.strip():
                return "", chat_history
            
            response = bot.generate_rag_response(message)
            chat_history.append((message, response))
            return "", chat_history
        
        def clear_chat():
            return []
        
        # Event handlers
        upload_btn.click(
            process_file,
            inputs=[file_input],
            outputs=[status]
        )
        
        question_input.submit(
            respond,
            inputs=[question_input, chatbot],
            outputs=[question_input, chatbot]
        )
        
        send_btn.click(
            respond,
            inputs=[question_input, chatbot],
            outputs=[question_input, chatbot]
        )
        
        clear_btn.click(
            clear_chat,
            outputs=[chatbot]
        )
    
    return demo

# Launch the application
if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        share=True,
        server_name="0.0.0.0",
        show_error=True
    )