Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import os
|
|
| 6 |
import PyPDF2
|
| 7 |
import docx
|
| 8 |
import pandas as pd
|
|
|
|
| 9 |
|
| 10 |
class SmartRAGBot:
|
| 11 |
def __init__(self):
|
|
@@ -15,35 +16,65 @@ class SmartRAGBot:
|
|
| 15 |
self.index = None
|
| 16 |
self.is_ready = False
|
| 17 |
|
| 18 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
self.general_responses = {
|
| 20 |
"greeting": [
|
| 21 |
-
"Hello! How can I
|
| 22 |
"Hi there! What would you like to know?",
|
| 23 |
-
"Greetings! I'm here to
|
|
|
|
| 24 |
],
|
| 25 |
"thanks": [
|
| 26 |
"You're welcome!",
|
| 27 |
"Happy to help!",
|
| 28 |
-
"Glad I could assist you!"
|
|
|
|
| 29 |
],
|
| 30 |
"identity": [
|
| 31 |
-
"I'm an AI assistant that can answer questions about your uploaded documents.",
|
| 32 |
-
"I'm a document Q&A bot that
|
| 33 |
-
"I'm here to help you
|
| 34 |
],
|
| 35 |
"capabilities": [
|
| 36 |
-
"I can
|
| 37 |
-
"I help
|
| 38 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
],
|
| 40 |
"default": [
|
| 41 |
-
"I
|
| 42 |
-
"That's
|
| 43 |
-
"I
|
|
|
|
| 44 |
]
|
| 45 |
}
|
| 46 |
-
|
| 47 |
def load_file_content(self, file):
|
| 48 |
"""Load content from various file types"""
|
| 49 |
try:
|
|
@@ -165,68 +196,110 @@ class SmartRAGBot:
|
|
| 165 |
return []
|
| 166 |
|
| 167 |
def detect_query_type(self, query):
|
| 168 |
-
"""
|
| 169 |
-
query_lower = query.lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
# Greeting detection
|
| 172 |
-
greetings = ['hello', 'hi', 'hey', '
|
| 173 |
if any(greet in query_lower for greet in greetings):
|
| 174 |
return "greeting"
|
| 175 |
|
| 176 |
# Thanks detection
|
| 177 |
-
thanks_words = ['thank', 'thanks', '
|
| 178 |
if any(word in query_lower for word in thanks_words):
|
| 179 |
return "thanks"
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
# Identity questions
|
| 182 |
-
identity_words = ['who are you', 'what are you', 'your name', '
|
| 183 |
if any(word in query_lower for word in identity_words):
|
| 184 |
return "identity"
|
| 185 |
|
| 186 |
# Capability questions
|
| 187 |
-
capability_words = ['what can you do', 'help', 'capabilities', '
|
| 188 |
if any(word in query_lower for word in capability_words):
|
| 189 |
return "capabilities"
|
| 190 |
|
| 191 |
return "document"
|
| 192 |
|
| 193 |
-
def get_general_response(self, query_type):
|
| 194 |
"""Get appropriate general response"""
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
responses = self.general_responses.get(query_type, self.general_responses["default"])
|
| 197 |
return random.choice(responses)
|
| 198 |
|
| 199 |
def generate_response(self, query):
|
| 200 |
"""Generate appropriate response based on query type"""
|
| 201 |
-
# First check
|
| 202 |
query_type = self.detect_query_type(query)
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
|
|
|
| 206 |
|
| 207 |
# If it's a document question but no file is loaded
|
| 208 |
if not self.is_ready:
|
| 209 |
-
return "Please upload a document file first to ask questions about its content."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
# Search in document content
|
| 212 |
results = self.search_documents(query)
|
| 213 |
|
| 214 |
if not results:
|
| 215 |
-
# No relevant content found in document
|
| 216 |
-
return (f"I couldn't find specific information about '{query}' in your document.
|
| 217 |
-
"This might be outside the document's scope. "
|
| 218 |
-
"
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
# Check if the results are actually relevant (score threshold)
|
| 221 |
relevant_results = [r for r in results if r['score'] > 0.3]
|
| 222 |
|
| 223 |
if not relevant_results:
|
| 224 |
-
return (f"The document doesn't
|
| 225 |
-
"
|
| 226 |
-
"
|
|
|
|
|
|
|
| 227 |
|
| 228 |
# Build response from relevant document content
|
| 229 |
-
response = "Based on your document:\n\n"
|
| 230 |
for i, result in enumerate(relevant_results[:2]): # Show top 2 results
|
| 231 |
response += f"β’ {result['content']}\n\n"
|
| 232 |
|
|
@@ -238,52 +311,65 @@ def create_interface():
|
|
| 238 |
with gr.Blocks(theme=gr.themes.Soft(), title="Smart Document Assistant") as demo:
|
| 239 |
gr.Markdown("""
|
| 240 |
# π€ Smart Document Assistant
|
|
|
|
| 241 |
**Upload your file and ask any questions!**
|
| 242 |
-
|
| 243 |
-
-
|
| 244 |
-
-
|
|
|
|
|
|
|
|
|
|
| 245 |
""")
|
| 246 |
|
| 247 |
with gr.Row():
|
| 248 |
with gr.Column(scale=1):
|
| 249 |
gr.Markdown("### π File Upload")
|
| 250 |
file_input = gr.File(
|
| 251 |
-
label="
|
| 252 |
file_types=[".txt", ".csv", ".pdf", ".docx", ".doc"],
|
| 253 |
type="filepath"
|
| 254 |
)
|
| 255 |
upload_btn = gr.Button("Process File", variant="primary")
|
| 256 |
status = gr.Textbox(
|
| 257 |
label="Status",
|
| 258 |
-
value="
|
| 259 |
interactive=False
|
| 260 |
)
|
| 261 |
|
| 262 |
with gr.Column(scale=2):
|
| 263 |
-
gr.Markdown("### π¬
|
| 264 |
chatbot = gr.Chatbot(
|
| 265 |
height=400,
|
| 266 |
-
label="
|
| 267 |
-
show_copy_button=True
|
|
|
|
| 268 |
)
|
| 269 |
with gr.Row():
|
| 270 |
question_input = gr.Textbox(
|
| 271 |
-
label="
|
| 272 |
-
placeholder="
|
| 273 |
scale=4
|
| 274 |
)
|
| 275 |
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 276 |
|
| 277 |
-
clear_btn = gr.Button("
|
| 278 |
|
| 279 |
# Example questions
|
| 280 |
gr.Markdown("""
|
| 281 |
-
### π‘
|
| 282 |
-
|
|
|
|
| 283 |
- "What is the main topic of this document?"
|
| 284 |
- "Tell me about the key points"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
-
**
|
| 287 |
- "Hello, how are you?"
|
| 288 |
- "What can you do?"
|
| 289 |
- "Thank you for your help!"
|
|
|
|
| 6 |
import PyPDF2
|
| 7 |
import docx
|
| 8 |
import pandas as pd
|
| 9 |
+
import random
|
| 10 |
|
| 11 |
class SmartRAGBot:
|
| 12 |
def __init__(self):
|
|
|
|
| 16 |
self.index = None
|
| 17 |
self.is_ready = False
|
| 18 |
|
| 19 |
+
# Enhanced general knowledge base
|
| 20 |
+
self.general_knowledge = {
|
| 21 |
+
"capital of india": "The capital of India is New Delhi.",
|
| 22 |
+
"capital of india?": "New Delhi is the capital of India.",
|
| 23 |
+
"what is capital of india": "The capital of India is New Delhi.",
|
| 24 |
+
"capital of usa": "The capital of USA is Washington D.C.",
|
| 25 |
+
"capital of uk": "The capital of United Kingdom is London.",
|
| 26 |
+
"capital of japan": "The capital of Japan is Tokyo.",
|
| 27 |
+
"current prime minister of india": "The current Prime Minister of India is Narendra Modi.",
|
| 28 |
+
"current president of india": "The current President of India is Droupadi Murmu.",
|
| 29 |
+
"population of india": "India's population is approximately 1.4 billion people.",
|
| 30 |
+
"currency of india": "The currency of India is Indian Rupee (βΉ).",
|
| 31 |
+
"largest city in india": "Mumbai is the largest city in India by population.",
|
| 32 |
+
"who is prime minister of india": "Narendra Modi is the Prime Minister of India.",
|
| 33 |
+
"who is president of india": "Droupadi Murmu is the President of India.",
|
| 34 |
+
"national animal of india": "The national animal of India is the Bengal Tiger.",
|
| 35 |
+
"national bird of india": "The national bird of India is the Peacock.",
|
| 36 |
+
"independence day of india": "India's Independence Day is on August 15th.",
|
| 37 |
+
"republic day of india": "India's Republic Day is on January 26th."
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# Enhanced general responses
|
| 41 |
self.general_responses = {
|
| 42 |
"greeting": [
|
| 43 |
+
"Hello! How can I assist you today?",
|
| 44 |
"Hi there! What would you like to know?",
|
| 45 |
+
"Greetings! I'm here to help you with both document questions and general knowledge.",
|
| 46 |
+
"Welcome! How can I help you today?"
|
| 47 |
],
|
| 48 |
"thanks": [
|
| 49 |
"You're welcome!",
|
| 50 |
"Happy to help!",
|
| 51 |
+
"Glad I could assist you!",
|
| 52 |
+
"My pleasure! Let me know if you need anything else."
|
| 53 |
],
|
| 54 |
"identity": [
|
| 55 |
+
"I'm an AI assistant that can answer questions about your uploaded documents and also provide general knowledge information.",
|
| 56 |
+
"I'm a smart document Q&A bot that can answer questions about your files and general knowledge topics.",
|
| 57 |
+
"I'm here to help you find information in your files and answer general knowledge questions."
|
| 58 |
],
|
| 59 |
"capabilities": [
|
| 60 |
+
"I can: Read your files (TXT, PDF, Word, CSV) and answer questions about them, Answer general knowledge questions, Have conversations in English",
|
| 61 |
+
"I help with: Document analysis, General knowledge, Casual conversation",
|
| 62 |
+
"My capabilities include: Document Q&A, General knowledge responses, File content analysis"
|
| 63 |
+
],
|
| 64 |
+
"how_are_you": [
|
| 65 |
+
"I'm doing great! Ready to help you with your questions.",
|
| 66 |
+
"I'm functioning perfectly! What can I help you with today?",
|
| 67 |
+
"I'm running smoothly and ready to assist you!",
|
| 68 |
+
"All systems go! How can I assist you?"
|
| 69 |
],
|
| 70 |
"default": [
|
| 71 |
+
"I can help you with that! But I'm even better at answering questions about your uploaded documents.",
|
| 72 |
+
"That's an interesting question! I specialize in document Q&A, but I'll do my best to help.",
|
| 73 |
+
"I can answer that! Feel free to upload a document if you have specific questions about its content.",
|
| 74 |
+
"I'd be happy to help with that question!"
|
| 75 |
]
|
| 76 |
}
|
| 77 |
+
|
| 78 |
def load_file_content(self, file):
|
| 79 |
"""Load content from various file types"""
|
| 80 |
try:
|
|
|
|
| 196 |
return []
|
| 197 |
|
| 198 |
def detect_query_type(self, query):
|
| 199 |
+
"""Enhanced query type detection"""
|
| 200 |
+
query_lower = query.lower().strip()
|
| 201 |
+
|
| 202 |
+
# Check general knowledge first
|
| 203 |
+
if query_lower in self.general_knowledge:
|
| 204 |
+
return "general_knowledge"
|
| 205 |
+
|
| 206 |
+
# Check for general knowledge patterns
|
| 207 |
+
general_patterns = [
|
| 208 |
+
'capital of', 'population of', 'currency of', 'prime minister of',
|
| 209 |
+
'president of', 'largest city in', 'what is', 'who is', 'when is',
|
| 210 |
+
'where is', 'how many', 'full form of', 'national animal',
|
| 211 |
+
'national bird', 'independence day', 'republic day'
|
| 212 |
+
]
|
| 213 |
+
if any(pattern in query_lower for pattern in general_patterns):
|
| 214 |
+
return "general_knowledge"
|
| 215 |
|
| 216 |
# Greeting detection
|
| 217 |
+
greetings = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening']
|
| 218 |
if any(greet in query_lower for greet in greetings):
|
| 219 |
return "greeting"
|
| 220 |
|
| 221 |
# Thanks detection
|
| 222 |
+
thanks_words = ['thank', 'thanks', 'thankyou', 'thank you']
|
| 223 |
if any(word in query_lower for word in thanks_words):
|
| 224 |
return "thanks"
|
| 225 |
|
| 226 |
+
# How are you detection
|
| 227 |
+
how_are_you = ['how are you', 'how do you do', 'how is it going']
|
| 228 |
+
if any(phrase in query_lower for phrase in how_are_you):
|
| 229 |
+
return "how_are_you"
|
| 230 |
+
|
| 231 |
# Identity questions
|
| 232 |
+
identity_words = ['who are you', 'what are you', 'your name', 'introduce yourself']
|
| 233 |
if any(word in query_lower for word in identity_words):
|
| 234 |
return "identity"
|
| 235 |
|
| 236 |
# Capability questions
|
| 237 |
+
capability_words = ['what can you do', 'help', 'capabilities', 'features']
|
| 238 |
if any(word in query_lower for word in capability_words):
|
| 239 |
return "capabilities"
|
| 240 |
|
| 241 |
return "document"
|
| 242 |
|
| 243 |
+
def get_general_response(self, query_type, original_query=""):
|
| 244 |
"""Get appropriate general response"""
|
| 245 |
+
if query_type == "general_knowledge":
|
| 246 |
+
# Try exact match first
|
| 247 |
+
if original_query.lower() in self.general_knowledge:
|
| 248 |
+
return self.general_knowledge[original_query.lower()]
|
| 249 |
+
|
| 250 |
+
# Try to find the best match
|
| 251 |
+
for key, value in self.general_knowledge.items():
|
| 252 |
+
if key in original_query.lower():
|
| 253 |
+
return value
|
| 254 |
+
|
| 255 |
+
# If no specific knowledge found, use default
|
| 256 |
+
responses = self.general_responses.get("default", ["I can help with that!"])
|
| 257 |
+
return random.choice(responses)
|
| 258 |
+
|
| 259 |
responses = self.general_responses.get(query_type, self.general_responses["default"])
|
| 260 |
return random.choice(responses)
|
| 261 |
|
| 262 |
def generate_response(self, query):
|
| 263 |
"""Generate appropriate response based on query type"""
|
| 264 |
+
# First check query type
|
| 265 |
query_type = self.detect_query_type(query)
|
| 266 |
|
| 267 |
+
# Handle general questions (always answer these)
|
| 268 |
+
if query_type in ["greeting", "thanks", "how_are_you", "identity", "capabilities", "general_knowledge"]:
|
| 269 |
+
return self.get_general_response(query_type, query)
|
| 270 |
|
| 271 |
# If it's a document question but no file is loaded
|
| 272 |
if not self.is_ready:
|
| 273 |
+
return ("π Please upload a document file first to ask questions about its content.\n\n"
|
| 274 |
+
"π But I can answer general questions like:\n"
|
| 275 |
+
"β’ 'What is the capital of India?'\n"
|
| 276 |
+
"β’ 'How are you?'\n"
|
| 277 |
+
"β’ 'What can you do?'")
|
| 278 |
|
| 279 |
# Search in document content
|
| 280 |
results = self.search_documents(query)
|
| 281 |
|
| 282 |
if not results:
|
| 283 |
+
# No relevant content found in document - provide helpful response
|
| 284 |
+
return (f"π I couldn't find specific information about '{query}' in your document.\n\n"
|
| 285 |
+
"π‘ This might be outside the document's scope. You can:\n"
|
| 286 |
+
"β’ Ask me general knowledge questions\n"
|
| 287 |
+
"β’ Upload a different file\n"
|
| 288 |
+
"β’ Try rephrasing your question\n\n"
|
| 289 |
+
"π Try asking: 'What is the capital of India?' or 'How are you?'")
|
| 290 |
|
| 291 |
# Check if the results are actually relevant (score threshold)
|
| 292 |
relevant_results = [r for r in results if r['score'] > 0.3]
|
| 293 |
|
| 294 |
if not relevant_results:
|
| 295 |
+
return (f"π The document doesn't contain specific information about '{query}'.\n\n"
|
| 296 |
+
"π‘ But I can help with:\n"
|
| 297 |
+
"β’ General knowledge questions\n"
|
| 298 |
+
"β’ Other questions about your document\n"
|
| 299 |
+
"β’ Casual conversation")
|
| 300 |
|
| 301 |
# Build response from relevant document content
|
| 302 |
+
response = "π Based on your document:\n\n"
|
| 303 |
for i, result in enumerate(relevant_results[:2]): # Show top 2 results
|
| 304 |
response += f"β’ {result['content']}\n\n"
|
| 305 |
|
|
|
|
| 311 |
with gr.Blocks(theme=gr.themes.Soft(), title="Smart Document Assistant") as demo:
|
| 312 |
gr.Markdown("""
|
| 313 |
# π€ Smart Document Assistant
|
| 314 |
+
|
| 315 |
**Upload your file and ask any questions!**
|
| 316 |
+
|
| 317 |
+
- **π Document Questions**: Get answers from your uploaded files
|
| 318 |
+
- **π General Knowledge**: Ask about capitals, populations, facts
|
| 319 |
+
- **π¬ Casual Chat**: Have normal conversations
|
| 320 |
+
|
| 321 |
+
**Supported Formats**: TXT, CSV, PDF, DOCX, DOC
|
| 322 |
""")
|
| 323 |
|
| 324 |
with gr.Row():
|
| 325 |
with gr.Column(scale=1):
|
| 326 |
gr.Markdown("### π File Upload")
|
| 327 |
file_input = gr.File(
|
| 328 |
+
label="Upload your file",
|
| 329 |
file_types=[".txt", ".csv", ".pdf", ".docx", ".doc"],
|
| 330 |
type="filepath"
|
| 331 |
)
|
| 332 |
upload_btn = gr.Button("Process File", variant="primary")
|
| 333 |
status = gr.Textbox(
|
| 334 |
label="Status",
|
| 335 |
+
value="Please upload a file first...",
|
| 336 |
interactive=False
|
| 337 |
)
|
| 338 |
|
| 339 |
with gr.Column(scale=2):
|
| 340 |
+
gr.Markdown("### π¬ Ask Questions")
|
| 341 |
chatbot = gr.Chatbot(
|
| 342 |
height=400,
|
| 343 |
+
label="Conversation",
|
| 344 |
+
show_copy_button=True,
|
| 345 |
+
placeholder="Your questions and answers will appear here..."
|
| 346 |
)
|
| 347 |
with gr.Row():
|
| 348 |
question_input = gr.Textbox(
|
| 349 |
+
label="Your question",
|
| 350 |
+
placeholder="Type any question - about your file or general knowledge...",
|
| 351 |
scale=4
|
| 352 |
)
|
| 353 |
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 354 |
|
| 355 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 356 |
|
| 357 |
# Example questions
|
| 358 |
gr.Markdown("""
|
| 359 |
+
### π‘ Try These Questions:
|
| 360 |
+
|
| 361 |
+
**π File-related Questions:**
|
| 362 |
- "What is the main topic of this document?"
|
| 363 |
- "Tell me about the key points"
|
| 364 |
+
- "Summarize the content"
|
| 365 |
+
|
| 366 |
+
**π General Knowledge:**
|
| 367 |
+
- "What is the capital of India?"
|
| 368 |
+
- "Who is the Prime Minister of India?"
|
| 369 |
+
- "What is the population of India?"
|
| 370 |
+
- "What is the national animal of India?"
|
| 371 |
|
| 372 |
+
**π¬ Casual Questions:**
|
| 373 |
- "Hello, how are you?"
|
| 374 |
- "What can you do?"
|
| 375 |
- "Thank you for your help!"
|