Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
# Minimal working Vision 2030 Virtual Assistant
|
2 |
import gradio as gr
|
3 |
import time
|
4 |
import logging
|
@@ -8,23 +7,21 @@ from datetime import datetime
|
|
8 |
import numpy as np
|
9 |
import pandas as pd
|
10 |
import matplotlib.pyplot as plt
|
11 |
-
from
|
12 |
-
import PyPDF2
|
13 |
-
import io
|
14 |
-
import json
|
15 |
-
from langdetect import detect
|
16 |
-
from sentence_transformers import SentenceTransformer
|
17 |
import faiss
|
18 |
import torch
|
19 |
import spaces
|
|
|
|
|
|
|
20 |
|
21 |
-
# Configure logging
|
22 |
logging.basicConfig(
|
23 |
level=logging.INFO,
|
24 |
-
format='%(asctime)s - %(
|
25 |
handlers=[logging.StreamHandler()]
|
26 |
)
|
27 |
-
logger = logging.getLogger('
|
28 |
|
29 |
# Check for GPU availability
|
30 |
has_gpu = torch.cuda.is_available()
|
@@ -32,726 +29,249 @@ logger.info(f"GPU available: {has_gpu}")
|
|
32 |
|
33 |
class Vision2030Assistant:
|
34 |
def __init__(self):
|
35 |
-
"""Initialize the
|
36 |
logger.info("Initializing Vision 2030 Assistant...")
|
37 |
|
38 |
-
#
|
39 |
self.load_embedding_models()
|
|
|
40 |
|
41 |
-
#
|
42 |
self._create_knowledge_base()
|
43 |
self._create_indices()
|
44 |
|
45 |
-
#
|
46 |
self._create_sample_eval_data()
|
47 |
|
48 |
-
#
|
49 |
-
self.metrics = {
|
50 |
-
"response_times": [],
|
51 |
-
"user_ratings": [],
|
52 |
-
"factual_accuracy": []
|
53 |
-
}
|
54 |
-
self.response_history = []
|
55 |
|
56 |
-
#
|
|
|
|
|
|
|
57 |
self.has_pdf_content = False
|
58 |
|
59 |
-
logger.info("
|
60 |
-
|
61 |
@spaces.GPU
|
62 |
def load_embedding_models(self):
|
63 |
-
"""Load embedding models
|
64 |
-
logger.info("Loading embedding models...")
|
65 |
-
|
66 |
try:
|
67 |
-
# Load embedding models
|
68 |
self.arabic_embedder = SentenceTransformer('CAMeL-Lab/bert-base-arabic-camelbert-ca')
|
69 |
self.english_embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
70 |
-
|
71 |
-
# Move to GPU if available
|
72 |
if has_gpu:
|
73 |
self.arabic_embedder = self.arabic_embedder.to('cuda')
|
74 |
self.english_embedder = self.english_embedder.to('cuda')
|
75 |
-
logger.info("Models moved to GPU")
|
76 |
-
|
77 |
logger.info("Embedding models loaded successfully")
|
78 |
except Exception as e:
|
79 |
-
logger.error(f"
|
80 |
-
self.
|
81 |
|
82 |
-
def
|
83 |
-
"""
|
84 |
-
logger.warning("Using fallback embedding
|
85 |
-
|
86 |
-
# Simple fallback using character-level encoding
|
87 |
-
def simple_encode(text, dim=384):
|
88 |
import hashlib
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
np.random.seed(int(hash_object.hexdigest(), 16) % 2**32)
|
93 |
-
# Generate a random vector
|
94 |
-
return np.random.randn(dim).astype(np.float32)
|
95 |
|
96 |
-
# Create embedding function objects
|
97 |
class SimpleEmbedder:
|
98 |
-
def __init__(self, dim=384):
|
99 |
-
self.dim = dim
|
100 |
-
|
101 |
def encode(self, text):
|
102 |
-
return
|
103 |
|
104 |
self.arabic_embedder = SimpleEmbedder()
|
105 |
self.english_embedder = SimpleEmbedder()
|
106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
def _create_knowledge_base(self):
|
108 |
-
"""Create knowledge base
|
109 |
-
logger.info("Creating Vision 2030 knowledge base")
|
110 |
-
|
111 |
-
# English texts
|
112 |
self.english_texts = [
|
113 |
"Vision 2030 is Saudi Arabia's strategic framework to reduce dependence on oil, diversify the economy, and develop public sectors.",
|
114 |
"The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation.",
|
115 |
-
"
|
116 |
-
"NEOM is a planned cross-border smart city in the Tabuk Province of northwestern Saudi Arabia, a key project of Vision 2030.",
|
117 |
-
"Vision 2030 aims to increase women's participation in the workforce from 22% to 30%.",
|
118 |
-
"The Red Sea Project is a Vision 2030 initiative to develop luxury tourism destinations across 50 islands off Saudi Arabia's Red Sea coast.",
|
119 |
-
"Qiddiya is an entertainment mega-project being built in Riyadh as part of Vision 2030.",
|
120 |
-
"The real wealth of Saudi Arabia, as emphasized in Vision 2030, is its people, particularly the youth.",
|
121 |
-
"Saudi Arabia aims to strengthen its position as a global gateway by leveraging its strategic location between Asia, Europe, and Africa.",
|
122 |
-
"Vision 2030 aims to have at least five Saudi universities among the top 200 universities in international rankings.",
|
123 |
-
"Vision 2030 sets a target of having at least 10 Saudi sites registered on the UNESCO World Heritage List.",
|
124 |
-
"Vision 2030 aims to increase the capacity to welcome Umrah visitors from 8 million to 30 million annually.",
|
125 |
-
"Vision 2030 includes multiple initiatives to strengthen Saudi national identity including cultural programs and heritage preservation.",
|
126 |
-
"Vision 2030 aims to increase non-oil government revenue from SAR 163 billion to SAR 1 trillion."
|
127 |
]
|
128 |
-
|
129 |
-
# Arabic texts
|
130 |
self.arabic_texts = [
|
131 |
-
"رؤية 2030 هي
|
132 |
"الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح.",
|
133 |
-
"
|
134 |
-
"نيوم هي مدينة ذكية مخططة عبر الحدود في مقاطعة تبوك شمال غرب المملكة العربية السعودية، وهي مشروع رئيسي من رؤية 2030.",
|
135 |
-
"تهدف رؤية 2030 إلى زيادة مشاركة المرأة في القوى العاملة من 22٪ إلى 30٪.",
|
136 |
-
"مشروع البحر الأحمر هو مبادرة رؤية 2030 لتطوير وجهات سياحية فاخرة عبر 50 جزيرة قبالة ساحل البحر الأحمر السعودي.",
|
137 |
-
"القدية هي مشروع ترفيهي ضخم يتم بناؤه في الرياض كجزء من رؤية 2030.",
|
138 |
-
"الثروة الحقيقية للمملكة العربية السعودية، كما أكدت رؤية 2030، هي شعبها، وخاصة الشباب.",
|
139 |
-
"تهدف المملكة العربية السعودية إلى تعزيز مكانتها كبوابة عالمية من خلال الاستفادة من موقعها الاستراتيجي بين آسيا وأوروبا وأفريقيا.",
|
140 |
-
"تهدف رؤية 2030 إلى أن تكون خمس جامعات سعودية على الأقل ضمن أفضل 200 جامعة في التصنيفات الدولية.",
|
141 |
-
"تضع رؤية 2030 هدفًا بتسجيل ما لا يقل عن 10 مواقع سعودية في قائمة التراث العالمي لليونسكو.",
|
142 |
-
"تهدف رؤية 2030 إلى زيادة القدرة على استقبال المعتمرين من 8 ملايين إلى 30 مليون معتمر سنويًا.",
|
143 |
-
"تتضمن رؤية 2030 مبادرات متعددة لتعزيز الهوية الوطنية السعودية بما في ذلك البرامج الثقافية والحفاظ على التراث.",
|
144 |
-
"تهدف رؤية 2030 إلى زيادة الإيرادات الحكومية غير النفطية من 163 مليار ريال سعودي إلى 1 تريليون ريال سعودي."
|
145 |
]
|
146 |
-
|
147 |
-
# Initialize PDF content containers
|
148 |
self.pdf_english_texts = []
|
149 |
self.pdf_arabic_texts = []
|
150 |
-
|
151 |
-
logger.info(f"Created knowledge base: {len(self.english_texts)} English, {len(self.arabic_texts)} Arabic texts")
|
152 |
|
153 |
@spaces.GPU
|
154 |
def _create_indices(self):
|
155 |
-
"""Create FAISS indices
|
156 |
-
logger.info("Creating FAISS indices for text retrieval")
|
157 |
-
|
158 |
try:
|
159 |
-
#
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
if self.english_vectors:
|
176 |
-
self.english_index = faiss.IndexFlatL2(len(self.english_vectors[0]))
|
177 |
-
self.english_index.add(np.array(self.english_vectors))
|
178 |
-
logger.info(f"Created English index with {len(self.english_vectors)} vectors")
|
179 |
-
else:
|
180 |
-
logger.warning("No English texts to index")
|
181 |
-
|
182 |
-
# Process and embed Arabic texts
|
183 |
-
self.arabic_vectors = []
|
184 |
-
for text in self.arabic_texts:
|
185 |
-
try:
|
186 |
-
if has_gpu and hasattr(self.arabic_embedder, 'to'):
|
187 |
-
with torch.no_grad():
|
188 |
-
vec = self.arabic_embedder.encode(text)
|
189 |
-
else:
|
190 |
-
vec = self.arabic_embedder.encode(text)
|
191 |
-
self.arabic_vectors.append(vec)
|
192 |
-
except Exception as e:
|
193 |
-
logger.error(f"Error encoding Arabic text: {str(e)}")
|
194 |
-
# Use a random vector as fallback
|
195 |
-
self.arabic_vectors.append(np.random.randn(384).astype(np.float32))
|
196 |
-
|
197 |
-
# Create Arabic index
|
198 |
-
if self.arabic_vectors:
|
199 |
-
self.arabic_index = faiss.IndexFlatL2(len(self.arabic_vectors[0]))
|
200 |
-
self.arabic_index.add(np.array(self.arabic_vectors))
|
201 |
-
logger.info(f"Created Arabic index with {len(self.arabic_vectors)} vectors")
|
202 |
-
else:
|
203 |
-
logger.warning("No Arabic texts to index")
|
204 |
-
|
205 |
-
# Create PDF indices if PDF content exists
|
206 |
-
if hasattr(self, 'pdf_english_texts') and self.pdf_english_texts:
|
207 |
-
self._create_pdf_indices()
|
208 |
-
|
209 |
except Exception as e:
|
210 |
-
logger.error(f"Error creating
|
211 |
-
|
212 |
-
def _create_pdf_indices(self):
|
213 |
-
"""Create indices for PDF content"""
|
214 |
-
if not self.pdf_english_texts and not self.pdf_arabic_texts:
|
215 |
-
return
|
216 |
-
|
217 |
-
logger.info("Creating indices for PDF content")
|
218 |
-
|
219 |
-
try:
|
220 |
-
# Process and embed English PDF texts
|
221 |
-
if self.pdf_english_texts:
|
222 |
-
self.pdf_english_vectors = []
|
223 |
-
for text in self.pdf_english_texts:
|
224 |
-
try:
|
225 |
-
if has_gpu and hasattr(self.english_embedder, 'to'):
|
226 |
-
with torch.no_grad():
|
227 |
-
vec = self.english_embedder.encode(text)
|
228 |
-
else:
|
229 |
-
vec = self.english_embedder.encode(text)
|
230 |
-
self.pdf_english_vectors.append(vec)
|
231 |
-
except Exception as e:
|
232 |
-
logger.error(f"Error encoding English PDF text: {str(e)}")
|
233 |
-
continue
|
234 |
-
|
235 |
-
if self.pdf_english_vectors:
|
236 |
-
self.pdf_english_index = faiss.IndexFlatL2(len(self.pdf_english_vectors[0]))
|
237 |
-
self.pdf_english_index.add(np.array(self.pdf_english_vectors))
|
238 |
-
logger.info(f"Created English PDF index with {len(self.pdf_english_vectors)} vectors")
|
239 |
-
|
240 |
-
# Process and embed Arabic PDF texts
|
241 |
-
if self.pdf_arabic_texts:
|
242 |
-
self.pdf_arabic_vectors = []
|
243 |
-
for text in self.pdf_arabic_texts:
|
244 |
-
try:
|
245 |
-
if has_gpu and hasattr(self.arabic_embedder, 'to'):
|
246 |
-
with torch.no_grad():
|
247 |
-
vec = self.arabic_embedder.encode(text)
|
248 |
-
else:
|
249 |
-
vec = self.arabic_embedder.encode(text)
|
250 |
-
self.pdf_arabic_vectors.append(vec)
|
251 |
-
except Exception as e:
|
252 |
-
logger.error(f"Error encoding Arabic PDF text: {str(e)}")
|
253 |
-
continue
|
254 |
-
|
255 |
-
if self.pdf_arabic_vectors:
|
256 |
-
self.pdf_arabic_index = faiss.IndexFlatL2(len(self.pdf_arabic_vectors[0]))
|
257 |
-
self.pdf_arabic_index.add(np.array(self.pdf_arabic_vectors))
|
258 |
-
logger.info(f"Created Arabic PDF index with {len(self.pdf_arabic_vectors)} vectors")
|
259 |
-
|
260 |
-
# Set flag to indicate PDF content is available
|
261 |
-
self.has_pdf_content = True
|
262 |
-
|
263 |
-
except Exception as e:
|
264 |
-
logger.error(f"Error creating PDF indices: {str(e)}")
|
265 |
-
|
266 |
def _create_sample_eval_data(self):
|
267 |
-
"""
|
268 |
self.eval_data = [
|
269 |
-
{
|
270 |
-
|
271 |
-
"lang": "en",
|
272 |
-
"reference_answer": "The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation."
|
273 |
-
},
|
274 |
-
{
|
275 |
-
"question": "ما هي الركائز الرئيسية لرؤية 2030؟",
|
276 |
-
"lang": "ar",
|
277 |
-
"reference_answer": "الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح."
|
278 |
-
},
|
279 |
-
{
|
280 |
-
"question": "What is NEOM?",
|
281 |
-
"lang": "en",
|
282 |
-
"reference_answer": "NEOM is a planned cross-border smart city in the Tabuk Province of northwestern Saudi Arabia, a key project of Vision 2030."
|
283 |
-
},
|
284 |
-
{
|
285 |
-
"question": "ما هو مشروع البحر الأحمر؟",
|
286 |
-
"lang": "ar",
|
287 |
-
"reference_answer": "مشروع البحر الأحمر هو مبادرة رؤية 2030 لتطوير وجهات سياحية فاخرة عبر 50 جزيرة قبالة ساحل البحر الأحمر السعودي."
|
288 |
-
},
|
289 |
-
{
|
290 |
-
"question": "ما هي الثروة الحقيقية التي تعتز بها المملكة كما وردت في الرؤية؟",
|
291 |
-
"lang": "ar",
|
292 |
-
"reference_answer": "الثروة الحقيقية للمملكة العربية السعودية، كما أكدت رؤية 2030، هي شعبها، وخاصة الشباب."
|
293 |
-
},
|
294 |
-
{
|
295 |
-
"question": "كيف تسعى المملكة إلى تعزيز مكانتها كبوابة للعالم؟",
|
296 |
-
"lang": "ar",
|
297 |
-
"reference_answer": "تهدف المملكة العربية السعودية إلى تعزيز مكانتها كبوابة عالمية من خلال الاستفادة من موقعها الاستراتيجي بين آسيا وأوروبا وأفريقيا."
|
298 |
-
}
|
299 |
]
|
300 |
-
logger.info(f"Created {len(self.eval_data)} sample evaluation examples")
|
301 |
|
302 |
@spaces.GPU
|
303 |
-
def retrieve_context(self, query, lang):
|
304 |
-
"""Retrieve
|
305 |
-
start_time = time.time()
|
306 |
-
|
307 |
try:
|
308 |
-
#
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
if
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
elif lang == "en" and hasattr(self, 'pdf_english_index') and hasattr(self, 'pdf_english_vectors') and len(self.pdf_english_vectors) > 0:
|
328 |
-
if has_gpu and hasattr(self.english_embedder, 'to'):
|
329 |
-
with torch.no_grad():
|
330 |
-
query_vec = self.english_embedder.encode(query)
|
331 |
-
else:
|
332 |
-
query_vec = self.english_embedder.encode(query)
|
333 |
-
|
334 |
-
D, I = self.pdf_english_index.search(np.array([query_vec]), k=2)
|
335 |
-
|
336 |
-
# If we found good matches in the PDF
|
337 |
-
if D[0][0] < 1.5: # Threshold for relevance
|
338 |
-
context = "\n".join([self.pdf_english_texts[i] for i in I[0] if i < len(self.pdf_english_texts) and i >= 0])
|
339 |
-
if context.strip():
|
340 |
-
logger.info("Retrieved context from PDF (English)")
|
341 |
-
return context
|
342 |
-
|
343 |
-
# Fall back to the pre-built knowledge base
|
344 |
-
if lang == "ar":
|
345 |
-
if has_gpu and hasattr(self.arabic_embedder, 'to'):
|
346 |
-
with torch.no_grad():
|
347 |
-
query_vec = self.arabic_embedder.encode(query)
|
348 |
-
else:
|
349 |
-
query_vec = self.arabic_embedder.encode(query)
|
350 |
-
|
351 |
-
D, I = self.arabic_index.search(np.array([query_vec]), k=2)
|
352 |
-
context = "\n".join([self.arabic_texts[i] for i in I[0] if i < len(self.arabic_texts) and i >= 0])
|
353 |
-
else:
|
354 |
-
if has_gpu and hasattr(self.english_embedder, 'to'):
|
355 |
-
with torch.no_grad():
|
356 |
-
query_vec = self.english_embedder.encode(query)
|
357 |
-
else:
|
358 |
-
query_vec = self.english_embedder.encode(query)
|
359 |
-
|
360 |
-
D, I = self.english_index.search(np.array([query_vec]), k=2)
|
361 |
-
context = "\n".join([self.english_texts[i] for i in I[0] if i < len(self.english_texts) and i >= 0])
|
362 |
-
|
363 |
-
retrieval_time = time.time() - start_time
|
364 |
-
logger.info(f"Retrieved context in {retrieval_time:.2f}s")
|
365 |
-
|
366 |
-
return context
|
367 |
except Exception as e:
|
368 |
-
logger.error(f"
|
369 |
-
return ""
|
370 |
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
start_time = time.time()
|
377 |
|
|
|
378 |
try:
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
|
|
|
|
|
|
|
|
386 |
|
387 |
-
#
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
reply = context
|
395 |
-
|
396 |
-
# Record metrics
|
397 |
-
response_time = time.time() - start_time
|
398 |
-
self.metrics["response_times"].append(response_time)
|
399 |
-
|
400 |
-
# Store the interaction
|
401 |
-
self.response_history.append({
|
402 |
-
"timestamp": datetime.now().isoformat(),
|
403 |
-
"user_input": user_input,
|
404 |
-
"response": reply,
|
405 |
-
"language": lang,
|
406 |
-
"response_time": response_time,
|
407 |
-
"source": "PDF document"
|
408 |
-
})
|
409 |
-
|
410 |
-
return reply
|
411 |
|
412 |
def evaluate_factual_accuracy(self, response, reference):
|
413 |
-
"""
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
keywords_response = {w for w in keywords_response if w not in english_stopwords and w not in arabic_stopwords}
|
424 |
-
|
425 |
-
common_keywords = keywords_reference.intersection(keywords_response)
|
426 |
-
|
427 |
-
if len(keywords_reference) > 0:
|
428 |
-
accuracy = len(common_keywords) / len(keywords_reference)
|
429 |
-
else:
|
430 |
-
accuracy = 0
|
431 |
-
|
432 |
-
return accuracy
|
433 |
-
|
434 |
-
@spaces.GPU
|
435 |
-
def evaluate_on_test_set(self):
|
436 |
-
"""Evaluate the assistant on the test set"""
|
437 |
-
logger.info("Running evaluation on test set")
|
438 |
-
|
439 |
-
eval_results = []
|
440 |
-
|
441 |
-
for example in self.eval_data:
|
442 |
-
# Generate response
|
443 |
-
response = self.generate_response(example["question"])
|
444 |
-
|
445 |
-
# Calculate factual accuracy
|
446 |
-
accuracy = self.evaluate_factual_accuracy(response, example["reference_answer"])
|
447 |
-
|
448 |
-
eval_results.append({
|
449 |
-
"question": example["question"],
|
450 |
-
"reference": example["reference_answer"],
|
451 |
-
"response": response,
|
452 |
-
"factual_accuracy": accuracy
|
453 |
-
})
|
454 |
-
|
455 |
-
self.metrics["factual_accuracy"].append(accuracy)
|
456 |
-
|
457 |
-
# Calculate average factual accuracy
|
458 |
-
avg_accuracy = sum(self.metrics["factual_accuracy"]) / len(self.metrics["factual_accuracy"]) if self.metrics["factual_accuracy"] else 0
|
459 |
-
avg_response_time = sum(self.metrics["response_times"]) / len(self.metrics["response_times"]) if self.metrics["response_times"] else 0
|
460 |
-
|
461 |
-
results = {
|
462 |
-
"average_factual_accuracy": avg_accuracy,
|
463 |
-
"average_response_time": avg_response_time,
|
464 |
-
"detailed_results": eval_results
|
465 |
-
}
|
466 |
-
|
467 |
-
logger.info(f"Evaluation results: Factual accuracy = {avg_accuracy:.2f}, Avg response time = {avg_response_time:.2f}s")
|
468 |
-
|
469 |
-
return results
|
470 |
-
|
471 |
-
def visualize_evaluation_results(self, results):
|
472 |
-
"""Generate visualization of evaluation results"""
|
473 |
-
# Create a DataFrame from the detailed results
|
474 |
-
df = pd.DataFrame(results["detailed_results"])
|
475 |
-
|
476 |
-
# Create the figure for visualizations
|
477 |
-
fig = plt.figure(figsize=(12, 8))
|
478 |
-
|
479 |
-
# Bar chart of factual accuracy by question
|
480 |
-
plt.subplot(2, 1, 1)
|
481 |
-
bars = plt.bar(range(len(df)), df["factual_accuracy"], color="skyblue")
|
482 |
-
plt.axhline(y=results["average_factual_accuracy"], color='r', linestyle='-',
|
483 |
-
label=f"Avg: {results['average_factual_accuracy']:.2f}")
|
484 |
-
plt.xlabel("Question Index")
|
485 |
-
plt.ylabel("Factual Accuracy")
|
486 |
-
plt.title("Factual Accuracy by Question")
|
487 |
-
plt.ylim(0, 1.1)
|
488 |
-
plt.legend()
|
489 |
-
|
490 |
-
# Add language information
|
491 |
-
df["language"] = df["question"].apply(lambda x: "Arabic" if detect(x) == "ar" else "English")
|
492 |
-
|
493 |
-
# Group by language
|
494 |
-
lang_accuracy = df.groupby("language")["factual_accuracy"].mean()
|
495 |
-
|
496 |
-
# Bar chart of accuracy by language
|
497 |
-
plt.subplot(2, 1, 2)
|
498 |
-
lang_bars = plt.bar(lang_accuracy.index, lang_accuracy.values, color=["lightblue", "lightgreen"])
|
499 |
-
plt.axhline(y=results["average_factual_accuracy"], color='r', linestyle='-',
|
500 |
-
label=f"Overall: {results['average_factual_accuracy']:.2f}")
|
501 |
-
plt.xlabel("Language")
|
502 |
-
plt.ylabel("Average Factual Accuracy")
|
503 |
-
plt.title("Factual Accuracy by Language")
|
504 |
-
plt.ylim(0, 1.1)
|
505 |
-
|
506 |
-
# Add value labels
|
507 |
-
for i, v in enumerate(lang_accuracy):
|
508 |
-
plt.text(i, v + 0.05, f"{v:.2f}", ha='center')
|
509 |
-
|
510 |
-
plt.tight_layout()
|
511 |
-
return fig
|
512 |
-
|
513 |
-
def record_user_feedback(self, user_input, response, rating, feedback_text=""):
|
514 |
-
"""Record user feedback for a response"""
|
515 |
-
feedback = {
|
516 |
-
"timestamp": datetime.now().isoformat(),
|
517 |
-
"user_input": user_input,
|
518 |
-
"response": response,
|
519 |
-
"rating": rating,
|
520 |
-
"feedback_text": feedback_text
|
521 |
-
}
|
522 |
-
|
523 |
-
self.metrics["user_ratings"].append(rating)
|
524 |
-
|
525 |
-
# In a production system, store this in a database
|
526 |
-
logger.info(f"Recorded user feedback: rating={rating}")
|
527 |
-
|
528 |
-
return True
|
529 |
|
530 |
@spaces.GPU
|
531 |
def process_pdf(self, file):
|
532 |
-
"""Process
|
533 |
-
if file
|
534 |
-
return "
|
535 |
|
536 |
try:
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
#
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
# Process the extracted text into meaningful chunks
|
565 |
-
# Default chunk size of ~200-300 characters for better semantic indexing
|
566 |
-
chunks = []
|
567 |
-
|
568 |
-
# Using sentences as more meaningful units than arbitrary chunks
|
569 |
-
sentences = re.split(r'(?<=[.!?])\s+', full_text)
|
570 |
-
current_chunk = ""
|
571 |
-
|
572 |
-
for sentence in sentences:
|
573 |
-
if not sentence.strip():
|
574 |
-
continue
|
575 |
-
|
576 |
-
# If adding this sentence would make chunk too big, save current and start new
|
577 |
-
if len(current_chunk) + len(sentence) > 300:
|
578 |
-
if current_chunk:
|
579 |
-
chunks.append(current_chunk.strip())
|
580 |
-
current_chunk = sentence
|
581 |
-
else:
|
582 |
-
current_chunk += " " + sentence if current_chunk else sentence
|
583 |
-
|
584 |
-
# Add the last chunk if any
|
585 |
-
if current_chunk:
|
586 |
-
chunks.append(current_chunk.strip())
|
587 |
-
|
588 |
-
# Filter out very short chunks (likely noise)
|
589 |
-
chunks = [chunk for chunk in chunks if len(chunk.strip()) > 30]
|
590 |
-
|
591 |
-
# Categorize by language with focus on accurate detection
|
592 |
-
english_chunks = []
|
593 |
-
arabic_chunks = []
|
594 |
|
595 |
-
for chunk in chunks:
|
596 |
-
try:
|
597 |
-
# Check for Arabic characters first (more reliable)
|
598 |
-
if any('\u0600' <= c <= '\u06FF' for c in chunk):
|
599 |
-
arabic_chunks.append(chunk)
|
600 |
-
else:
|
601 |
-
# Use language detection as backup
|
602 |
-
lang = detect(chunk)
|
603 |
-
if lang == "ar":
|
604 |
-
arabic_chunks.append(chunk)
|
605 |
-
else:
|
606 |
-
english_chunks.append(chunk)
|
607 |
-
except:
|
608 |
-
# If detection fails, check for Arabic characters
|
609 |
-
if any('\u0600' <= c <= '\u06FF' for c in chunk):
|
610 |
-
arabic_chunks.append(chunk)
|
611 |
-
else:
|
612 |
-
english_chunks.append(chunk)
|
613 |
-
|
614 |
-
# Replace PDF content with new content
|
615 |
-
self.pdf_english_texts = english_chunks
|
616 |
-
self.pdf_arabic_texts = arabic_chunks
|
617 |
-
|
618 |
-
# Create high-quality embeddings - this is critical for accurate retrieval
|
619 |
-
self._create_pdf_indices()
|
620 |
-
|
621 |
-
# Mark system to prioritize document content over pre-defined answers
|
622 |
self.has_pdf_content = True
|
623 |
-
self.
|
624 |
-
|
625 |
-
logger.info(f"Successfully processed PDF: {len(arabic_chunks)} Arabic and {len(english_chunks)} English segments")
|
626 |
-
|
627 |
-
# Also modify the retrieval threshold to ensure better matches
|
628 |
-
self.pdf_relevance_threshold = 1.2 # Lower threshold = stricter matching
|
629 |
-
|
630 |
-
return f"✅ Successfully processed your PDF! Found {len(arabic_chunks)} Arabic and {len(english_chunks)} English text segments. The system will now answer questions directly from your document content."
|
631 |
-
|
632 |
except Exception as e:
|
633 |
-
logger.error(f"
|
634 |
-
return f"
|
635 |
-
|
636 |
-
#
|
637 |
def create_interface():
|
638 |
-
# Initialize the assistant
|
639 |
assistant = Vision2030Assistant()
|
640 |
|
641 |
-
def chat(
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
# Generate response
|
646 |
-
reply = assistant.generate_response(message)
|
647 |
-
|
648 |
-
# Update history
|
649 |
-
history.append((message, reply))
|
650 |
-
|
651 |
return history, ""
|
652 |
|
653 |
-
def provide_feedback(history, rating, feedback_text):
|
654 |
-
# Record feedback for the last conversation
|
655 |
-
if history and len(history) > 0:
|
656 |
-
last_interaction = history[-1]
|
657 |
-
assistant.record_user_feedback(last_interaction[0], last_interaction[1], rating, feedback_text)
|
658 |
-
return f"Thank you for your feedback! (Rating: {rating}/5)"
|
659 |
-
return "No conversation found to rate."
|
660 |
-
|
661 |
-
@spaces.GPU
|
662 |
-
def run_evaluation():
|
663 |
-
results = assistant.evaluate_on_test_set()
|
664 |
-
|
665 |
-
# Create summary text
|
666 |
-
summary = f"""
|
667 |
-
Evaluation Results:
|
668 |
-
------------------
|
669 |
-
Total questions evaluated: {len(results['detailed_results'])}
|
670 |
-
Overall factual accuracy: {results['average_factual_accuracy']:.2f}
|
671 |
-
Average response time: {results['average_response_time']:.4f} seconds
|
672 |
-
|
673 |
-
Detailed Results:
|
674 |
-
"""
|
675 |
-
|
676 |
-
for i, result in enumerate(results['detailed_results']):
|
677 |
-
summary += f"\nQ{i+1}: {result['question']}\n"
|
678 |
-
summary += f"Reference: {result['reference']}\n"
|
679 |
-
summary += f"Response: {result['response']}\n"
|
680 |
-
summary += f"Accuracy: {result['factual_accuracy']:.2f}\n"
|
681 |
-
summary += "-" * 40 + "\n"
|
682 |
-
|
683 |
-
# Return both the results summary and visualization
|
684 |
-
fig = assistant.visualize_evaluation_results(results)
|
685 |
-
|
686 |
-
return summary, fig
|
687 |
-
|
688 |
-
def process_uploaded_file(file):
|
689 |
-
"""Process the uploaded PDF file"""
|
690 |
-
return assistant.process_pdf(file)
|
691 |
-
|
692 |
-
# Create the Gradio interface
|
693 |
with gr.Blocks() as demo:
|
694 |
-
gr.Markdown("# Vision 2030 Virtual Assistant
|
695 |
-
gr.
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
gr.Markdown("### Provide Feedback")
|
705 |
-
with gr.Row():
|
706 |
-
rating = gr.Slider(minimum=1, maximum=5, step=1, value=3, label="Rate the Response (1-5)")
|
707 |
-
feedback_text = gr.Textbox(label="Additional Comments (Optional)")
|
708 |
-
feedback_btn = gr.Button("Submit Feedback")
|
709 |
-
feedback_result = gr.Textbox(label="Feedback Status")
|
710 |
-
|
711 |
-
with gr.Tab("Evaluation"):
|
712 |
-
evaluate_btn = gr.Button("Run Evaluation on Test Set")
|
713 |
-
eval_output = gr.Textbox(label="Evaluation Results", lines=20)
|
714 |
-
eval_chart = gr.Plot(label="Evaluation Metrics")
|
715 |
-
|
716 |
-
with gr.Tab("Upload PDF"):
|
717 |
-
gr.Markdown("""
|
718 |
-
### Upload a Vision 2030 PDF Document
|
719 |
-
Upload a PDF document to enhance the assistant's knowledge base.
|
720 |
-
""")
|
721 |
-
|
722 |
-
with gr.Row():
|
723 |
-
file_input = gr.File(
|
724 |
-
label="Select PDF File",
|
725 |
-
file_types=[".pdf"],
|
726 |
-
type="binary" # This is critical - use binary mode
|
727 |
-
)
|
728 |
-
|
729 |
-
with gr.Row():
|
730 |
-
upload_btn = gr.Button("Process PDF", variant="primary")
|
731 |
-
|
732 |
-
with gr.Row():
|
733 |
-
upload_status = gr.Textbox(
|
734 |
-
label="Upload Status",
|
735 |
-
placeholder="Upload status will appear here...",
|
736 |
-
interactive=False
|
737 |
-
)
|
738 |
-
|
739 |
-
gr.Markdown("""
|
740 |
-
### Notes:
|
741 |
-
- The PDF should contain text that can be extracted (not scanned images)
|
742 |
-
- After uploading, return to the Chat tab to ask questions about the uploaded content
|
743 |
-
""")
|
744 |
-
|
745 |
-
# Set up event handlers
|
746 |
-
msg.submit(chat, [msg, chatbot], [chatbot, msg])
|
747 |
-
submit_btn.click(chat, [msg, chatbot], [chatbot, msg])
|
748 |
-
clear_btn.click(lambda: [], None, chatbot)
|
749 |
-
feedback_btn.click(provide_feedback, [chatbot, rating, feedback_text], feedback_result)
|
750 |
-
evaluate_btn.click(run_evaluation, None, [eval_output, eval_chart])
|
751 |
-
upload_btn.click(process_uploaded_file, [file_input], [upload_status])
|
752 |
|
753 |
return demo
|
754 |
|
755 |
-
# Launch the app
|
756 |
demo = create_interface()
|
757 |
demo.launch()
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import time
|
3 |
import logging
|
|
|
7 |
import numpy as np
|
8 |
import pandas as pd
|
9 |
import matplotlib.pyplot as plt
|
10 |
+
from sentence_transformers import SentenceTransformer, util
|
|
|
|
|
|
|
|
|
|
|
11 |
import faiss
|
12 |
import torch
|
13 |
import spaces
|
14 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
15 |
+
import PyPDF2
|
16 |
+
import io
|
17 |
|
18 |
+
# Configure logging for debugging and monitoring
|
19 |
logging.basicConfig(
|
20 |
level=logging.INFO,
|
21 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
22 |
handlers=[logging.StreamHandler()]
|
23 |
)
|
24 |
+
logger = logging.getLogger('Vision2030Assistant')
|
25 |
|
26 |
# Check for GPU availability
|
27 |
has_gpu = torch.cuda.is_available()
|
|
|
29 |
|
30 |
class Vision2030Assistant:
|
31 |
def __init__(self):
|
32 |
+
"""Initialize the assistant with enhanced features"""
|
33 |
logger.info("Initializing Vision 2030 Assistant...")
|
34 |
|
35 |
+
# Load models with error handling
|
36 |
self.load_embedding_models()
|
37 |
+
self.load_language_model()
|
38 |
|
39 |
+
# Initialize knowledge base and indices
|
40 |
self._create_knowledge_base()
|
41 |
self._create_indices()
|
42 |
|
43 |
+
# Sample evaluation data
|
44 |
self._create_sample_eval_data()
|
45 |
|
46 |
+
# Metrics storage
|
47 |
+
self.metrics = {"response_times": [], "user_ratings": [], "factual_accuracy": []}
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
+
# Session management
|
50 |
+
self.session_history = {}
|
51 |
+
|
52 |
+
# PDF content flag
|
53 |
self.has_pdf_content = False
|
54 |
|
55 |
+
logger.info("Assistant initialized successfully")
|
56 |
+
|
57 |
@spaces.GPU
|
58 |
def load_embedding_models(self):
|
59 |
+
"""Load embedding models with fallback"""
|
|
|
|
|
60 |
try:
|
|
|
61 |
self.arabic_embedder = SentenceTransformer('CAMeL-Lab/bert-base-arabic-camelbert-ca')
|
62 |
self.english_embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
|
|
|
|
63 |
if has_gpu:
|
64 |
self.arabic_embedder = self.arabic_embedder.to('cuda')
|
65 |
self.english_embedder = self.english_embedder.to('cuda')
|
|
|
|
|
66 |
logger.info("Embedding models loaded successfully")
|
67 |
except Exception as e:
|
68 |
+
logger.error(f"Failed to load embedding models: {e}")
|
69 |
+
self._fallback_embedding()
|
70 |
|
71 |
+
def _fallback_embedding(self):
|
72 |
+
"""Fallback to simple embedding if model loading fails"""
|
73 |
+
logger.warning("Using fallback embedding method")
|
74 |
+
def simple_embed(text):
|
|
|
|
|
75 |
import hashlib
|
76 |
+
hash_obj = hashlib.md5(text.encode())
|
77 |
+
np.random.seed(int(hash_obj.hexdigest(), 16) % 2**32)
|
78 |
+
return np.random.randn(384).astype(np.float32)
|
|
|
|
|
|
|
79 |
|
|
|
80 |
class SimpleEmbedder:
|
|
|
|
|
|
|
81 |
def encode(self, text):
|
82 |
+
return simple_embed(text)
|
83 |
|
84 |
self.arabic_embedder = SimpleEmbedder()
|
85 |
self.english_embedder = SimpleEmbedder()
|
86 |
|
87 |
+
@spaces.GPU
|
88 |
+
def load_language_model(self):
|
89 |
+
"""Load language model for advanced response generation"""
|
90 |
+
try:
|
91 |
+
self.tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
92 |
+
self.model = AutoModelForCausalLM.from_pretrained("distilgpt2")
|
93 |
+
if has_gpu:
|
94 |
+
self.model = self.model.to('cuda')
|
95 |
+
self.generator = pipeline('text-generation', model=self.model, tokenizer=self.tokenizer, device=0 if has_gpu else -1)
|
96 |
+
logger.info("Language model loaded successfully")
|
97 |
+
except Exception as e:
|
98 |
+
logger.error(f"Failed to load language model: {e}")
|
99 |
+
self.generator = None
|
100 |
+
|
101 |
def _create_knowledge_base(self):
|
102 |
+
"""Create initial knowledge base"""
|
|
|
|
|
|
|
103 |
self.english_texts = [
|
104 |
"Vision 2030 is Saudi Arabia's strategic framework to reduce dependence on oil, diversify the economy, and develop public sectors.",
|
105 |
"The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation.",
|
106 |
+
"NEOM is a planned smart city in Tabuk Province, a key Vision 2030 project."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
]
|
|
|
|
|
108 |
self.arabic_texts = [
|
109 |
+
"رؤية 2030 هي إطار استراتيجي لتقليل الاعتماد على النفط وتنويع الاقتصاد.",
|
110 |
"الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح.",
|
111 |
+
"نيوم مدينة ذكية مخططة في تبوك، مشروع رئيسي لرؤية 2030."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
]
|
|
|
|
|
113 |
self.pdf_english_texts = []
|
114 |
self.pdf_arabic_texts = []
|
|
|
|
|
115 |
|
116 |
@spaces.GPU
|
117 |
def _create_indices(self):
|
118 |
+
"""Create scalable FAISS indices"""
|
|
|
|
|
119 |
try:
|
120 |
+
# English index with IVF for scalability
|
121 |
+
english_vectors = [self.english_embedder.encode(text) for text in self.english_texts]
|
122 |
+
dim = len(english_vectors[0])
|
123 |
+
nlist = max(1, len(english_vectors) // 10)
|
124 |
+
quantizer = faiss.IndexFlatL2(dim)
|
125 |
+
self.english_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
|
126 |
+
self.english_index.train(np.array(english_vectors))
|
127 |
+
self.english_index.add(np.array(english_vectors))
|
128 |
+
|
129 |
+
# Arabic index
|
130 |
+
arabic_vectors = [self.arabic_embedder.encode(text) for text in self.arabic_texts]
|
131 |
+
self.arabic_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
|
132 |
+
self.arabic_index.train(np.array(arabic_vectors))
|
133 |
+
self.arabic_index.add(np.array(arabic_vectors))
|
134 |
+
|
135 |
+
logger.info("FAISS indices created successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
except Exception as e:
|
137 |
+
logger.error(f"Error creating indices: {e}")
|
138 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
def _create_sample_eval_data(self):
|
140 |
+
"""Sample evaluation data"""
|
141 |
self.eval_data = [
|
142 |
+
{"question": "What are the key pillars of Vision 2030?", "lang": "en", "reference": "The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation."},
|
143 |
+
{"question": "ما هي الركائز الرئيسية لرؤية 2030؟", "lang": "ar", "reference": "الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
]
|
|
|
145 |
|
146 |
@spaces.GPU
|
147 |
+
def retrieve_context(self, query, lang, session_id):
|
148 |
+
"""Retrieve context with session history integration"""
|
|
|
|
|
149 |
try:
|
150 |
+
# Incorporate session history
|
151 |
+
history = self.session_history.get(session_id, [])
|
152 |
+
history_context = " ".join([f"Q: {q} A: {a}" for q, a in history[-2:]]) # Last 2 interactions
|
153 |
+
|
154 |
+
# Embed query
|
155 |
+
embedder = self.arabic_embedder if lang == "ar" else self.english_embedder
|
156 |
+
query_vec = embedder.encode(query)
|
157 |
+
|
158 |
+
# Search appropriate index
|
159 |
+
index = self.pdf_arabic_index if (lang == "ar" and self.has_pdf_content) else \
|
160 |
+
self.pdf_english_index if (lang == "en" and self.has_pdf_content) else \
|
161 |
+
self.arabic_index if lang == "ar" else self.english_index
|
162 |
+
texts = self.pdf_arabic_texts if (lang == "ar" and self.has_pdf_content) else \
|
163 |
+
self.pdf_english_texts if (lang == "en" and self.has_pdf_content) else \
|
164 |
+
self.arabic_texts if lang == "ar" else self.english_texts
|
165 |
+
|
166 |
+
D, I = index.search(np.array([query_vec]), k=2)
|
167 |
+
context = "\n".join([texts[i] for i in I[0] if i >= 0]) + f"\nHistory: {history_context}"
|
168 |
+
return context if context.strip() else "No relevant information found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
169 |
except Exception as e:
|
170 |
+
logger.error(f"Retrieval error: {e}")
|
171 |
+
return "Error retrieving context."
|
172 |
|
173 |
+
@spaces.GPU
|
174 |
+
def generate_response(self, query, session_id):
|
175 |
+
"""Generate advanced responses with error handling"""
|
176 |
+
if not query.strip():
|
177 |
+
return "Please enter a valid question."
|
|
|
178 |
|
179 |
+
start_time = time.time()
|
180 |
try:
|
181 |
+
lang = "ar" if any('\u0600' <= c <= '\u06FF' for c in query) else "en"
|
182 |
+
context = self.retrieve_context(query, lang, session_id)
|
183 |
+
|
184 |
+
if "Error" in context or "No relevant" in context:
|
185 |
+
reply = context
|
186 |
+
elif self.generator:
|
187 |
+
prompt = f"Context: {context}\nQuestion: {query}\nAnswer:"
|
188 |
+
response = self.generator(prompt, max_length=150, num_return_sequences=1, do_sample=True, temperature=0.7)
|
189 |
+
reply = response[0]['generated_text'].split("Answer:")[-1].strip()
|
190 |
+
else:
|
191 |
+
reply = context # Fallback
|
192 |
|
193 |
+
# Update session history
|
194 |
+
self.session_history.setdefault(session_id, []).append((query, reply))
|
195 |
+
self.metrics["response_times"].append(time.time() - start_time)
|
196 |
+
return reply
|
197 |
+
except Exception as e:
|
198 |
+
logger.error(f"Response generation error: {e}")
|
199 |
+
return "Sorry, an error occurred. Please try again."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
201 |
def evaluate_factual_accuracy(self, response, reference):
|
202 |
+
"""Evaluate using semantic similarity"""
|
203 |
+
try:
|
204 |
+
embedder = self.english_embedder # Assuming reference is in English; extend for Arabic if needed
|
205 |
+
response_vec = embedder.encode(response)
|
206 |
+
reference_vec = embedder.encode(reference)
|
207 |
+
similarity = util.cos_sim(response_vec, reference_vec).item()
|
208 |
+
return similarity
|
209 |
+
except Exception as e:
|
210 |
+
logger.error(f"Evaluation error: {e}")
|
211 |
+
return 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
212 |
|
213 |
@spaces.GPU
|
214 |
def process_pdf(self, file):
|
215 |
+
"""Process PDF with scalability and error handling"""
|
216 |
+
if not file:
|
217 |
+
return "Please upload a PDF file."
|
218 |
|
219 |
try:
|
220 |
+
pdf_reader = PyPDF2.PdfReader(io.BytesIO(file))
|
221 |
+
text = "".join([page.extract_text() or "" for page in pdf_reader.pages])
|
222 |
+
if not text.strip():
|
223 |
+
return "No extractable text found in PDF."
|
224 |
+
|
225 |
+
# Chunk text for scalability
|
226 |
+
chunks = [text[i:i+300] for i in range(0, len(text), 300)]
|
227 |
+
self.pdf_english_texts = [c for c in chunks if not any('\u0600' <= char <= '\u06FF' for char in c)]
|
228 |
+
self.pdf_arabic_texts = [c for c in chunks if any('\u0600' <= char <= '\u06FF' for char in c)]
|
229 |
+
|
230 |
+
# Batch process embeddings
|
231 |
+
batch_size = 32
|
232 |
+
for lang, texts, embedder in [("en", self.pdf_english_texts, self.english_embedder),
|
233 |
+
("ar", self.pdf_arabic_texts, self.arabic_embedder)]:
|
234 |
+
if texts:
|
235 |
+
vectors = []
|
236 |
+
for i in range(0, len(texts), batch_size):
|
237 |
+
batch = texts[i:i+batch_size]
|
238 |
+
vectors.extend(embedder.encode(batch))
|
239 |
+
dim = len(vectors[0])
|
240 |
+
nlist = max(1, len(vectors) // 10)
|
241 |
+
quantizer = faiss.IndexFlatL2(dim)
|
242 |
+
index = faiss.IndexIVFFlat(quantizer, dim, nlist)
|
243 |
+
index.train(np.array(vectors))
|
244 |
+
index.add(np.array(vectors))
|
245 |
+
setattr(self, f"pdf_{lang}_index", index)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
247 |
self.has_pdf_content = True
|
248 |
+
return f"PDF processed: {len(self.pdf_english_texts)} English, {len(self.pdf_arabic_texts)} Arabic chunks."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
except Exception as e:
|
250 |
+
logger.error(f"PDF processing error: {e}")
|
251 |
+
return f"Error processing PDF: {e}"
|
252 |
+
|
253 |
+
# Gradio Interface
|
254 |
def create_interface():
|
|
|
255 |
assistant = Vision2030Assistant()
|
256 |
|
257 |
+
def chat(query, history, session_id):
|
258 |
+
reply = assistant.generate_response(query, session_id)
|
259 |
+
history.append((query, reply))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
260 |
return history, ""
|
261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
262 |
with gr.Blocks() as demo:
|
263 |
+
gr.Markdown("# Vision 2030 Virtual Assistant")
|
264 |
+
session_id = gr.State(value="user1") # Simple session ID; enhance with authentication
|
265 |
+
chatbot = gr.Chatbot()
|
266 |
+
msg = gr.Textbox(label="Ask a question")
|
267 |
+
submit = gr.Button("Submit")
|
268 |
+
pdf_upload = gr.File(label="Upload PDF", type="binary")
|
269 |
+
upload_status = gr.Textbox(label="Upload Status")
|
270 |
+
|
271 |
+
submit.click(chat, [msg, chatbot, session_id], [chatbot, msg])
|
272 |
+
pdf_upload.upload(assistant.process_pdf, pdf_upload, upload_status)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
|
274 |
return demo
|
275 |
|
|
|
276 |
demo = create_interface()
|
277 |
demo.launch()
|