Youmnaaaa commited on
Commit
36368f4
·
verified ·
1 Parent(s): 626e1c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -6
app.py CHANGED
@@ -148,10 +148,17 @@ CATEGORY_KEYWORDS = {
148
  "مطعم", "مطاعم", "اكل", "أكل", "وجبات", "مشويات", "كباب", "كفته", "كفتة",
149
  "شاورما", "كريب", "سندوتش", "سندوتشات", "برجر", "بيتزا", "فراخ", "فول",
150
  "طعمية", "سمك", "restaurant", "food", "burger", "pizza", "shawarma", "crepe",
 
 
 
 
151
  ],
152
  "pharmacy": [
153
  "صيدليه", "صيدلية", "صيدليات", "صيدله", "صديليه", "صديليه", "دوا", "دواء", "ادويه", "أدوية",
154
  "ادوية", "علاج", "pharmacy", "drugstore", "medicine",
 
 
 
155
  ],
156
  "cafe": [
157
  "كافيه", "كافيهات", "كافية", "كوفي", "قهوه", "قهوة", "كافيتيريا", "لاتيه",
@@ -183,7 +190,8 @@ CAT_SINGLE = {
183
  }
184
 
185
  KEYWORD_INTENTS = {
186
- "greeting": ["السلام عليكم", "سلام عليكم", "وعليكم السلام", "اهلا", "أهلا", "هلا", "هاي", "مرحبا", "صباح الخير", "مساء الخير", "سلام", "hi", "hello", "hey"],
 
187
  "thanks": ["شكرا", "شكراً", "تسلم", "تسلمي", "يسلمو", "مشكور", "thanks", "thank you"],
188
  "goodbye": ["مع السلامة", "مع السلامه", "باي", "وداعا", "bye", "goodbye"],
189
  "confirm": ["تمام", "اوك", "أوك", "ماشي", "حاضر", "اه", "اها", "ايوه", "نعم"],
@@ -975,7 +983,9 @@ def clean_item_query(text: str) -> str:
975
  "فاتح", "فاتحه", "فاتحة", "مفتوح", "مفتوحه", "مفتوحة", "شغال", "شغاله", "شغالة",
976
  "دلوقتي", "حاليا", "الان", "هلا", "النهارده", "مني", "لي",
977
  "اروح", "هروح", "اشوف", "هشوف", "اتاكل", "أتاكل", "اقدر", "الاقي", "الاقيه",
978
- "ادور", "هدور", "اديني", "اديلي", "جيبلي", "ازاي",
 
 
979
  ]
980
  for w in remove_words:
981
  q = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", q)
@@ -1121,6 +1131,13 @@ LOCATION_PREPOSITIONS = ["في منطقة", "في", "ناحية", "قرب", "ج
1121
 
1122
 
1123
  def extract_location_suffix(text: str) -> tuple:
 
 
 
 
 
 
 
1124
  """Split a trailing '<preposition> <location words>' phrase off the end
1125
  of the text, e.g. 'عندو سندوتشات في كورنيش' -> ('عندو سندوتشات', 'كورنيش').
1126
 
@@ -1200,7 +1217,7 @@ def _strip_category_words(q: str) -> str:
1200
  "ادور", "هدور", "اديني", "اديلي", "هات", "جيبلي", "فين",
1201
  # generic "something to eat" filler — "حتة اكل"/"حته اكل" means "a
1202
  # bite to eat" in general, not a specific dish; never a real item.
1203
- "حته", "حتة", "اكل", "أكل",
1204
  ]
1205
  for w in generic_words:
1206
  cw = clean_text(w)
@@ -1345,6 +1362,14 @@ def _confident_place_candidate(candidate: str, category_hint: str = "", min_scor
1345
  candidate = clean_text(candidate)
1346
  if not candidate or len(candidate) < 2:
1347
  return False
 
 
 
 
 
 
 
 
1348
  try:
1349
  hits = name_search(candidate, category=category_hint, top_k=1)
1350
  if hits.empty and category_hint:
@@ -1536,7 +1561,9 @@ def extract_place_name_from_text(text: str) -> str:
1536
  "مطعم", "صيدليه", "صيدلية", "صديليه", "كافيه", "ماركت", "سوبر", "سوبرماركت", "هات", "منيو", "عايز", "عايزة",
1537
  "عايزه", "عاوزه", "عاوز", "محتاج", "محتاجة", "محتاجه", "اشتري", "اشترى", "اشتر", "اجيب", "نفسي",
1538
  "اروح", "هروح", "ازاي", "اشوف", "هشوف", "اتاكل", "أتاكل", "اقدر", "الاقي", "الاقيه",
1539
- "ادور", "هدور", "اديني", "اديلي", "جيبلي", "هل", "الوقت", "ده", "دي",
 
 
1540
  "قريب", "اقرب", "مفتوح", "فاتح", "دلوقتي", "في", "من", "عند",
1541
  "رقمه", "رقمها", "تليفونه", "تليفونها", "ايه", "إيه", "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "توب", "التوب",
1542
  "طب", "طيب", "تمام", "ماشي", "كام", "بكام", "قد ايه", "مين",
@@ -1691,10 +1718,31 @@ def item_category_conflict(item_query: str, category: str) -> Optional[str]:
1691
  return None
1692
 
1693
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1694
  def item_matches_place(place: dict, item_query: str, use_menu: bool = True) -> bool:
1695
  item = clean_text(item_query)
1696
  if not item:
1697
  return True
 
 
 
 
 
 
 
1698
  place_blob = clean_text(" ".join([
1699
  str(place.get("name", "")), str(place.get("name_ar", "")), str(place.get("name_en", "")),
1700
  str(place.get("category", "")), str(place.get("sub_category", "")), str(place.get("description", "")),
@@ -2236,14 +2284,35 @@ def find_menu_item_price(menu_obj: Any, item_query: str):
2236
  return best[1], best[2]
2237
 
2238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2239
  def handle_detail(text: str, place: Optional[dict]) -> str:
2240
  if not place:
2241
  return "تقصد أنهي مكان؟ اكتب اسم المكان أو اسألني الأول عن مطعم/صيدلية/كافيه. 😊"
2242
  t = norm(text)
2243
  name = place.get("name") or place.get("name_ar") or "المكان"
2244
  if any(w in t for w in ["رقم", "تليفون", "تلفون", "phone", "اتصل"]):
2245
- phone = place.get("phone") or ""
2246
- return f"📞 {name}: {phone}" if phone else f"😔 الرقم غير متاح لـ {name} حاليًا."
2247
  if any(w in t for w in ["عنوان", "فين", "مكان", "لوكيشن", "الموقع", "ازاي اروح"]):
2248
  addr = place.get("address") or place.get("location") or "العنوان غير متاح"
2249
  lat = place.get("lat")
@@ -2488,6 +2557,8 @@ def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2488
  # Islamic greeting gets proper Islamic reply
2489
  if intent == "greeting" and any(w in t_norm for w in ["السلام عليكم", "سلام عليكم", "السلام عليك"]):
2490
  reply = "وعليكم السلام ورحمة الله وبركاته 😊\nبتدور على إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟"
 
 
2491
  else:
2492
  replies = {
2493
  "greeting": "أهلاً 😊 قولي بتدور على إيه في بني سويف: مطعم، كافيه، صيدلية، ماركت أو سكن؟",
@@ -2784,6 +2855,27 @@ def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2784
  if results_df.empty and item_query and is_near_query(text):
2785
  results_df = search_places(text, category=category or "restaurant", item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name="", user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12)
2786
  soft_reason = "near_item" if not results_df.empty else soft_reason
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2787
  related_item_used = ""
2788
  if results_df.empty and item_query and not soft_reason:
2789
  pass
@@ -2804,6 +2896,8 @@ def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2804
  user_has_location=(user_lat is not None and user_lon is not None),
2805
  related_item_used=related_item_used,
2806
  )
 
 
2807
  session.add(text, reply, result_intent, entities, best, results)
2808
  return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results}
2809
  @asynccontextmanager
 
148
  "مطعم", "مطاعم", "اكل", "أكل", "وجبات", "مشويات", "كباب", "كفته", "كفتة",
149
  "شاورما", "كريب", "سندوتش", "سندوتشات", "برجر", "بيتزا", "فراخ", "فول",
150
  "طعمية", "سمك", "restaurant", "food", "burger", "pizza", "shawarma", "crepe",
151
+ # implicit "I'm hungry / want to eat" style requests — these mean
152
+ # "find me a restaurant", not a literal item or place name.
153
+ "جعان", "جعانة", "جوعان", "جوعانة", "هفطر", "هتغدى", "هتعشى",
154
+ "افطر", "أفطر", "اتغدى", "أتغدى", "اتعشى", "أتعشى", "عشا", "عشاء", "غدا", "غداء", "فطار", "فطور",
155
  ],
156
  "pharmacy": [
157
  "صيدليه", "صيدلية", "صيدليات", "صيدله", "صديليه", "صديليه", "دوا", "دواء", "ادويه", "أدوية",
158
  "ادوية", "علاج", "pharmacy", "drugstore", "medicine",
159
+ # implicit "I'm sick/tired" style requests commonly precede a
160
+ # pharmacy need in Egyptian Arabic conversation.
161
+ "تعبان", "تعبانة", "عيان", "عيانة",
162
  ],
163
  "cafe": [
164
  "كافيه", "كافيهات", "كافية", "كوفي", "قهوه", "قهوة", "كافيتيريا", "لاتيه",
 
190
  }
191
 
192
  KEYWORD_INTENTS = {
193
+ "greeting": ["السلام عليكم", "سلام عليكم", "وعليكم السلام", "اهلا", "أهلا", "هلا", "هاي", "مرحبا", "صباح الخير", "مساء الخير", "سلام", "hi", "hello", "hey",
194
+ "عامل ايه", "عامل إيه", "عاملة ايه", "عاملة إيه", "اخبارك ايه", "أخبارك ايه", "اخبارك إيه", "ازيك", "ازيّك", "ازيك ايه", "ايه الاخبار", "ايه أخبارك", "عامل ايه انهارده"],
195
  "thanks": ["شكرا", "شكراً", "تسلم", "تسلمي", "يسلمو", "مشكور", "thanks", "thank you"],
196
  "goodbye": ["مع السلامة", "مع السلامه", "باي", "وداعا", "bye", "goodbye"],
197
  "confirm": ["تمام", "اوك", "أوك", "ماشي", "حاضر", "اه", "اها", "ايوه", "نعم"],
 
983
  "فاتح", "فاتحه", "فاتحة", "مفتوح", "مفتوحه", "مفتوحة", "شغال", "شغاله", "شغالة",
984
  "دلوقتي", "حاليا", "الان", "هلا", "النهارده", "مني", "لي",
985
  "اروح", "هروح", "اشوف", "هشوف", "اتاكل", "أتاكل", "اقدر", "الاقي", "الاقيه",
986
+ "ادور", "هدور", "اديني", "اديلي", "جيبلي", "ازاي", "انا", "أنا",
987
+ "جعان", "جعانة", "جوعان", "جوعانة", "تعبان", "تعبانة", "عيان", "عيانة",
988
+ "افطر", "أفطر", "اتغدى", "أتغدى", "اتعشى", "أتعشى", "هفطر", "هتغدى", "هتعشى", "عشاء", "عشا", "غداء", "غدا", "فطار", "فطور",
989
  ]
990
  for w in remove_words:
991
  q = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", q)
 
1131
 
1132
 
1133
  def extract_location_suffix(text: str) -> tuple:
1134
+ # KNOWN LIMITATION: this only catches location phrases introduced by a
1135
+ # preposition (في/ناحية/قرب/جنب...). A location mentioned with NO
1136
+ # preposition at all ("الكورنيش عايز مطعم") isn't reliably detectable
1137
+ # here without either hardcoding area names (against this file's
1138
+ # no-hardcoding design) or a location gazetteer. In production this case
1139
+ # is expected to be caught by the real NER model (ner_pipe) instead —
1140
+ # this function is the rule-based fallback layer, not the only layer.
1141
  """Split a trailing '<preposition> <location words>' phrase off the end
1142
  of the text, e.g. 'عندو سندوتشات في كورنيش' -> ('عندو سندوتشات', 'كورنيش').
1143
 
 
1217
  "ادور", "هدور", "اديني", "اديلي", "هات", "جيبلي", "فين",
1218
  # generic "something to eat" filler — "حتة اكل"/"حته اكل" means "a
1219
  # bite to eat" in general, not a specific dish; never a real item.
1220
+ "حته", "حتة", "اكل", "أكل", "انا", "أنا",
1221
  ]
1222
  for w in generic_words:
1223
  cw = clean_text(w)
 
1362
  candidate = clean_text(candidate)
1363
  if not candidate or len(candidate) < 2:
1364
  return False
1365
+ if is_generic_category_item(candidate):
1366
+ # "مطعم" said alone means "a restaurant" (generic category request),
1367
+ # never the specific place named e.g. "مطعم النيل" just because its
1368
+ # name happens to start with the same generic word. Without this
1369
+ # guard, "مطعم في الكورنيش" would wrongly extract place_name="مطعم"
1370
+ # and search for a place literally named "مطعم" instead of doing a
1371
+ # normal category+location search.
1372
+ return False
1373
  try:
1374
  hits = name_search(candidate, category=category_hint, top_k=1)
1375
  if hits.empty and category_hint:
 
1561
  "مطعم", "صيدليه", "صيدلية", "صديليه", "كافيه", "ماركت", "سوبر", "سوبرماركت", "هات", "منيو", "عايز", "عايزة",
1562
  "عايزه", "عاوزه", "عاوز", "محتاج", "محتاجة", "محتاجه", "اشتري", "اشترى", "اشتر", "اجيب", "نفسي",
1563
  "اروح", "هروح", "ازاي", "اشوف", "هشوف", "اتاكل", "أتاكل", "اقدر", "الاقي", "الاقيه",
1564
+ "ادور", "هدور", "اديني", "اديلي", "جيبلي", "هل", "الوقت", "ده", "دي", "انا", "أنا",
1565
+ "جعان", "جعانة", "جوعان", "جوعانة", "تعبان", "تعبانة", "عيان", "عيانة",
1566
+ "افطر", "أفطر", "اتغدى", "أتغدى", "اتعشى", "أتعشى", "هفطر", "هتغدى", "هتعشى", "عشاء", "عشا", "غداء", "غدا", "فطار", "فطور",
1567
  "قريب", "اقرب", "مفتوح", "فاتح", "دلوقتي", "في", "من", "عند",
1568
  "رقمه", "رقمها", "تليفونه", "تليفونها", "ايه", "إيه", "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "توب", "التوب",
1569
  "طب", "طيب", "تمام", "ماشي", "كام", "بكام", "قد ايه", "مين",
 
1718
  return None
1719
 
1720
 
1721
+ def _split_conjunction_items(item_query: str) -> list:
1722
+ """Split a multi-item request like 'بيتزا وبرجر' / 'رز وزيت' / 'a and b'
1723
+ into individual item strings. Arabic 'و' (and) is normally attached
1724
+ directly to the following word with NO space ('لاتيه وموهيتو'), not
1725
+ surrounded by spaces on both sides — so we split on whitespace followed
1726
+ by 'و' immediately before a non-space character, which covers both the
1727
+ attached form and the (less common) spaced form ('لاتيه و موهيتو').
1728
+ Never splits a single item name that happens to start with 'و' as part
1729
+ of the word itself, since that only happens after a space+bare-و here.
1730
+ """
1731
+ parts = [p.strip() for p in re.split(r"\s+و\s*(?=\S)|\s*,\s*|\s*،\s*|\s+and\s+", item_query) if p.strip()]
1732
+ return parts if len(parts) > 1 else [item_query]
1733
+
1734
+
1735
  def item_matches_place(place: dict, item_query: str, use_menu: bool = True) -> bool:
1736
  item = clean_text(item_query)
1737
  if not item:
1738
  return True
1739
+ # Multi-item request ("بيتزا وبرجر"): the place must have ALL of them, not
1740
+ # just one. Previously the whole combined phrase was fuzzy-matched as a
1741
+ # single blob, so "بيتزا وسوشي" (pizza AND sushi) would wrongly match any
1742
+ # place that merely had pizza, even with no sushi at all.
1743
+ parts = _split_conjunction_items(item)
1744
+ if len(parts) > 1:
1745
+ return all(item_matches_place(place, p, use_menu=use_menu) for p in parts)
1746
  place_blob = clean_text(" ".join([
1747
  str(place.get("name", "")), str(place.get("name_ar", "")), str(place.get("name_en", "")),
1748
  str(place.get("category", "")), str(place.get("sub_category", "")), str(place.get("description", "")),
 
2284
  return best[1], best[2]
2285
 
2286
 
2287
+ def _format_phone_reply(name: str, phone_field) -> str:
2288
+ """Format a place's phone number(s) cleanly, no matter what shape the
2289
+ backend API returns them in (a single string, a comma/slash-separated
2290
+ string, or an actual list). Never prints a raw Python list like
2291
+ "['010...', '012...']" to the user.
2292
+ """
2293
+ numbers = []
2294
+ if isinstance(phone_field, (list, tuple, set)):
2295
+ numbers = [str(p).strip() for p in phone_field if str(p).strip()]
2296
+ elif isinstance(phone_field, str):
2297
+ numbers = [p.strip() for p in re.split(r"[,/;،]|\s{2,}", phone_field) if p.strip()]
2298
+ elif phone_field not in (None, ""):
2299
+ numbers = [str(phone_field).strip()]
2300
+ numbers = [n for n in dict.fromkeys(numbers) if n] # de-dupe, keep order
2301
+ if not numbers:
2302
+ return f"😔 الرقم غير متاح لـ {name} حاليًا."
2303
+ if len(numbers) == 1:
2304
+ return f"📞 {name}\n{numbers[0]}"
2305
+ lines = "\n".join(numbers)
2306
+ return f"📞 {name}\n{lines}"
2307
+
2308
+
2309
  def handle_detail(text: str, place: Optional[dict]) -> str:
2310
  if not place:
2311
  return "تقصد أنهي مكان؟ اكتب اسم المكان أو اسألني الأول عن مطعم/صيدلية/كافيه. 😊"
2312
  t = norm(text)
2313
  name = place.get("name") or place.get("name_ar") or "المكان"
2314
  if any(w in t for w in ["رقم", "تليفون", "تلفون", "phone", "اتصل"]):
2315
+ return _format_phone_reply(name, place.get("phone"))
 
2316
  if any(w in t for w in ["عنوان", "فين", "مكان", "لوكيشن", "الموقع", "ازاي اروح"]):
2317
  addr = place.get("address") or place.get("location") or "العنوان غير متاح"
2318
  lat = place.get("lat")
 
2557
  # Islamic greeting gets proper Islamic reply
2558
  if intent == "greeting" and any(w in t_norm for w in ["السلام عليكم", "سلام عليكم", "السلام عليك"]):
2559
  reply = "وعليكم السلام ورحمة الله وبركاته 😊\nبتدور على إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟"
2560
+ elif intent == "greeting" and any(w in t_norm for w in ["عامل", "عاملة", "اخبارك", "أخبارك", "ازيك", "ازيّك", "الاخبار", "أخبارك"]):
2561
+ reply = "تمام الحمد لله 😊 تحبي تسألي عن إيه النهارده؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟"
2562
  else:
2563
  replies = {
2564
  "greeting": "أهلاً 😊 قولي بتدور على إيه في بني سويف: مطعم، كافيه، صيدلية، ماركت أو سكن؟",
 
2855
  if results_df.empty and item_query and is_near_query(text):
2856
  results_df = search_places(text, category=category or "restaurant", item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name="", user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12)
2857
  soft_reason = "near_item" if not results_df.empty else soft_reason
2858
+ # ── Multi-item partial match fallback ──────────────────────────────────
2859
+ # "مطعم عنده بيتزا وبرجر": if no single place has ALL requested items,
2860
+ # don't silently fail — look for places that have AT LEAST ONE of them
2861
+ # and say so clearly, instead of returning nothing or (the old bug)
2862
+ # returning places that only match part of the request without saying so.
2863
+ partial_items_note = ""
2864
+ if results_df.empty and item_query:
2865
+ item_parts = _split_conjunction_items(item_query)
2866
+ if len(item_parts) > 1:
2867
+ try:
2868
+ base = places_df.copy() if places_df is not None else pd.DataFrame()
2869
+ if category and "category_norm" in base.columns:
2870
+ base = base[base["category_norm"].apply(lambda c: category_matches(c, category))]
2871
+ if not base.empty:
2872
+ mask = base.apply(lambda row: any(item_matches_place(row.to_dict(), p) for p in item_parts), axis=1)
2873
+ partial_df = base[mask]
2874
+ if not partial_df.empty:
2875
+ results_df = rank_places(partial_df, text, user_lat, user_lon, intent).head(12)
2876
+ partial_items_note = "مش لاقي مكان عنده كل الأصناف دي، لكن لقيت أماكن عندها جزء من الطلب:"
2877
+ except Exception as exc:
2878
+ log.warning("multi-item partial fallback failed: %s", exc)
2879
  related_item_used = ""
2880
  if results_df.empty and item_query and not soft_reason:
2881
  pass
 
2896
  user_has_location=(user_lat is not None and user_lon is not None),
2897
  related_item_used=related_item_used,
2898
  )
2899
+ if partial_items_note and results:
2900
+ reply = f"{partial_items_note}\n{reply}"
2901
  session.add(text, reply, result_intent, entities, best, results)
2902
  return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results}
2903
  @asynccontextmanager