fatma812 commited on
Commit
4c38aa8
·
verified ·
1 Parent(s): 88e7548

Update chatbot_updated.py

Browse files
Files changed (1) hide show
  1. chatbot_updated.py +323 -113
chatbot_updated.py CHANGED
@@ -1,38 +1,115 @@
1
- # ==============================
2
- # ✅ Imports
3
- # ==============================
4
  import json
 
 
 
5
  import numpy as np
6
  from PIL import Image
7
  from deep_translator import GoogleTranslator
8
  from ultralytics import YOLO
9
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
 
 
10
  import re
 
11
 
12
  # ==============================
13
- # Load Models
14
  # ==============================
15
- yolo_model = YOLO("best_egypt.pt")
16
- model_name = "google/flan-t5-base"
17
- tokenizer = AutoTokenizer.from_pretrained(model_name)
18
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
 
 
 
 
 
 
 
19
 
20
  # ==============================
21
- # Load Data
22
  # ==============================
23
- with open("artifacts .json", "r", encoding="utf-8") as f:
24
- data = json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  # ==============================
27
- # 🔹 Global Memory
28
  # ==============================
29
- LAST_ARTIFACT = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  # ==============================
32
- # 🔹 Helpers
33
  # ==============================
 
34
  def is_arabic(text):
35
- return any('\u0600' <= ch <= '\u06FF' for ch in text)
 
36
 
37
  def translate_to_en(text):
38
  try:
@@ -40,141 +117,274 @@ def translate_to_en(text):
40
  except:
41
  return text
42
 
 
43
  def translate_to_ar(text):
44
  try:
45
  return GoogleTranslator(source='auto', target='ar').translate(text)
46
  except:
47
  return text
48
 
49
- def split_questions(text):
50
- # تقسيم الأسئلة بناءً على الروابط والترقيم
51
- parts = re.split(r'[?.,]| and | و ', text)
52
- return [q.strip() for q in parts if len(q.strip()) > 3]
53
 
54
  # ==============================
55
- # 🔹 Logic Functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  # ==============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  def detect_artifact(image):
58
- results = yolo_model(image)
 
 
59
  result = results[0]
60
- annotated_img = Image.fromarray(result.plot())
61
-
 
62
  if result.boxes is None or len(result.boxes) == 0:
63
- return None, annotated_img
64
 
65
- scores = result.boxes.conf.cpu().numpy()
66
- best_index = np.argmax(scores)
67
- class_name = result.names[int(result.boxes.cls[best_index])]
68
- return class_name, annotated_img
69
 
70
- def get_artifact(artifact_name):
71
- artifact_name = artifact_name.lower().strip()
72
- for doc in data:
73
- if artifact_name == doc['name'].lower().strip() or artifact_name in doc['name'].lower():
74
- return doc
75
- for doc in data:
76
- if 'keywords' in doc:
77
- for k in doc['keywords']:
78
- if k.lower() in artifact_name:
79
- return doc
80
- return None
81
 
82
  # ==============================
83
- # 🔥 Flexible Response Engine
84
  # ==============================
85
- def get_best_response(question_en, artifact):
86
- q = question_en.lower()
87
 
88
- # Era
89
- if any(word in q for word in ["era", "time period", "age"]):
90
- return f"The {artifact['name']} is from the {artifact['era']} era."
91
 
92
- # Material
93
- elif any(word in q for word in ["material", "made of", "composition"]):
94
- return f"The material of {artifact['name']} is {artifact['material']}."
95
 
96
- # Creator
97
- elif any(word in q for word in ["creator", "made by", "built by", "who"]):
98
- return f"The creator of {artifact['name']} is {artifact['creator']}."
 
99
 
100
- # Built Year
101
- elif any(word in q for word in ["built year", "constructed", "built in", "when"]):
102
- return f"{artifact['name']} was built around {artifact['built_year']}."
103
 
104
- # Type
105
- elif any(word in q for word in ["type", "kind", "form"]):
106
- return f"{artifact['name']} is a {artifact['type']}."
107
 
