Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import json
|
| 3 |
import numpy as np
|
|
@@ -8,28 +10,42 @@ import faiss
|
|
| 8 |
from typing import List, Dict, Any, Optional, Tuple
|
| 9 |
import logging
|
| 10 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
-
class
|
| 16 |
-
def __init__(
|
| 17 |
-
self
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
|
| 25 |
-
self.temperature = temperature
|
| 26 |
-
self.top_k = top_k
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 32 |
-
|
| 33 |
trust_remote_code=True
|
| 34 |
)
|
| 35 |
|
|
@@ -37,303 +53,434 @@ class QwenRAGSystem:
|
|
| 37 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 38 |
|
| 39 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 40 |
-
|
| 41 |
torch_dtype=torch.float32,
|
| 42 |
trust_remote_code=True,
|
| 43 |
low_cpu_mem_usage=True
|
| 44 |
)
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
logger.info("β Models loaded successfully")
|
| 49 |
|
| 50 |
except Exception as e:
|
| 51 |
-
logger.error(f"Error loading
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
def load_json_knowledge_base(self, json_data, text_fields: List[str] = None):
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
logger.info(f"Loaded {len(self.knowledge_base)} documents")
|
| 72 |
-
|
| 73 |
-
self.text_contents = []
|
| 74 |
-
for doc in self.knowledge_base:
|
| 75 |
-
if text_fields:
|
| 76 |
-
text_parts = []
|
| 77 |
-
for field in text_fields:
|
| 78 |
-
if field in doc and doc[field]:
|
| 79 |
-
text_parts.append(str(doc[field]))
|
| 80 |
-
text = " ".join(text_parts)
|
| 81 |
else:
|
| 82 |
-
|
| 83 |
-
for k, v in doc.items():
|
| 84 |
-
if isinstance(v, str) and len(v.strip()) > 0:
|
| 85 |
-
text_parts.append(f"{k}: {v}")
|
| 86 |
-
text = " ".join(text_parts)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
def _create_embeddings(self):
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
self.text_contents,
|
| 97 |
-
convert_to_numpy=True,
|
| 98 |
-
show_progress_bar=False
|
| 99 |
-
)
|
| 100 |
-
|
| 101 |
-
dimension = self.embeddings.shape[1]
|
| 102 |
-
self.index = faiss.IndexFlatIP(dimension)
|
| 103 |
|
| 104 |
-
|
| 105 |
-
self.index.add(self.embeddings)
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
def retrieve_documents(self, query: str, top_k:
|
|
|
|
| 110 |
if self.index is None:
|
| 111 |
raise ValueError("Knowledge base not loaded")
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
query_embedding = self.embedding_model.encode([query], convert_to_numpy=True)
|
| 116 |
-
faiss.normalize_L2(query_embedding)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
for score, idx in zip(scores[0], indices[0]):
|
| 122 |
-
if idx != -1:
|
| 123 |
-
results.append((self.knowledge_base[idx], float(score)))
|
| 124 |
-
|
| 125 |
-
return results
|
| 126 |
-
|
| 127 |
-
def format_context(self, retrieved_docs):
|
| 128 |
-
context_parts = []
|
| 129 |
-
|
| 130 |
-
for i, (doc, score) in enumerate(retrieved_docs, 1):
|
| 131 |
-
doc_text = ""
|
| 132 |
-
for k, v in doc.items():
|
| 133 |
-
if isinstance(v, str) and len(v.strip()) > 0:
|
| 134 |
-
doc_text += f"{k}: {v}\n"
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
def generate_response(self, query: str, context: str
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
with torch.no_grad():
|
| 154 |
-
generated_ids = self.model.generate(
|
| 155 |
-
model_inputs.input_ids,
|
| 156 |
-
attention_mask=model_inputs.attention_mask,
|
| 157 |
-
max_new_tokens=max_new_tokens,
|
| 158 |
-
temperature=self.temperature,
|
| 159 |
-
do_sample=True if self.temperature > 0 else False,
|
| 160 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 161 |
-
eos_token_id=self.tokenizer.eos_token_id,
|
| 162 |
-
use_cache=True
|
| 163 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
|
| 169 |
-
|
| 170 |
-
return response.strip()
|
| 171 |
|
| 172 |
-
def query(self, question: str, top_k:
|
|
|
|
| 173 |
if self.index is None:
|
| 174 |
-
return "Please upload a JSON knowledge base first.", ""
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
# Global
|
| 192 |
rag_system = None
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
def load_knowledge_base(json_file, text_fields):
|
|
|
|
| 195 |
global rag_system
|
| 196 |
|
| 197 |
if json_file is None:
|
| 198 |
-
return "Please upload a JSON file.", "", ""
|
| 199 |
|
| 200 |
try:
|
|
|
|
| 201 |
if rag_system is None:
|
| 202 |
-
|
|
|
|
|
|
|
| 203 |
|
|
|
|
| 204 |
with open(json_file.name, 'r', encoding='utf-8') as f:
|
| 205 |
json_data = json.load(f)
|
| 206 |
|
|
|
|
| 207 |
fields = None
|
| 208 |
if text_fields.strip():
|
| 209 |
fields = [field.strip() for field in text_fields.split(',')]
|
| 210 |
|
| 211 |
-
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
except Exception as e:
|
| 216 |
return f"β Error loading knowledge base: {str(e)}", "", ""
|
| 217 |
|
| 218 |
def ask_question(question, top_k):
|
|
|
|
| 219 |
global rag_system
|
| 220 |
|
| 221 |
-
if
|
| 222 |
-
return "Please
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
try:
|
| 225 |
-
response, retrieved_docs = rag_system.query(question, top_k)
|
| 226 |
return response, retrieved_docs
|
| 227 |
except Exception as e:
|
| 228 |
-
|
|
|
|
| 229 |
|
| 230 |
-
# Create Gradio interface
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
# π€ RAG System with Qwen 1.5
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
with gr.Tab("π Load Knowledge Base"):
|
| 239 |
with gr.Row():
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
| 252 |
|
| 253 |
-
with gr.
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
)
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
-
with gr.
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
with gr.
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
|
|
|
| 298 |
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
"content": "Machine learning is a subset of artificial intelligence...",
|
| 307 |
-
"category": "AI"
|
| 308 |
-
},
|
| 309 |
-
{
|
| 310 |
-
"id": 2,
|
| 311 |
-
"title": "Deep Learning",
|
| 312 |
-
"content": "Deep learning uses neural networks...",
|
| 313 |
-
"category": "AI"
|
| 314 |
-
}
|
| 315 |
-
]
|
| 316 |
-
```
|
| 317 |
-
""")
|
| 318 |
-
|
| 319 |
-
# Event handlers
|
| 320 |
-
load_btn.click(
|
| 321 |
-
load_knowledge_base,
|
| 322 |
-
inputs=[json_file, text_fields],
|
| 323 |
-
outputs=[load_status, answer, retrieved_docs]
|
| 324 |
-
)
|
| 325 |
-
|
| 326 |
-
ask_btn.click(
|
| 327 |
-
ask_question,
|
| 328 |
-
inputs=[question, top_k],
|
| 329 |
-
outputs=[answer, retrieved_docs]
|
| 330 |
-
)
|
| 331 |
|
| 332 |
-
|
| 333 |
-
ask_question,
|
| 334 |
-
inputs=[question, top_k],
|
| 335 |
-
outputs=[answer, retrieved_docs]
|
| 336 |
-
)
|
| 337 |
|
|
|
|
| 338 |
if __name__ == "__main__":
|
| 339 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FIXED VERSION OF app.py - Copy this if you're getting runtime errors
|
| 2 |
+
|
| 3 |
import gradio as gr
|
| 4 |
import json
|
| 5 |
import numpy as np
|
|
|
|
| 10 |
from typing import List, Dict, Any, Optional, Tuple
|
| 11 |
import logging
|
| 12 |
import os
|
| 13 |
+
import warnings
|
| 14 |
+
|
| 15 |
+
# Suppress warnings
|
| 16 |
+
warnings.filterwarnings("ignore")
|
| 17 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 18 |
|
| 19 |
logging.basicConfig(level=logging.INFO)
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
+
class SimpleRAGSystem:
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.device = 'cpu' # Force CPU to avoid GPU memory issues
|
| 25 |
+
self.knowledge_base = []
|
| 26 |
+
self.embeddings = None
|
| 27 |
+
self.index = None
|
| 28 |
+
self.embedding_model = None
|
| 29 |
+
self.tokenizer = None
|
| 30 |
+
self.model = None
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# Initialize models with better error handling
|
| 33 |
+
self._initialize_models()
|
| 34 |
+
|
| 35 |
+
def _initialize_models(self):
|
| 36 |
+
"""Initialize models with fallback options"""
|
| 37 |
+
logger.info("Initializing models...")
|
| 38 |
|
| 39 |
try:
|
| 40 |
+
# Try to load embedding model first (smaller, less likely to fail)
|
| 41 |
+
logger.info("Loading embedding model...")
|
| 42 |
+
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2', device='cpu')
|
| 43 |
+
logger.info("β
Embedding model loaded")
|
| 44 |
+
|
| 45 |
+
# Try to load Qwen model
|
| 46 |
+
logger.info("Loading Qwen model...")
|
| 47 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 48 |
+
"Qwen/Qwen1.5-0.5B-Chat",
|
| 49 |
trust_remote_code=True
|
| 50 |
)
|
| 51 |
|
|
|
|
| 53 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 54 |
|
| 55 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 56 |
+
"Qwen/Qwen1.5-0.5B-Chat",
|
| 57 |
torch_dtype=torch.float32,
|
| 58 |
trust_remote_code=True,
|
| 59 |
low_cpu_mem_usage=True
|
| 60 |
)
|
| 61 |
|
| 62 |
+
logger.info("β
Qwen model loaded successfully")
|
|
|
|
|
|
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
+
logger.error(f"Error loading Qwen model: {e}")
|
| 66 |
+
logger.info("Falling back to simpler model...")
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
# Fallback to a more reliable model
|
| 70 |
+
self.tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
|
| 71 |
+
self.model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
|
| 72 |
+
|
| 73 |
+
if self.tokenizer.pad_token is None:
|
| 74 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 75 |
+
|
| 76 |
+
logger.info("β
Fallback model loaded")
|
| 77 |
+
|
| 78 |
+
except Exception as e2:
|
| 79 |
+
logger.error(f"Fallback model also failed: {e2}")
|
| 80 |
+
# Set models to None - we'll handle this in the interface
|
| 81 |
+
self.model = None
|
| 82 |
+
self.tokenizer = None
|
| 83 |
|
| 84 |
def load_json_knowledge_base(self, json_data, text_fields: List[str] = None):
|
| 85 |
+
"""Load knowledge base from JSON data"""
|
| 86 |
+
try:
|
| 87 |
+
logger.info("Loading knowledge base...")
|
| 88 |
+
|
| 89 |
+
# Handle different JSON structures
|
| 90 |
+
if isinstance(json_data, dict):
|
| 91 |
+
if any(isinstance(v, dict) for v in json_data.values()):
|
| 92 |
+
self.knowledge_base = [{"id": k, **v} for k, v in json_data.items()]
|
| 93 |
+
else:
|
| 94 |
+
self.knowledge_base = [json_data]
|
| 95 |
+
elif isinstance(json_data, list):
|
| 96 |
+
self.knowledge_base = json_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
else:
|
| 98 |
+
raise ValueError("JSON must contain either a dict or list structure")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
logger.info(f"Loaded {len(self.knowledge_base)} documents")
|
| 101 |
+
|
| 102 |
+
# Extract text content
|
| 103 |
+
self.text_contents = []
|
| 104 |
+
for doc in self.knowledge_base:
|
| 105 |
+
if text_fields:
|
| 106 |
+
text_parts = []
|
| 107 |
+
for field in text_fields:
|
| 108 |
+
if field in doc and doc[field]:
|
| 109 |
+
text_parts.append(str(doc[field]))
|
| 110 |
+
text = " ".join(text_parts)
|
| 111 |
+
else:
|
| 112 |
+
text_parts = []
|
| 113 |
+
for k, v in doc.items():
|
| 114 |
+
if isinstance(v, str) and len(v.strip()) > 0:
|
| 115 |
+
text_parts.append(f"{k}: {v}")
|
| 116 |
+
text = " ".join(text_parts)
|
| 117 |
+
|
| 118 |
+
self.text_contents.append(text)
|
| 119 |
+
|
| 120 |
+
# Create embeddings
|
| 121 |
+
self._create_embeddings()
|
| 122 |
+
return True
|
| 123 |
+
|
| 124 |
+
except Exception as e:
|
| 125 |
+
logger.error(f"Error loading knowledge base: {e}")
|
| 126 |
+
return False
|
| 127 |
|
| 128 |
def _create_embeddings(self):
|
| 129 |
+
"""Create embeddings and FAISS index"""
|
| 130 |
+
if self.embedding_model is None:
|
| 131 |
+
raise ValueError("Embedding model not loaded")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
logger.info("Creating embeddings...")
|
|
|
|
| 134 |
|
| 135 |
+
try:
|
| 136 |
+
self.embeddings = self.embedding_model.encode(
|
| 137 |
+
self.text_contents,
|
| 138 |
+
convert_to_numpy=True,
|
| 139 |
+
show_progress_bar=False
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Build FAISS index
|
| 143 |
+
dimension = self.embeddings.shape[1]
|
| 144 |
+
self.index = faiss.IndexFlatIP(dimension)
|
| 145 |
+
|
| 146 |
+
# Normalize embeddings
|
| 147 |
+
faiss.normalize_L2(self.embeddings)
|
| 148 |
+
self.index.add(self.embeddings)
|
| 149 |
+
|
| 150 |
+
logger.info(f"β
Created FAISS index with {self.index.ntotal} documents")
|
| 151 |
+
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.error(f"Error creating embeddings: {e}")
|
| 154 |
+
raise
|
| 155 |
|
| 156 |
+
def retrieve_documents(self, query: str, top_k: int = 3):
|
| 157 |
+
"""Retrieve relevant documents"""
|
| 158 |
if self.index is None:
|
| 159 |
raise ValueError("Knowledge base not loaded")
|
| 160 |
|
| 161 |
+
if self.embedding_model is None:
|
| 162 |
+
raise ValueError("Embedding model not available")
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
try:
|
| 165 |
+
query_embedding = self.embedding_model.encode([query], convert_to_numpy=True)
|
| 166 |
+
faiss.normalize_L2(query_embedding)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
scores, indices = self.index.search(query_embedding, top_k)
|
| 169 |
+
|
| 170 |
+
results = []
|
| 171 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 172 |
+
if idx != -1:
|
| 173 |
+
results.append((self.knowledge_base[idx], float(score)))
|
| 174 |
+
|
| 175 |
+
return results
|
| 176 |
+
|
| 177 |
+
except Exception as e:
|
| 178 |
+
logger.error(f"Error retrieving documents: {e}")
|
| 179 |
+
return []
|
| 180 |
|
| 181 |
+
def generate_response(self, query: str, context: str):
|
| 182 |
+
"""Generate response - with fallback to simple text matching"""
|
| 183 |
|
| 184 |
+
if self.model is None or self.tokenizer is None:
|
| 185 |
+
# Fallback: simple text-based response
|
| 186 |
+
return self._simple_response_fallback(query, context)
|
| 187 |
|
| 188 |
+
try:
|
| 189 |
+
prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
|
| 190 |
+
|
| 191 |
+
inputs = self.tokenizer(
|
| 192 |
+
prompt,
|
| 193 |
+
return_tensors="pt",
|
| 194 |
+
max_length=512,
|
| 195 |
+
truncation=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
)
|
| 197 |
+
|
| 198 |
+
with torch.no_grad():
|
| 199 |
+
outputs = self.model.generate(
|
| 200 |
+
inputs.input_ids,
|
| 201 |
+
max_new_tokens=100,
|
| 202 |
+
temperature=0.7,
|
| 203 |
+
do_sample=True,
|
| 204 |
+
pad_token_id=self.tokenizer.pad_token_id
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
response = self.tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
| 208 |
+
return response.strip()
|
| 209 |
+
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logger.error(f"Error generating response: {e}")
|
| 212 |
+
return self._simple_response_fallback(query, context)
|
| 213 |
+
|
| 214 |
+
def _simple_response_fallback(self, query: str, context: str):
|
| 215 |
+
"""Simple fallback response when models fail"""
|
| 216 |
+
if not context.strip():
|
| 217 |
+
return "I couldn't find relevant information in the knowledge base to answer your question."
|
| 218 |
|
| 219 |
+
# Simple keyword matching response
|
| 220 |
+
context_lines = context.split('\n')[:5] # First 5 lines
|
| 221 |
+
response = f"Based on the available information:\n\n{chr(10).join(context_lines)}\n\nNote: Advanced AI response generation is currently unavailable, showing relevant context instead."
|
| 222 |
|
| 223 |
+
return response
|
|
|
|
| 224 |
|
| 225 |
+
def query(self, question: str, top_k: int = 3):
|
| 226 |
+
"""Complete RAG pipeline"""
|
| 227 |
if self.index is None:
|
| 228 |
+
return "β Please upload a JSON knowledge base first.", "No documents loaded."
|
| 229 |
|
| 230 |
+
try:
|
| 231 |
+
# Retrieve documents
|
| 232 |
+
retrieved_docs = self.retrieve_documents(question, top_k)
|
| 233 |
+
|
| 234 |
+
if not retrieved_docs:
|
| 235 |
+
return "β No relevant documents found for your query.", "No matches found."
|
| 236 |
+
|
| 237 |
+
# Format context
|
| 238 |
+
context_parts = []
|
| 239 |
+
for i, (doc, score) in enumerate(retrieved_docs, 1):
|
| 240 |
+
doc_text = ""
|
| 241 |
+
for k, v in doc.items():
|
| 242 |
+
if isinstance(v, str) and len(v.strip()) > 0:
|
| 243 |
+
doc_text += f"{k}: {v}\n"
|
| 244 |
+
context_parts.append(f"Document {i} (score: {score:.3f}):\n{doc_text}")
|
| 245 |
+
|
| 246 |
+
context = "\n---\n".join(context_parts)
|
| 247 |
+
|
| 248 |
+
# Generate response
|
| 249 |
+
response = self.generate_response(question, context)
|
| 250 |
+
|
| 251 |
+
# Format retrieved docs for display
|
| 252 |
+
retrieved_info = ""
|
| 253 |
+
for i, (doc, score) in enumerate(retrieved_docs, 1):
|
| 254 |
+
retrieved_info += f"**Document {i}** (Score: {score:.3f})\n"
|
| 255 |
+
for k, v in list(doc.items())[:3]:
|
| 256 |
+
if isinstance(v, str):
|
| 257 |
+
preview = v[:100] + "..." if len(v) > 100 else v
|
| 258 |
+
retrieved_info += f"- **{k}**: {preview}\n"
|
| 259 |
+
retrieved_info += "\n"
|
| 260 |
+
|
| 261 |
+
return response, retrieved_info
|
| 262 |
+
|
| 263 |
+
except Exception as e:
|
| 264 |
+
logger.error(f"Error in query pipeline: {e}")
|
| 265 |
+
return f"β Error processing query: {str(e)}", "Error occurred."
|
| 266 |
|
| 267 |
+
# Global RAG system
|
| 268 |
rag_system = None
|
| 269 |
|
| 270 |
+
def initialize_system():
|
| 271 |
+
"""Initialize the RAG system"""
|
| 272 |
+
global rag_system
|
| 273 |
+
if rag_system is None:
|
| 274 |
+
try:
|
| 275 |
+
rag_system = SimpleRAGSystem()
|
| 276 |
+
return "β
System initialized successfully"
|
| 277 |
+
except Exception as e:
|
| 278 |
+
return f"β System initialization failed: {str(e)}"
|
| 279 |
+
return "β
System already initialized"
|
| 280 |
+
|
| 281 |
def load_knowledge_base(json_file, text_fields):
|
| 282 |
+
"""Load knowledge base from uploaded file"""
|
| 283 |
global rag_system
|
| 284 |
|
| 285 |
if json_file is None:
|
| 286 |
+
return "β Please upload a JSON file.", "", ""
|
| 287 |
|
| 288 |
try:
|
| 289 |
+
# Initialize system if not done
|
| 290 |
if rag_system is None:
|
| 291 |
+
init_msg = initialize_system()
|
| 292 |
+
if "failed" in init_msg:
|
| 293 |
+
return init_msg, "", ""
|
| 294 |
|
| 295 |
+
# Read JSON file
|
| 296 |
with open(json_file.name, 'r', encoding='utf-8') as f:
|
| 297 |
json_data = json.load(f)
|
| 298 |
|
| 299 |
+
# Parse text fields
|
| 300 |
fields = None
|
| 301 |
if text_fields.strip():
|
| 302 |
fields = [field.strip() for field in text_fields.split(',')]
|
| 303 |
|
| 304 |
+
# Load knowledge base
|
| 305 |
+
success = rag_system.load_json_knowledge_base(json_data, fields)
|
| 306 |
|
| 307 |
+
if success:
|
| 308 |
+
return f"β
Successfully loaded {len(rag_system.knowledge_base)} documents", "", ""
|
| 309 |
+
else:
|
| 310 |
+
return "β Failed to load knowledge base. Check logs for details.", "", ""
|
| 311 |
+
|
| 312 |
+
except json.JSONDecodeError:
|
| 313 |
+
return "β Invalid JSON file. Please check your file format.", "", ""
|
| 314 |
except Exception as e:
|
| 315 |
return f"β Error loading knowledge base: {str(e)}", "", ""
|
| 316 |
|
| 317 |
def ask_question(question, top_k):
|
| 318 |
+
"""Ask a question using RAG"""
|
| 319 |
global rag_system
|
| 320 |
|
| 321 |
+
if not question.strip():
|
| 322 |
+
return "Please enter a question.", ""
|
| 323 |
+
|
| 324 |
+
if rag_system is None:
|
| 325 |
+
return "β System not initialized. Please try reloading the page.", ""
|
| 326 |
|
| 327 |
try:
|
| 328 |
+
response, retrieved_docs = rag_system.query(question.strip(), int(top_k))
|
| 329 |
return response, retrieved_docs
|
| 330 |
except Exception as e:
|
| 331 |
+
logger.error(f"Error in ask_question: {e}")
|
| 332 |
+
return f"β Error processing question: {str(e)}", ""
|
| 333 |
|
| 334 |
+
# Create the Gradio interface
|
| 335 |
+
def create_interface():
|
| 336 |
+
"""Create Gradio interface with better error handling"""
|
|
|
|
| 337 |
|
| 338 |
+
with gr.Blocks(title="RAG System", theme=gr.themes.Soft()) as demo:
|
| 339 |
+
|
| 340 |
+
# Add initialization status
|
|
|
|
| 341 |
with gr.Row():
|
| 342 |
+
gr.Markdown("# π€ RAG System with AI")
|
| 343 |
+
init_status = gr.Textbox(
|
| 344 |
+
label="System Status",
|
| 345 |
+
value="Initializing...",
|
| 346 |
+
interactive=False,
|
| 347 |
+
scale=1
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
with gr.Tab("π Load Knowledge Base"):
|
| 351 |
+
gr.Markdown("""
|
| 352 |
+
### Step 1: Upload your JSON knowledge base
|
| 353 |
+
Upload a JSON file containing your documents. The system will process and index them for search.
|
| 354 |
+
""")
|
| 355 |
|
| 356 |
+
with gr.Row():
|
| 357 |
+
with gr.Column(scale=2):
|
| 358 |
+
json_file = gr.File(
|
| 359 |
+
label="Upload JSON Knowledge Base",
|
| 360 |
+
file_types=[".json"],
|
| 361 |
+
type="filepath"
|
| 362 |
+
)
|
| 363 |
+
text_fields = gr.Textbox(
|
| 364 |
+
label="Text Fields (comma-separated, optional)",
|
| 365 |
+
placeholder="title, content, description",
|
| 366 |
+
info="Specify which fields to use for search. Leave empty to auto-detect."
|
| 367 |
+
)
|
| 368 |
+
load_btn = gr.Button("π€ Load Knowledge Base", variant="primary", size="lg")
|
| 369 |
+
|
| 370 |
+
with gr.Column(scale=1):
|
| 371 |
+
load_status = gr.Textbox(
|
| 372 |
+
label="Loading Status",
|
| 373 |
+
lines=3,
|
| 374 |
+
interactive=False,
|
| 375 |
+
placeholder="Status will appear here..."
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
with gr.Tab("π¬ Ask Questions"):
|
| 379 |
+
gr.Markdown("""
|
| 380 |
+
### Step 2: Ask questions about your knowledge base
|
| 381 |
+
Once you've loaded your knowledge base, you can ask questions and get AI-powered answers.
|
| 382 |
+
""")
|
| 383 |
|
| 384 |
+
with gr.Row():
|
| 385 |
+
with gr.Column(scale=2):
|
| 386 |
+
question = gr.Textbox(
|
| 387 |
+
label="Your Question",
|
| 388 |
+
placeholder="What would you like to know?",
|
| 389 |
+
lines=2
|
| 390 |
+
)
|
| 391 |
+
with gr.Row():
|
| 392 |
+
top_k = gr.Slider(
|
| 393 |
+
minimum=1,
|
| 394 |
+
maximum=5,
|
| 395 |
+
value=3,
|
| 396 |
+
step=1,
|
| 397 |
+
label="Documents to retrieve"
|
| 398 |
+
)
|
| 399 |
+
ask_btn = gr.Button("π Ask Question", variant="primary")
|
| 400 |
+
|
| 401 |
+
with gr.Column(scale=2):
|
| 402 |
+
answer = gr.Textbox(
|
| 403 |
+
label="Answer",
|
| 404 |
+
lines=6,
|
| 405 |
+
interactive=False,
|
| 406 |
+
placeholder="Answers will appear here..."
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
with gr.Accordion("π Retrieved Documents", open=False):
|
| 410 |
+
retrieved_docs = gr.Markdown("No documents retrieved yet.")
|
| 411 |
|
| 412 |
+
with gr.Tab("π Help & Examples"):
|
| 413 |
+
gr.Markdown("""
|
| 414 |
+
## How to Use This System
|
| 415 |
+
|
| 416 |
+
1. **Upload JSON**: Click "Load Knowledge Base" tab and upload your JSON file
|
| 417 |
+
2. **Load Data**: Click "Load Knowledge Base" button to process your data
|
| 418 |
+
3. **Ask Questions**: Go to "Ask Questions" tab and type your question
|
| 419 |
+
4. **Get Answers**: The AI will search your data and provide answers
|
| 420 |
+
|
| 421 |
+
## Supported JSON Format
|
| 422 |
+
|
| 423 |
+
```json
|
| 424 |
+
[
|
| 425 |
+
{
|
| 426 |
+
"id": 1,
|
| 427 |
+
"title": "Example Document",
|
| 428 |
+
"content": "This is the content of the document...",
|
| 429 |
+
"category": "Information"
|
| 430 |
+
},
|
| 431 |
+
{
|
| 432 |
+
"id": 2,
|
| 433 |
+
"title": "Another Document",
|
| 434 |
+
"content": "More content here...",
|
| 435 |
+
"category": "Knowledge"
|
| 436 |
+
}
|
| 437 |
+
]
|
| 438 |
+
```
|
| 439 |
+
|
| 440 |
+
## Example Questions
|
| 441 |
+
- "What is this document about?"
|
| 442 |
+
- "Tell me about [specific topic]"
|
| 443 |
+
- "How does [concept] work?"
|
| 444 |
+
- "What are the main points?"
|
| 445 |
+
|
| 446 |
+
## Troubleshooting
|
| 447 |
+
- Make sure your JSON file is valid
|
| 448 |
+
- Try smaller JSON files if you get memory errors
|
| 449 |
+
- Refresh the page if something seems stuck
|
| 450 |
+
""")
|
| 451 |
+
|
| 452 |
+
# Event handlers
|
| 453 |
+
load_btn.click(
|
| 454 |
+
fn=load_knowledge_base,
|
| 455 |
+
inputs=[json_file, text_fields],
|
| 456 |
+
outputs=[load_status, answer, retrieved_docs]
|
| 457 |
+
)
|
| 458 |
|
| 459 |
+
ask_btn.click(
|
| 460 |
+
fn=ask_question,
|
| 461 |
+
inputs=[question, top_k],
|
| 462 |
+
outputs=[answer, retrieved_docs]
|
| 463 |
+
)
|
| 464 |
|
| 465 |
+
question.submit(
|
| 466 |
+
fn=ask_question,
|
| 467 |
+
inputs=[question, top_k],
|
| 468 |
+
outputs=[answer, retrieved_docs]
|
| 469 |
+
)
|
| 470 |
|
| 471 |
+
# Initialize system on load
|
| 472 |
+
demo.load(
|
| 473 |
+
fn=initialize_system,
|
| 474 |
+
outputs=[init_status]
|
| 475 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
|
| 477 |
+
return demo
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
| 479 |
+
# Launch the app
|
| 480 |
if __name__ == "__main__":
|
| 481 |
+
demo = create_interface()
|
| 482 |
+
demo.launch(
|
| 483 |
+
server_name="0.0.0.0",
|
| 484 |
+
server_port=7860,
|
| 485 |
+
show_error=True
|
| 486 |
+
)
|