abdull4h commited on
Commit
64f3706
·
verified ·
1 Parent(s): d04e4d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +694 -191
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # Import necessary libraries
2
  import gradio as gr
3
  import time
4
  import logging
@@ -7,267 +7,770 @@ import re
7
  from datetime import datetime
8
  import numpy as np
9
  import pandas as pd
10
- from sentence_transformers import SentenceTransformer, util
11
- import faiss
12
- import torch
13
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
14
  import PyPDF2
15
  import io
16
- import spaces # Added for @spaces.GPU decorator
 
 
 
 
 
17
 
18
- # Set up logging
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()
28
  logger.info(f"GPU available: {has_gpu}")
29
 
30
- # Define the Vision2030Assistant class
31
  class Vision2030Assistant:
32
  def __init__(self):
33
- """Initialize the Vision 2030 Assistant with models, knowledge base, and indices."""
34
  logger.info("Initializing Vision 2030 Assistant...")
 
 
35
  self.load_embedding_models()
36
- self.load_language_model()
 
37
  self._create_knowledge_base()
38
  self._create_indices()
 
 
39
  self._create_sample_eval_data()
40
- self.metrics = {"response_times": [], "user_ratings": [], "factual_accuracy": []}
41
- self.session_history = {} # Dictionary to store session history
42
- self.has_pdf_content = False # Flag to indicate if PDF content is available
43
- logger.info("Assistant initialized successfully")
44
-
 
 
 
 
 
 
 
 
 
 
45
  def load_embedding_models(self):
46
- """Load Arabic and English embedding models on CPU."""
 
 
47
  try:
 
48
  self.arabic_embedder = SentenceTransformer('CAMeL-Lab/bert-base-arabic-camelbert-ca')
49
  self.english_embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
50
- # Models remain on CPU; GPU usage handled in decorated functions
 
 
 
 
 
 
51
  logger.info("Embedding models loaded successfully")
52
  except Exception as e:
53
- logger.error(f"Failed to load embedding models: {e}")
54
- self._fallback_embedding()
55
 
56
- def _fallback_embedding(self):
57
- """Fallback method for embedding models using a simple random vector approach."""
58
- logger.warning("Using fallback embedding method")
 
 
 
 
 
 
 
 
 
 
 
 
59
  class SimpleEmbedder:
60
- def encode(self, text, device=None): # Added device parameter for compatibility
61
- import hashlib
62
- hash_obj = hashlib.md5(text.encode())
63
- np.random.seed(int(hash_obj.hexdigest(), 16) % 2**32)
64
- return np.random.randn(384).astype(np.float32)
 
65
  self.arabic_embedder = SimpleEmbedder()
66
  self.english_embedder = SimpleEmbedder()
67
 
68
- def load_language_model(self):
69
- """Load the DistilGPT-2 language model on CPU."""
70
- try:
71
- self.tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
72
- self.model = AutoModelForCausalLM.from_pretrained("distilgpt2")
73
- self.generator = pipeline(
74
- 'text-generation',
75
- model=self.model,
76
- tokenizer=self.tokenizer,
77
- device=-1 # CPU
78
- )
79
- logger.info("Language model loaded successfully")
80
- except Exception as e:
81
- logger.error(f"Failed to load language model: {e}")
82
- self.generator = None
83
-
84
  def _create_knowledge_base(self):
85
- """Initialize the knowledge base with basic Vision 2030 information."""
 
 
 
86
  self.english_texts = [
87
  "Vision 2030 is Saudi Arabia's strategic framework to reduce dependence on oil, diversify the economy, and develop public sectors.",
88
  "The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation.",
89
- "NEOM is a planned smart city in Tabuk Province, a key Vision 2030 project."
 
 
 
 
 
 
 
 
 
 
 
90
  ]
 
 
91
  self.arabic_texts = [
92
- "رؤية 2030 هي إطار استراتيجي لتقليل الاعتماد على النفط وتنويع الاقتصاد.",
93
  "الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح.",
94
- "نيوم مدينة ذكية مخططة في تبوك، مشروع رئيسي لرؤية 2030."
 
 
 
 
 
 
 
 
 
 
 
95
  ]
 
 
96
  self.pdf_english_texts = []
97
  self.pdf_arabic_texts = []
 
 
98
 
 
99
  def _create_indices(self):
100
- """Create FAISS indices for the initial knowledge base on CPU."""
 
 
101
  try:
102
- # English index
103
- english_vectors = [self.english_embedder.encode(text) for text in self.english_texts]
104
- dim = len(english_vectors[0])
105
- nlist = max(1, len(english_vectors) // 10)
106
- quantizer = faiss.IndexFlatL2(dim)
107
- self.english_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
108
- self.english_index.train(np.array(english_vectors))
109
- self.english_index.add(np.array(english_vectors))
110
-
111
- # Arabic index
112
- arabic_vectors = [self.arabic_embedder.encode(text) for text in self.arabic_texts]
113
- self.arabic_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
114
- self.arabic_index.train(np.array(arabic_vectors))
115
- self.arabic_index.add(np.array(arabic_vectors))
116
- logger.info("FAISS indices created successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  except Exception as e:
118
- logger.error(f"Error creating indices: {e}")
119
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  def _create_sample_eval_data(self):
121
- """Create sample evaluation data for testing factual accuracy."""
122
  self.eval_data = [
123
- {"question": "What are the key pillars of Vision 2030?",
124
- "lang": "en",
125
- "reference": "The key pillars of Vision 2030 are a vibrant society, a thriving economy, and an ambitious nation."},
126
- {"question": "ما هي الركائز الرئيسية لرؤية 2030؟",
127
- "lang": "ar",
128
- "reference": "الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  ]
 
130
 
131
- def retrieve_context(self, query, lang, session_id, device='cpu'):
132
- """Retrieve relevant context using the specified device for encoding."""
 
 
 
133
  try:
134
- history = self.session_history.get(session_id, [])
135
- history_context = " ".join([f"Q: {q} A: {a}" for q, a in history[-2:]])
136
- embedder = self.arabic_embedder if lang == "ar" else self.english_embedder
137
- query_vec = embedder.encode(query, device=device)
138
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  if lang == "ar":
140
- if self.has_pdf_content and self.pdf_arabic_texts:
141
- index = self.pdf_arabic_index
142
- texts = self.pdf_arabic_texts
143
  else:
144
- index = self.arabic_index
145
- texts = self.arabic_texts
 
 
146
  else:
147
- if self.has_pdf_content and self.pdf_english_texts:
148
- index = self.pdf_english_index
149
- texts = self.pdf_english_texts
150
  else:
151
- index = self.english_index
152
- texts = self.english_texts
153
-
154
- D, I = index.search(np.array([query_vec]), k=2)
155
- context = "\n".join([texts[i] for i in I[0] if i >= 0]) + f"\nHistory: {history_context}"
156
- return context if context.strip() else "No relevant information found."
 
 
 
157
  except Exception as e:
158
- logger.error(f"Retrieval error: {e}")
159
- return "Error retrieving context."
160
-
161
- @spaces.GPU
162
- def generate_response(self, query, session_id):
163
- """Generate a response using GPU resources when available."""
164
- if not query.strip():
165
- return "Please enter a valid question."
166
 
 
 
 
 
 
167
  start_time = time.time()
 
 
 
 
 
 
 
168
  try:
169
- lang = "ar" if any('\u0600' <= c <= '\u06FF' for c in query) else "en"
170
- context = self.retrieve_context(query, lang, session_id, device='cuda')
171
-
172
- if "Error" in context or "No relevant" in context:
173
- reply = context
174
- elif self.generator:
175
- # Move the language model to GPU
176
- self.generator.model.to('cuda')
177
- prompt = f"Context: {context}\nQuestion: {query}\nAnswer:"
178
- response = self.generator(prompt, max_length=150, num_return_sequences=1, do_sample=True, temperature=0.7)
179
- reply = response[0]['generated_text'].split("Answer:")[-1].strip()
180
- # Move the language model back to CPU
181
- self.generator.model.to('cpu')
182
- else:
183
- reply = context
184
-
185
- self.session_history.setdefault(session_id, []).append((query, reply))
186
- self.metrics["response_times"].append(time.time() - start_time)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  return reply
 
188
  except Exception as e:
189
- logger.error(f"Response generation error: {e}")
190
- return "Sorry, an error occurred. Please try again."
191
 
192
  def evaluate_factual_accuracy(self, response, reference):
193
- """Evaluate the factual accuracy of a response using semantic similarity."""
194
- try:
195
- embedder = self.english_embedder # Assuming reference is in English for simplicity
196
- response_vec = embedder.encode(response)
197
- reference_vec = embedder.encode(reference)
198
- similarity = util.cos_sim(response_vec, reference_vec).item()
199
- return similarity
200
- except Exception as e:
201
- logger.error(f"Evaluation error: {e}")
202
- return 0.0
 
 
 
 
 
 
 
 
 
 
203
 
204
  @spaces.GPU
205
- def process_pdf(self, file):
206
- """Process a PDF file and update the knowledge base using GPU for encoding."""
207
- if not file:
208
- return "Please upload a PDF file."
209
-
210
- try:
211
- pdf_reader = PyPDF2.PdfReader(io.BytesIO(file))
212
- text = "".join([page.extract_text() or "" for page in pdf_reader.pages])
213
- if not text.strip():
214
- return "No extractable text found in PDF."
215
-
216
- # Split text into chunks
217
- chunks = [text[i:i+300] for i in range(0, len(text), 300)]
218
- self.pdf_english_texts = [c for c in chunks if not any('\u0600' <= char <= '\u06FF' for char in c)]
219
- self.pdf_arabic_texts = [c for c in chunks if any('\u0600' <= char <= '\u06FF' for char in c)]
220
-
221
- # Create indices for PDF content using GPU
222
- if self.pdf_english_texts:
223
- english_vectors = [self.english_embedder.encode(text, device='cuda') for text in self.pdf_english_texts]
224
- dim = len(english_vectors[0])
225
- nlist = max(1, len(english_vectors) // 10)
226
- quantizer = faiss.IndexFlatL2(dim)
227
- self.pdf_english_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
228
- self.pdf_english_index.train(np.array(english_vectors))
229
- self.pdf_english_index.add(np.array(english_vectors))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
- if self.pdf_arabic_texts:
232
- arabic_vectors = [self.arabic_embedder.encode(text, device='cuda') for text in self.pdf_arabic_texts]
233
- dim = len(arabic_vectors[0])
234
- nlist = max(1, len(arabic_vectors) // 10)
235
- quantizer = faiss.IndexFlatL2(dim)
236
- self.pdf_arabic_index = faiss.IndexIVFFlat(quantizer, dim, nlist)
237
- self.pdf_arabic_index.train(np.array(arabic_vectors))
238
- self.pdf_arabic_index.add(np.array(arabic_vectors))
 
 
 
 
 
 
 
 
239
 
240
- self.has_pdf_content = True
241
- return f"PDF processed: {len(self.pdf_english_texts)} English, {len(self.pdf_arabic_texts)} Arabic chunks."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  except Exception as e:
243
- logger.error(f"PDF processing error: {e}")
244
- return f"Error processing PDF: {e}"
245
 
246
  # Create the Gradio interface
247
  def create_interface():
248
- """Set up the Gradio interface for chatting and PDF uploading."""
249
  assistant = Vision2030Assistant()
250
-
251
- def chat(query, history, session_id):
252
- reply = assistant.generate_response(query, session_id)
253
- history.append((query, reply))
 
 
 
 
 
 
 
254
  return history, ""
255
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  with gr.Blocks() as demo:
257
- gr.Markdown("# Vision 2030 Virtual Assistant")
258
- session_id = gr.State(value="user1") # Fixed session ID for simplicity
259
- chatbot = gr.Chatbot()
260
- msg = gr.Textbox(label="Ask a question")
261
- submit = gr.Button("Submit")
262
- pdf_upload = gr.File(label="Upload PDF", type="binary")
263
- upload_status = gr.Textbox(label="Upload Status")
264
-
265
- submit.click(chat, [msg, chatbot, session_id], [chatbot, msg])
266
- pdf_upload.upload(assistant.process_pdf, pdf_upload, upload_status)
267
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  return demo
269
 
270
- # Launch the interface
271
- if __name__ == "__main__":
272
- demo = create_interface()
273
- demo.launch()
 
1
+ # Minimal working Vision 2030 Virtual Assistant
2
  import gradio as gr
3
  import time
4
  import logging
 
7
  from datetime import datetime
8
  import numpy as np
9
  import pandas as pd
10
+ import matplotlib.pyplot as plt
11
+ from sklearn.metrics import precision_recall_fscore_support, accuracy_score
 
 
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 - %(name)s - %(levelname)s - %(message)s',
25
  handlers=[logging.StreamHandler()]
26
  )
27
+ logger = logging.getLogger('vision2030_assistant')
28
 
29
  # Check for GPU availability
30
  has_gpu = torch.cuda.is_available()
31
  logger.info(f"GPU available: {has_gpu}")
32
 
 
33
  class Vision2030Assistant:
34
  def __init__(self):
35
+ """Initialize the Vision 2030 Assistant with basic knowledge"""
36
  logger.info("Initializing Vision 2030 Assistant...")
37
+
38
+ # Initialize embedding models
39
  self.load_embedding_models()
40
+
41
+ # Create data
42
  self._create_knowledge_base()
43
  self._create_indices()
44
+
45
+ # Create sample evaluation data
46
  self._create_sample_eval_data()
47
+
48
+ # Initialize metrics
49
+ self.metrics = {
50
+ "response_times": [],
51
+ "user_ratings": [],
52
+ "factual_accuracy": []
53
+ }
54
+ self.response_history = []
55
+
56
+ # Flag for PDF content
57
+ self.has_pdf_content = False
58
+
59
+ logger.info("Vision 2030 Assistant initialized successfully")
60
+
61
+ @spaces.GPU
62
  def load_embedding_models(self):
63
+ """Load embedding models for retrieval"""
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"Error loading embedding models: {str(e)}")
80
+ self._create_fallback_embedders()
81
 
82
+ def _create_fallback_embedders(self):
83
+ """Create fallback embedding methods if model loading fails"""
84
+ logger.warning("Using fallback embedding methods")
85
+
86
+ # Simple fallback using character-level encoding
87
+ def simple_encode(text, dim=384):
88
+ import hashlib
89
+ # Create a hash of the text
90
+ hash_object = hashlib.md5(text.encode())
91
+ # Use the hash to seed a random number generator
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 simple_encode(text, self.dim)
103
+
104
  self.arabic_embedder = SimpleEmbedder()
105
  self.english_embedder = SimpleEmbedder()
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def _create_knowledge_base(self):
108
+ """Create knowledge base with Vision 2030 information"""
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
+ "Vision 2030 targets increasing the private sector's contribution to GDP from 40% to 65%.",
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
+ "تستهدف رؤية 2030 زيادة مساهمة القطاع الخاص في الناتج المحلي الإجمالي من 40٪ إلى 65٪.",
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 for text retrieval"""
156
+ logger.info("Creating FAISS indices for text retrieval")
157
+
158
  try:
159
+ # Process and embed English texts
160
+ self.english_vectors = []
161
+ for text in self.english_texts:
162
+ try:
163
+ if has_gpu and hasattr(self.english_embedder, 'to'):
164
+ with torch.no_grad():
165
+ vec = self.english_embedder.encode(text)
166
+ else:
167
+ vec = self.english_embedder.encode(text)
168
+ self.english_vectors.append(vec)
169
+ except Exception as e:
170
+ logger.error(f"Error encoding English text: {str(e)}")
171
+ # Use a random vector as fallback
172
+ self.english_vectors.append(np.random.randn(384).astype(np.float32))
173
+
174
+ # Create English index
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 FAISS indices: {str(e)}")
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
+ """Create sample evaluation data with ground truth"""
268
  self.eval_data = [
269
+ {
270
+ "question": "What are the key pillars of Vision 2030?",
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 relevant context with priority to PDF content"""
305
+ start_time = time.time()
306
+
307
  try:
308
+ # First check if we have PDF content
309
+ if self.has_pdf_content:
310
+ # Try to retrieve from PDF content first
311
+ if lang == "ar" and hasattr(self, 'pdf_arabic_index') and hasattr(self, 'pdf_arabic_vectors') and len(self.pdf_arabic_vectors) > 0:
312
+ if has_gpu and hasattr(self.arabic_embedder, 'to'):
313
+ with torch.no_grad():
314
+ query_vec = self.arabic_embedder.encode(query)
315
+ else:
316
+ query_vec = self.arabic_embedder.encode(query)
317
+
318
+ D, I = self.pdf_arabic_index.search(np.array([query_vec]), k=2)
319
+
320
+ # If we found good matches in the PDF
321
+ if D[0][0] < 1.5: # Threshold for relevance
322
+ context = "\n".join([self.pdf_arabic_texts[i] for i in I[0] if i < len(self.pdf_arabic_texts) and i >= 0])
323
+ if context.strip():
324
+ logger.info("Retrieved context from PDF (Arabic)")
325
+ return context
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"Error retrieving context: {str(e)}")
369
+ return ""
 
 
 
 
 
 
370
 
371
+ def generate_response(self, user_input):
372
+ """Generate response based on user input"""
373
+ if not user_input or user_input.strip() == "":
374
+ return ""
375
+
376
  start_time = time.time()
377
+
378
+ # Default response in case of failure
379
+ default_response = {
380
+ "en": "I apologize, but I couldn't process your request properly. Please try again.",
381
+ "ar": "أعتذر، لم أتمكن من معالجة طلبك بشكل صحيح. الرجاء المحاولة مرة أخرى."
382
+ }
383
+
384
  try:
385
+ # Detect language
386
+ try:
387
+ lang = detect(user_input)
388
+ if lang != "ar": # Simplify to just Arabic vs non-Arabic
389
+ lang = "en"
390
+ except:
391
+ lang = "en" # Default fallback
392
+
393
+ logger.info(f"Detected language: {lang}")
394
+
395
+ # Check for specific question patterns
396
+ if lang == "ar":
397
+ # National identity
398
+ if "الهوية الوطنية" in user_input or "تعزيز الهوية" in user_input:
399
+ reply = "تتضمن رؤية 2030 مبادرات متعددة لتعزيز الهوية الوطنية السعودية بما في ذلك البرامج الثقافية والحفاظ على التراث وتعزيز القيم السعودية."
400
+ # Hajj and Umrah
401
+ elif "المعتمرين" in user_input or "الحجاج" in user_input or "العمرة" in user_input or "الحج" in user_input:
402
+ reply = "تهدف رؤية 2030 إلى زيادة القدرة على استقبال المعتمرين من 8 ملايين إلى 30 مليون معتمر سنويًا."
403
+ # Economic diversification
404
+ elif "تنويع مصادر الدخل" in user_input or "الاقتصاد المزدهر" in user_input or "تنمية الاقتصاد" in user_input:
405
+ reply = "تهدف رؤية 2030 إلى زيادة الإيرادات الحكومية غير النفطية من 163 مليار ريال سعودي إلى 1 تريليون ريال سعودي من خلال تطوير قطاعات متنوعة مثل السياحة والتصنيع والطاقة المتجددة."
406
+ # UNESCO sites
407
+ elif "المواقع الأثرية" in user_input or "اليونسكو" in user_input or "التراث العالمي" in user_input:
408
+ reply = "تضع رؤية 2030 هدفًا بتسجيل ما لا يقل عن 10 مواقع سعودية في قائمة التراث العالمي لليونسكو."
409
+ # Real wealth
410
+ elif "الثروة الحقيقية" in user_input or "أثمن" in user_input or "ثروة" in user_input:
411
+ reply = "الثروة الحقيقية للمملكة العربية السعودية، كما أكدت رؤية 2030، هي شعبها، وخاصة الشباب."
412
+ # Global gateway
413
+ elif "بوابة للعالم" in user_input or "مكانتها" in user_input or "موقعها الاستراتيجي" in user_input:
414
+ reply = "تهدف المملكة العربية السعودية إلى تعزيز مكانتها كبوابة عالمية من خلال الاستفادة من موقعها الاستراتيجي بين آسيا وأوروبا وأفريقيا."
415
+ # Key pillars
416
+ elif "ركائز" in user_input or "اركان" in user_input:
417
+ reply = "الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح."
418
+ # General Vision 2030
419
+ elif "ما هي" in user_input or "ماهي" in user_input:
420
+ reply = "رؤية 2030 هي الإطار الاستراتيجي للمملكة العربية السعودية للحد من الاعتماد على النفط وتنويع الاقتصاد وتطوير القطاعات العامة. الركائز الرئيسية لرؤية 2030 هي مجتمع حيوي، واقتصاد مزدهر، ووطن طموح."
421
+ else:
422
+ # Use retrieved context
423
+ context = self.retrieve_context(user_input, lang)
424
+ reply = context if context else "لم أتمكن من العثور على معلومات كافية حول هذا السؤال."
425
+ else: # English
426
+ # Use retrieved context
427
+ context = self.retrieve_context(user_input, lang)
428
+ reply = context if context else "I couldn't find enough information about this question."
429
+
430
+ # Record response time
431
+ response_time = time.time() - start_time
432
+ self.metrics["response_times"].append(response_time)
433
+
434
+ logger.info(f"Generated response in {response_time:.2f}s")
435
+
436
+ # Store the interaction for later evaluation
437
+ interaction = {
438
+ "timestamp": datetime.now().isoformat(),
439
+ "user_input": user_input,
440
+ "response": reply,
441
+ "language": lang,
442
+ "response_time": response_time
443
+ }
444
+ self.response_history.append(interaction)
445
+
446
  return reply
447
+
448
  except Exception as e:
449
+ logger.error(f"Error generating response: {str(e)}")
450
+ return default_response.get(lang, default_response["en"])
451
 
452
  def evaluate_factual_accuracy(self, response, reference):
453
+ """Simple evaluation of factual accuracy by keyword matching"""
454
+ # This is a simplified approach - in production, use more sophisticated methods
455
+ keywords_reference = set(re.findall(r'\b\w+\b', reference.lower()))
456
+ keywords_response = set(re.findall(r'\b\w+\b', response.lower()))
457
+
458
+ # Remove common stopwords (simplified approach)
459
+ english_stopwords = {"the", "is", "a", "an", "and", "or", "of", "to", "in", "for", "with", "by", "on", "at"}
460
+ arabic_stopwords = {"في", "من", "إلى", "على", "و", "هي", "هو", "عن", "مع"}
461
+
462
+ keywords_reference = {w for w in keywords_reference if w not in english_stopwords and w not in arabic_stopwords}
463
+ keywords_response = {w for w in keywords_response if w not in english_stopwords and w not in arabic_stopwords}
464
+
465
+ common_keywords = keywords_reference.intersection(keywords_response)
466
+
467
+ if len(keywords_reference) > 0:
468
+ accuracy = len(common_keywords) / len(keywords_reference)
469
+ else:
470
+ accuracy = 0
471
+
472
+ return accuracy
473
 
474
  @spaces.GPU
475
+ def evaluate_on_test_set(self):
476
+ """Evaluate the assistant on the test set"""
477
+ logger.info("Running evaluation on test set")
478
+
479
+ eval_results = []
480
+
481
+ for example in self.eval_data:
482
+ # Generate response
483
+ response = self.generate_response(example["question"])
484
+
485
+ # Calculate factual accuracy
486
+ accuracy = self.evaluate_factual_accuracy(response, example["reference_answer"])
487
+
488
+ eval_results.append({
489
+ "question": example["question"],
490
+ "reference": example["reference_answer"],
491
+ "response": response,
492
+ "factual_accuracy": accuracy
493
+ })
494
+
495
+ self.metrics["factual_accuracy"].append(accuracy)
496
+
497
+ # Calculate average factual accuracy
498
+ avg_accuracy = sum(self.metrics["factual_accuracy"]) / len(self.metrics["factual_accuracy"]) if self.metrics["factual_accuracy"] else 0
499
+ avg_response_time = sum(self.metrics["response_times"]) / len(self.metrics["response_times"]) if self.metrics["response_times"] else 0
500
+
501
+ results = {
502
+ "average_factual_accuracy": avg_accuracy,
503
+ "average_response_time": avg_response_time,
504
+ "detailed_results": eval_results
505
+ }
506
+
507
+ logger.info(f"Evaluation results: Factual accuracy = {avg_accuracy:.2f}, Avg response time = {avg_response_time:.2f}s")
508
+
509
+ return results
510
+
511
+ def visualize_evaluation_results(self, results):
512
+ """Generate visualization of evaluation results"""
513
+ # Create a DataFrame from the detailed results
514
+ df = pd.DataFrame(results["detailed_results"])
515
+
516
+ # Create the figure for visualizations
517
+ fig = plt.figure(figsize=(12, 8))
518
+
519
+ # Bar chart of factual accuracy by question
520
+ plt.subplot(2, 1, 1)
521
+ bars = plt.bar(range(len(df)), df["factual_accuracy"], color="skyblue")
522
+ plt.axhline(y=results["average_factual_accuracy"], color='r', linestyle='-',
523
+ label=f"Avg: {results['average_factual_accuracy']:.2f}")
524
+ plt.xlabel("Question Index")
525
+ plt.ylabel("Factual Accuracy")
526
+ plt.title("Factual Accuracy by Question")
527
+ plt.ylim(0, 1.1)
528
+ plt.legend()
529
+
530
+ # Add language information
531
+ df["language"] = df["question"].apply(lambda x: "Arabic" if detect(x) == "ar" else "English")
532
+
533
+ # Group by language
534
+ lang_accuracy = df.groupby("language")["factual_accuracy"].mean()
535
+
536
+ # Bar chart of accuracy by language
537
+ plt.subplot(2, 1, 2)
538
+ lang_bars = plt.bar(lang_accuracy.index, lang_accuracy.values, color=["lightblue", "lightgreen"])
539
+ plt.axhline(y=results["average_factual_accuracy"], color='r', linestyle='-',
540
+ label=f"Overall: {results['average_factual_accuracy']:.2f}")
541
+ plt.xlabel("Language")
542
+ plt.ylabel("Average Factual Accuracy")
543
+ plt.title("Factual Accuracy by Language")
544
+ plt.ylim(0, 1.1)
545
+
546
+ # Add value labels
547
+ for i, v in enumerate(lang_accuracy):
548
+ plt.text(i, v + 0.05, f"{v:.2f}", ha='center')
549
+
550
+ plt.tight_layout()
551
+ return fig
552
 
553
+ def record_user_feedback(self, user_input, response, rating, feedback_text=""):
554
+ """Record user feedback for a response"""
555
+ feedback = {
556
+ "timestamp": datetime.now().isoformat(),
557
+ "user_input": user_input,
558
+ "response": response,
559
+ "rating": rating,
560
+ "feedback_text": feedback_text
561
+ }
562
+
563
+ self.metrics["user_ratings"].append(rating)
564
+
565
+ # In a production system, store this in a database
566
+ logger.info(f"Recorded user feedback: rating={rating}")
567
+
568
+ return True
569
 
570
+ @spaces.GPU
571
+ def process_pdf(self, file):
572
+ """Process uploaded PDF file"""
573
+ if file is None:
574
+ return "No file uploaded. Please select a PDF file."
575
+
576
+ try:
577
+ logger.info(f"Processing uploaded file")
578
+
579
+ # Convert bytes to file-like object
580
+ file_stream = io.BytesIO(file)
581
+
582
+ # Use PyPDF2 to read the file content
583
+ reader = PyPDF2.PdfReader(file_stream)
584
+
585
+ # Extract text from the PDF
586
+ full_text = ""
587
+ for page_num in range(len(reader.pages)):
588
+ page = reader.pages[page_num]
589
+ extracted_text = page.extract_text()
590
+ if extracted_text:
591
+ full_text += extracted_text + "\n"
592
+
593
+ if not full_text.strip():
594
+ return "The uploaded PDF doesn't contain extractable text. Please try another file."
595
+
596
+ # Process the extracted text with better chunking
597
+ chunks = []
598
+ paragraphs = re.split(r'\n\s*\n', full_text)
599
+
600
+ for paragraph in paragraphs:
601
+ # Skip very short paragraphs
602
+ if len(paragraph.strip()) < 20:
603
+ continue
604
+
605
+ if len(paragraph) > 500: # For very long paragraphs
606
+ # Split into smaller chunks
607
+ sentences = re.split(r'(?<=[.!?])\s+', paragraph)
608
+ current_chunk = ""
609
+ for sentence in sentences:
610
+ if len(current_chunk) + len(sentence) > 300:
611
+ if current_chunk:
612
+ chunks.append(current_chunk.strip())
613
+ current_chunk = sentence
614
+ else:
615
+ current_chunk += " " + sentence if current_chunk else sentence
616
+
617
+ if current_chunk:
618
+ chunks.append(current_chunk.strip())
619
+ else:
620
+ chunks.append(paragraph.strip())
621
+
622
+ # Categorize text by language
623
+ english_chunks = []
624
+ arabic_chunks = []
625
+
626
+ for chunk in chunks:
627
+ try:
628
+ lang = detect(chunk)
629
+ if lang == "ar":
630
+ arabic_chunks.append(chunk)
631
+ else:
632
+ english_chunks.append(chunk)
633
+ except:
634
+ # If language detection fails, check for Arabic characters
635
+ if any('\u0600' <= c <= '\u06FF' for c in chunk):
636
+ arabic_chunks.append(chunk)
637
+ else:
638
+ english_chunks.append(chunk)
639
+
640
+ # Store PDF content
641
+ self.pdf_english_texts = english_chunks
642
+ self.pdf_arabic_texts = arabic_chunks
643
+
644
+ # Create indices for PDF content
645
+ self._create_pdf_indices()
646
+
647
+ logger.info(f"Successfully processed PDF: {len(arabic_chunks)} Arabic chunks, {len(english_chunks)} English chunks")
648
+
649
+ return f"✅ Successfully processed the PDF! Found {len(arabic_chunks)} Arabic and {len(english_chunks)} English text segments. PDF content will now be prioritized when answering questions."
650
+
651
  except Exception as e:
652
+ logger.error(f"Error processing PDF: {str(e)}")
653
+ return f"Error processing the PDF: {str(e)}. Please try another file."
654
 
655
  # Create the Gradio interface
656
  def create_interface():
657
+ # Initialize the assistant
658
  assistant = Vision2030Assistant()
659
+
660
+ def chat(message, history):
661
+ if not message or message.strip() == "":
662
+ return history, ""
663
+
664
+ # Generate response
665
+ reply = assistant.generate_response(message)
666
+
667
+ # Update history
668
+ history.append((message, reply))
669
+
670
  return history, ""
671
+
672
+ def provide_feedback(history, rating, feedback_text):
673
+ # Record feedback for the last conversation
674
+ if history and len(history) > 0:
675
+ last_interaction = history[-1]
676
+ assistant.record_user_feedback(last_interaction[0], last_interaction[1], rating, feedback_text)
677
+ return f"Thank you for your feedback! (Rating: {rating}/5)"
678
+ return "No conversation found to rate."
679
+
680
+ @spaces.GPU
681
+ def run_evaluation():
682
+ results = assistant.evaluate_on_test_set()
683
+
684
+ # Create summary text
685
+ summary = f"""
686
+ Evaluation Results:
687
+ ------------------
688
+ Total questions evaluated: {len(results['detailed_results'])}
689
+ Overall factual accuracy: {results['average_factual_accuracy']:.2f}
690
+ Average response time: {results['average_response_time']:.4f} seconds
691
+
692
+ Detailed Results:
693
+ """
694
+
695
+ for i, result in enumerate(results['detailed_results']):
696
+ summary += f"\nQ{i+1}: {result['question']}\n"
697
+ summary += f"Reference: {result['reference']}\n"
698
+ summary += f"Response: {result['response']}\n"
699
+ summary += f"Accuracy: {result['factual_accuracy']:.2f}\n"
700
+ summary += "-" * 40 + "\n"
701
+
702
+ # Return both the results summary and visualization
703
+ fig = assistant.visualize_evaluation_results(results)
704
+
705
+ return summary, fig
706
+
707
+ def process_uploaded_file(file):
708
+ """Process the uploaded PDF file"""
709
+ return assistant.process_pdf(file)
710
+
711
+ # Create the Gradio interface
712
  with gr.Blocks() as demo:
713
+ gr.Markdown("# Vision 2030 Virtual Assistant 🌟")
714
+ gr.Markdown("Ask questions about Saudi Arabia's Vision 2030 in both Arabic and English")
715
+
716
+ with gr.Tab("Chat"):
717
+ chatbot = gr.Chatbot(height=400)
718
+ msg = gr.Textbox(label="Your Question", placeholder="Ask about Vision 2030...")
719
+ with gr.Row():
720
+ submit_btn = gr.Button("Submit")
721
+ clear_btn = gr.Button("Clear Chat")
722
+
723
+ gr.Markdown("### Provide Feedback")
724
+ with gr.Row():
725
+ rating = gr.Slider(minimum=1, maximum=5, step=1, value=3, label="Rate the Response (1-5)")
726
+ feedback_text = gr.Textbox(label="Additional Comments (Optional)")
727
+ feedback_btn = gr.Button("Submit Feedback")
728
+ feedback_result = gr.Textbox(label="Feedback Status")
729
+
730
+ with gr.Tab("Evaluation"):
731
+ evaluate_btn = gr.Button("Run Evaluation on Test Set")
732
+ eval_output = gr.Textbox(label="Evaluation Results", lines=20)
733
+ eval_chart = gr.Plot(label="Evaluation Metrics")
734
+
735
+ with gr.Tab("Upload PDF"):
736
+ gr.Markdown("""
737
+ ### Upload a Vision 2030 PDF Document
738
+ Upload a PDF document to enhance the assistant's knowledge base.
739
+ """)
740
+
741
+ with gr.Row():
742
+ file_input = gr.File(
743
+ label="Select PDF File",
744
+ file_types=[".pdf"],
745
+ type="binary" # This is critical - use binary mode
746
+ )
747
+
748
+ with gr.Row():
749
+ upload_btn = gr.Button("Process PDF", variant="primary")
750
+
751
+ with gr.Row():
752
+ upload_status = gr.Textbox(
753
+ label="Upload Status",
754
+ placeholder="Upload status will appear here...",
755
+ interactive=False
756
+ )
757
+
758
+ gr.Markdown("""
759
+ ### Notes:
760
+ - The PDF should contain text that can be extracted (not scanned images)
761
+ - After uploading, return to the Chat tab to ask questions about the uploaded content
762
+ """)
763
+
764
+ # Set up event handlers
765
+ msg.submit(chat, [msg, chatbot], [chatbot, msg])
766
+ submit_btn.click(chat, [msg, chatbot], [chatbot, msg])
767
+ clear_btn.click(lambda: [], None, chatbot)
768
+ feedback_btn.click(provide_feedback, [chatbot, rating, feedback_text], feedback_result)
769
+ evaluate_btn.click(run_evaluation, None, [eval_output, eval_chart])
770
+ upload_btn.click(process_uploaded_file, [file_input], [upload_status])
771
+
772
  return demo
773
 
774
+ # Launch the app
775
+ demo = create_interface()
776
+ demo.launch()