108
- # Location (Found + Current)
109
- elif any(word in q for word in ["location", "found", "discovered", "where", "current location", "now", "displayed", "museum"]):
110
- return (f"{artifact['name']} was found at {artifact['location_found']} "
111
- f"and is currently located at {artifact['current_location']}.")
 
 
 
 
 
 
 
112
 
113
- # Description or importance
114
- else:
115
- return (f"{artifact['name']} is a remarkable {artifact['type']} from the {artifact['era']} era, "
116
- f"made of {artifact['material']}. Created by {artifact['creator']}, "
117
- f"it {artifact['description']} {artifact['importance']}. "
118
- f"It was found at {artifact['location_found']} and is currently in {artifact['current_location']}.")
119
 
120
  # ==============================
121
- # 🔹 Main Entry Point
122
  # ==============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  def chatbot_updated(question, image=None):
124
- global LAST_ARTIFACT
125
 
126
- if not question or question.strip() == "":
127
- return "أهلاً بك! كيف يمكنني مساعدتك في التعرف على الآثار؟"
 
 
 
 
 
 
128
 
129
- user_lang = "ar" if is_arabic(question) else "en"
130
- question_en = translate_to_en(question) if user_lang == "ar" else question
131
 
132
- artifact_name = None
 
133
 
134
- # 1️⃣ التعرف من الصورة
135
  if image is not None:
136
- detected, _ = detect_artifact(image)
137
- if detected and get_artifact(detected):
138
- artifact_name = detected
139
- LAST_ARTIFACT = detected
140
-
141
- # 2️⃣ التعرف من النص
142
- if artifact_name is None:
143
- for doc in data:
144
- if doc['name'].lower() in question_en.lower():
145
- artifact_name = doc['name']
146
- LAST_ARTIFACT = doc['name']
147
- break
148
 
149
- # 3️⃣ لو ما لقيناش أثر نهائي
150
- if artifact_name is None or not get_artifact(artifact_name):
151
- return "لا توجد معلومات عن هذا الأثر." if user_lang == "ar" else "No data found for this artifact."
152
 
153
- artifact = get_artifact(artifact_name)
 
 
 
154
 
155
- # معالجة الأسئلة المتعددة
156
- raw_parts = split_questions(question_en)
157
- if not raw_parts:
158
- raw_parts = [question_en]
159
 
160
- all_answers = []
161
- for part in raw_parts:
162
- # حل الضمائر it → اسم الأثر
163
- if " it " in f" {part.lower()} ":
164
- part = part.replace(" it ", f" {artifact_name} ")
165
- answer = get_best_response(part, artifact)
166
- if answer:
167
- all_answers.append(answer)
168
 
169
- # دمج الإجابات بجملة واحدة سلسة
170
- if not all_answers:
171
- return "لا يمكنني العثور على إجابة محددة."
172
 
173
- final_answer_en = " ".join(all_answers)
 
174
 
175
- # الترجمة النهائية
176
- if user_lang == "ar":
177
- ar_answer = translate_to_ar(final_answer_en)
178
- return ar_answer.replace(" ", " ").strip()
179
-
180
- return final_answer_en
 
 
 
 
1
  import json
2
+ import os
3
+ import uuid
4
+ import tempfile
5
  import numpy as np
6
  from PIL import Image
7
  from deep_translator import GoogleTranslator
8
  from ultralytics import YOLO
9
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
10
+ from gtts import gTTS
11
+ import whisper as whisper_lib
12
  import re
13
+ from rapidfuzz import fuzz
14
 
15
  # ==============================
16
+ # Lazy Loaded Models (IMPORTANT)
17
  # ==============================
18
+
19
+ embed_model = None
20
+ yolo_model = None
21
+ whisper_model = None
22
+
23
+ _model = None
24
+ _tokenizer = None
25
+
26
+ _index = None
27
+ _artifact_docs = None
28
+ _artifact_texts = None
29
 
30
  # ==============================
31
+ # Lazy Getters
32
  # ==============================
33
+
34
+ def get_embed_model():
35
+ global embed_model
36
+ if embed_model is None:
37
+ embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
38
+ return embed_model
39
+
40
+
41
+ def get_yolo_model():
42
+ global yolo_model
43
+ if yolo_model is None:
44
+ model_path = os.path.join("models", "best_egypt.pt")
45
+ yolo_model = YOLO(model_path)
46
+ return yolo_model
47
+
48
+
49
+ def get_whisper_model():
50
+ global whisper_model
51
+ if whisper_model is None:
52
+ whisper_model = whisper_lib.load_model("small")
53
+ return whisper_model
54
+
55
+
56
+ def get_llm():
57
+ global _model, _tokenizer
58
+ if _model is None:
59
+ print("Loading LLM...")
60
+ model_name = "google/flan-t5-base"
61
+ _tokenizer = AutoTokenizer.from_pretrained(model_name)
62
+ _model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
63
+ print("LLM loaded.")
64
+ return _model, _tokenizer
65
+
66
 
67
  # ==============================
68
+ # Load Artifacts JSON (lazy index)
69
  # ==============================
70
+
71
+ with open(os.path.join("data", "artifacts.json"), "r", encoding="utf-8") as f:
72
+ data = json.load(f)
73
+
74
+
75
+ def build_index():
76
+ global _index, _artifact_docs, _artifact_texts
77
+
78
+ if _index is not None:
79
+ return _index
80
+
81
+ model = get_embed_model()
82
+
83
+ artifact_texts = []
84
+ artifact_docs = []
85
+
86
+ for doc in data:
87
+ name = doc.get("name", "")
88
+ keywords = " ".join(doc.get("keywords", []))
89
+ text = f"{name} {keywords}"
90
+
91
+ artifact_texts.append(text)
92
+ artifact_docs.append(doc)
93
+
94
+ embeddings = model.encode(artifact_texts, convert_to_numpy=True)
95
+
96
+ import faiss
97
+ _index = faiss.IndexFlatL2(embeddings.shape[1])
98
+ _index.add(np.array(embeddings))
99
+
100
+ _artifact_docs = artifact_docs
101
+ _artifact_texts = artifact_texts
102
+
103
+ return _index
104
+
105
 
106
  # ==============================
107
+ # Helper Functions
108
  # ==============================
109
+
110
  def is_arabic(text):
111
+ return any('\u0600' <= c <= '\u06FF' for c in text)
112
+
113
 
114
  def translate_to_en(text):
115
  try:
 
117
  except:
118
  return text
119
 
120
+
121
  def translate_to_ar(text):
122
  try:
123
  return GoogleTranslator(source='auto', target='ar').translate(text)
124
  except:
125
  return text
126
 
 
 
 
 
127
 
128
  # ==============================
129
+ # Intent Detection
130
+ # ==============================
131
+
132
+ INTENT_KEYWORDS = {
133
+ "creator": ["who built", "who made", "creator", "made by",
134
+ "من بناه", "من صنعه", "المنشئ", "من بنى"],
135
+ "built_year": ["when was it built", "year", "date",
136
+ "متى بني", "سنة", "تاريخ"],
137
+ "type": ["type", "what kind", "نوع", "ما نوع"],
138
+ "era": ["era", "period", "dynasty",
139
+ "العصر", "الفترة", "الحقبة", "عصر"],
140
+ "material": ["material", "made of",
141
+ "مم صنع", "مصنوع من", "المادة"],
142
+ "description": ["describe", "appearance", "look like",
143
+ "وصف", "كيف يبدو", "شكل"],
144
+ "importance": ["importance", "significance", "why important",
145
+ "الأهمية", "أهميته", "ليه مهم"],
146
+ "location_found": ["where was it found", "discovered",
147
+ "اين وجد", "مكان اكتشافه", "اكتشف"],
148
+ "current_location": ["where is", "current location", "located",
149
+ "اين يوجد", "يقع", "مكانه"],
150
+ "summary": ["tell me about", "overview", "summary", "brief",
151
+ "what is", "who is", "information",
152
+ "احكيلي", "أهم المعل��مات", "نبذة", "معلومات"],
153
+ }
154
+
155
+
156
+ def detect_intents(q_en, q_ar=""):
157
+ q_en = (q_en or "").lower()
158
+ q_ar = (q_ar or "").lower()
159
+ detected_intents = []
160
+
161
+ for intent, keywords in INTENT_KEYWORDS.items():
162
+ if intent == "summary":
163
+ continue
164
+
165
+ for kw in keywords:
166
+ if kw in q_en or kw in q_ar:
167
+ detected_intents.append(intent)
168
+ break
169
+
170
+ if not detected_intents:
171
+ detected_intents.append("summary")
172
+
173
+ return detected_intents
174
+
175
+
176
+ # ==============================
177
+ # Response Generator
178
  # ==============================
179
+
180
+ def generate_intent_response(artifact, intent, user_lang="en"):
181
+ name_en = artifact.get("name", "This artifact").replace("-", " ").replace("_", " ")
182
+ name = translate_to_ar(name_en) if user_lang == "ar" else name_en
183
+
184
+ value = artifact.get(intent, "Unknown")
185
+
186
+ if user_lang == "ar":
187
+ creator = translate_to_ar(str(artifact.get('creator', '')))
188
+ era = translate_to_ar(str(artifact.get('era', '')))
189
+ location = translate_to_ar(str(artifact.get('current_location', '')))
190
+ description = translate_to_ar(str(artifact.get('description', '')))
191
+ material = translate_to_ar(str(artifact.get('material', '')))
192
+ value = translate_to_ar(str(value))
193
+
194
+ templates = {
195
+ "creator": f"تم إنشاء {name} بواسطة {creator}.",
196
+ "built_year": f"تم بناء {name} في عام {value}.",
197
+ "type": f"{name} هو {value}.",
198
+ "era": f"يرجع {name} إلى عصر {era}.",
199
+ "material": f"{name} مصنوع من {material}.",
200
+ "description": f"يتميز {name} بأنه {description}، ويعكس أهمية كبيرة في تاريخ وحضارة مصر القديمة.",
201
+ "importance": f"تكمن أهمية {name} في أنه {value}.",
202
+ "location_found": f"تم اكتشاف {name} في {value}.",
203
+ "current_location": f"يوجد {name} حاليًا في {location}.",
204
+ "summary": f"يُعد {name} من أبرز المعالم الأثرية في مصر القديمة، حيث يتميز بأنه {description}. تم إنشاؤه بواسطة {creator}، ويرجع تاريخه إلى عصر {era}. ويقع حاليًا في {location}.",
205
+ }
206
+
207
+ else:
208
+ templates = {
209
+ "creator": f"{name} was created by {value}.",
210
+ "built_year": f"{name} was built around {value}.",
211
+ "type": f"{name} is a {value}.",
212
+ "era": f"{name} dates back to the {value}.",
213
+ "material": f"{name} is made of {value}.",
214
+ "description": f"{name} is characterized by {value}.",
215
+ "importance": f"The importance of {name}: {value}.",
216
+ "location_found": f"{name} was discovered in {value}.",
217
+ "current_location": f"{name} is currently located in {value}.",
218
+ "summary": f"{name} is one of the most significant Egyptian monuments.",
219
+ }
220
+
221
+ return templates.get(intent, f"{name}: {value}")
222
+
223
+
224
+ # ==============================
225
+ # Artifact Search (lazy index)
226
+ # ==============================
227
+
228
+ def find_artifact(q_ar, q_en):
229
+ model = get_embed_model()
230
+ index = build_index()
231
+
232
+ q_ar_n = q_ar.lower() if q_ar else ""
233
+ q_en_n = q_en.lower() if q_en else ""
234
+
235
+ query = q_en_n + " " + q_ar_n
236
+
237
+ q_vec = model.encode([query])
238
+ D, I = index.search(np.array(q_vec), k=5)
239
+
240
+ candidates = [_artifact_docs[i] for i in I[0]]
241
+
242
+ best_doc = None
243
+ best_score = 0
244
+
245
+ for doc in candidates:
246
+ name = doc.get("name", "").lower()
247
+
248
+ score = 0
249
+
250
+ if name in query:
251
+ score += 300
252
+
253
+ score += fuzz.ratio(name, query)
254
+
255
+ for token in name.split():
256
+ if token in query:
257
+ score += 50
258
+
259
+ for kw in doc.get("keywords", []):
260
+ if kw.lower() in query:
261
+ score += 80
262
+
263
+ if score > best_score:
264
+ best_score = score
265
+ best_doc = doc
266
+
267
+ if best_score < 70:
268
+ return None
269
+
270
+ return best_doc
271
+
272
+
273
+ # ==============================
274
+ # YOLO (lazy)
275
+ # ==============================
276
+
277
  def detect_artifact(image):
278
+ model = get_yolo_model()
279
+
280
+ results = model(image)
281
  result = results[0]
282
+
283
+ annotated = Image.fromarray(result.plot())
284
+
285
  if result.boxes is None or len(result.boxes) == 0:
286
+ return None, annotated
287
 
288
+ best_idx = int(np.argmax(result.boxes.conf.cpu().numpy()))
289
+ class_id = int(result.boxes.cls[best_idx])
290
+
291
+ return result.names[class_id], annotated
292
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  # ==============================
295
+ # STT (lazy whisper)
296
  # ==============================
 
 
297
 
298
+ def speech_to_text(audio_bytes):
299
+ if not audio_bytes:
300
+ return "", "en"
301
 
302
+ tmp_path = None
 
 
303
 
304
+ try:
305
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
306
+ f.write(audio_bytes)
307
+ tmp_path = f.name
308
 
309
+ model = get_whisper_model()
 
 
310
 
311
+ audio = whisper_lib.load_audio(tmp_path)
312
+ clip = whisper_lib.pad_or_trim(audio)
313
+ mel = whisper_lib.log_mel_spectrogram(clip).to(model.device)
314
 
315
+ _, probs = model.detect_language(mel)
316
+ det_lang = max(probs, key=probs.get)
317
+
318
+ res = model.transcribe(tmp_path, language=det_lang, fp16=False)
319
+ text = res.get("text", "")
320
+
321
+ return text, det_lang
322
+
323
+ finally:
324
+ if tmp_path and os.path.exists(tmp_path):
325
+ os.remove(tmp_path)
326
 
 
 
 
 
 
 
327
 
328
  # ==============================
329
+ # TTS
330
  # ==============================
331
+
332
+ def text_to_speech(text):
333
+ try:
334
+ path = os.path.join(tempfile.gettempdir(), f"tts_{uuid.uuid4().hex}.mp3")
335
+ gTTS(text=text, lang="ar" if is_arabic(text) else "en").save(path)
336
+ return path
337
+ except:
338
+ return None
339
+
340
+
341
+ def cleanup_audio_file(filepath):
342
+ if filepath and os.path.exists(filepath):
343
+ os.remove(filepath)
344
+
345
+
346
+ # ==============================
347
+ # Chatbot Core (UNCHANGED LOGIC)
348
+ # ==============================
349
+
350
  def chatbot_updated(question, image=None):
 
351
 
352
+ if isinstance(question, bytes):
353
+ text, lang = speech_to_text(question)
354
+ else:
355
+ text = (question or "").strip()
356
+ lang = "ar" if is_arabic(text) else "en"
357
+
358
+ if not text:
359
+ return "Please provide a question." if lang == "en" else "من فضلك اكتب سؤالك."
360
 
361
+ q_en = translate_to_en(text) if lang == "ar" else text
 
362
 
363
+ artifact_from_image = None
364
+ detected_name = None
365
 
 
366
  if image is not None:
367
+ detected_name, _ = detect_artifact(image)
368
+ if detected_name:
369
+ artifact_from_image = find_artifact("", detected_name)
 
 
 
 
 
 
 
 
 
370
 
371
+ artifact_from_text = find_artifact(text, q_en)
 
 
372
 
373
+ if artifact_from_image:
374
+ artifact = artifact_from_image if artifact_from_image else artifact_from_text
375
+ else:
376
+ artifact = artifact_from_text
377
 
378
+ if not artifact:
379
+ return "Artifact not found."
 
 
380
 
381
+ intents = detect_intents(q_en, text)
 
 
 
 
 
 
 
382
 
383
+ responses = []
 
 
384
 
385
+ for intent in intents:
386
+ responses.append(generate_intent_response(artifact, intent, lang))
387
 
388
+ final_response = " ".join(responses)
389
+
390
+ return final_response