Youmnaaaa commited on
Commit
0f2c736
·
verified ·
1 Parent(s): 875e4b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +321 -378
app.py CHANGED
@@ -538,9 +538,9 @@ def clean_item_query(text: str) -> str:
538
  "بيعمل", "يعمل", "بتعمل",
539
  "عنده", "عندها",
540
  "فيه", "فيها",
541
- "بيقدم", "بتقدم",
542
- "عندو", "نفسى"
543
-
544
  ]
545
 
546
  for w in remove_words:
@@ -910,7 +910,7 @@ def search_places(query, top_k_final=5, category=None, sub_category=None,
910
 
911
  RESPONSE_TEMPLATES = {
912
  "find_restaurant": [
913
- " لقيتلك *{name}* في {location}. {rating_info}{hours_info}",
914
  "أنصحك بـ *{name}* — هتلاقيه في {location}. {rating_info}{hours_info}",
915
  "في {location} فيه *{name}*. {description_short}{hours_info}",
916
  "دور على *{name}* في {location}. {rating_info}{hours_info}",
@@ -3354,427 +3354,370 @@ def search_places(query, top_k_final=5, category=None, sub_category=None,
3354
  return ranked.drop_duplicates(subset=["place_id"]).head(top_k_final)
3355
 
3356
 
 
 
 
3357
 
3358
- # ════════════════════════════════════════════════════════════════
3359
- # FINAL ROUTING PATCH — stable rules for doctor demo
3360
- # This section intentionally overrides earlier duplicated helpers.
3361
- # ════════════════════════════════════════════════════════════════
 
 
 
3362
 
3363
- _FOOD_ITEM_WORDS_FINAL = {
3364
- "شاورما","برجر","بيتزا","كريب","فراخ","فرخه","دجاج","مشويات","كباب","كفته","كفتة",
3365
- "سمك","سندوتش","ساندوتش","حواوشي","كشري","مكرونه","مكرونة","فتة","فته","طعمية","فول",
3366
- "اكل","اكلة","وجبة","وجبه","غدا","غداء","عشا","عشاء","burger","pizza","shawarma","crepe"
3367
  }
3368
- _DRINK_ITEM_WORDS_FINAL = {
3369
- "قهوه","قهوة","كوفي","لاتيه","اسبريسو","نسكافيه","عصير","مشروب","مشروبات",
3370
- "اسموزي","سموزي","سموذي","موهيتو","ساقعه","ساقعة","مانجو","خوخ","smoothie","juice","coffee"
3371
  }
3372
- _MENU_FOLLOWUP_FINAL = [
3373
- "بيقدم ايه","بتقدم ايه","عنده ايه","عندها ايه","ايه الموجود","الموجود عند",
3374
- "ايه الاصناف","اصنافه","اكلاته","منيوه","منيوها","القائمة","القائمه","menu"
 
 
 
 
3375
  ]
3376
- _DETAIL_PHONE_FINAL = ["رقمه","رقمها","رقم تليفونه","رقم تلفونه","تليفونه","تلفونه","phone","اتصل","اتواصل"]
3377
- _DETAIL_ADDR_FINAL = ["فينه","فينها","عنوانه","عنوانها","مكانه","مكانها","لوكيشن","الموقع","map","الخريطة"]
3378
- _DETAIL_HOURS_FINAL = ["مواعيده","مواعيدها","بيفتح","بتفتح","فاتح","مفتوح","شغال","امتى","امتي","بيقفل"]
3379
- _STUDY_WORK_FINAL = ["اذاكر","أذاكر","مذاكره","مذاكرة","اشتغل","شغل","لابتوب","هادي","هادئ","اقعد","أقعد","كووركينج","coworking","study","work"]
3380
- _HOUSING_FINAL = ["شقه","شقة","سكن","ايجار","إيجار","فندق","هوستل","مفروشه","مفروشة","apartment","hotel","hostel"]
3381
- _LOCATION_ALIASES_FINAL = {
3382
- "الاباصيري": ["الاباصيري","الأباصيري","اباصيري","أباصيري"],
3383
- "الكورنيش": ["الكورنيش","كورنيش"],
3384
- "مقبل": ["مقبل"],
3385
- "صلاح سالم": ["صلاح سالم"],
3386
- "عبدالسلام عارف": ["عبدالسلام عارف","عبد السلام عارف"],
3387
- "شرق النيل": ["شرق النيل"],
3388
- "الحي الاول": ["الحي الاول","الحي الأول","حي اول","حي أول"],
3389
- "الحي الثاني": ["الحي الثاني","الحي الثانى","الحي الثاني"],
3390
- "الحي الثالث": ["الحي الثالث"],
3391
- "الزراعيين": ["الزراعيين"],
3392
- "بني سويف": ["بني سويف","بنى سويف"],
3393
- }
3394
 
3395
- def _contains_any_final(text: str, words: list | set) -> bool:
3396
- t = norm(text)
3397
- return any(norm(w) in t for w in words)
 
3398
 
3399
- def _extract_location_final(text: str) -> str | None:
3400
- t = norm(text)
3401
- for canonical, variants in _LOCATION_ALIASES_FINAL.items():
3402
- if any(norm(v) in t for v in variants):
3403
- return canonical
3404
- return None
3405
 
3406
- def _infer_category_final(text: str) -> str | None:
3407
  t = norm(text)
3408
- # housing first because "مكان سكن" might also include generic "مكان"
3409
- if _contains_any_final(t, _HOUSING_FINAL):
3410
- return "housing"
3411
- if any(w in t for w in ["صيدليه","صيدلية","صيدلي","دوا","دواء","ادويه","ادوية","علاج","pharmacy","medicine"]):
3412
- return "pharmacy"
3413
- if any(w in t for w in ["سوبرماركت","سوبر ماركت","ماركت","هايبر","بقاله","بقالة","supermarket","market","grocery"]):
3414
- return "supermarket"
3415
- if any(w in t for w in ["كافيه","كافية","كوفي","قهوة","قهوه","كافيتيريا","cafe","coffee"]):
3416
- return "cafe"
3417
- if any(w in t for w in ["مطعم","مطاعم","اكل","أكل","وجبه","وجبة","جعان","جعانه","جعانة","اتعشى","عشا","غدا","غداء","restaurant","food"]):
3418
- return "restaurant"
3419
- if _contains_any_final(t, _STUDY_WORK_FINAL):
3420
- return "cafe"
3421
- return None
3422
 
3423
- def _is_best_final(text: str) -> bool:
3424
- return _contains_any_final(text, ["احسن","أحسن","افضل","أفضل","اعلى تقييم","أعلى تقييم","انضف","أنضف","best","top"])
3425
 
3426
- def _is_open_query_final(text: str) -> bool:
3427
- return _contains_any_final(text, ["مفتوح","فاتح","دلوقتي","شغال","open now","opened now"])
 
 
 
 
 
 
3428
 
3429
- def _is_nearest_final(text: str) -> bool:
3430
- return _is_proximity_query(text)
3431
 
3432
- def _is_detail_followup_final(text: str) -> bool:
3433
- return _contains_any_final(text, _DETAIL_PHONE_FINAL + _DETAIL_ADDR_FINAL + _DETAIL_HOURS_FINAL)
 
 
 
 
 
 
 
 
 
 
 
 
 
3434
 
3435
- def _is_menu_followup_final(text: str) -> bool:
3436
- return _contains_any_final(text, _MENU_FOLLOWUP_FINAL)
3437
 
3438
- def _looks_like_menu_request_final(text: str) -> bool:
3439
- t = norm(text)
3440
- # Explicit menu words or "what does PLACE offer?"
3441
- if any(w in t for w in ["منيو","menu","القائمة","القائمه","الاصناف","الأصناف","اكلاته","أكلاته"]):
3442
- return True
3443
- if any(p in t for p in ["ايه الموجود عند","الموجود عند","بيقدم ايه","بتقدم ايه","عنده ايه","عندها ايه"]):
3444
- return True
3445
- return False
 
 
 
3446
 
3447
- def _strip_category_location_words_final(text: str) -> str:
3448
- t = clean_text(text)
3449
- for loc, vars_ in _LOCATION_ALIASES_FINAL.items():
3450
- for v in vars_:
3451
- t = t.replace(clean_text(v), " ")
3452
- stop = [
3453
- "عايز","عايزة","عايزه","عاوز","عاوزة","عاوزه","فين","دور","دوري","بدور","ابحث","هات","هاتلي","جيب",
3454
- "مطعم","مطاعم","كافيه","صيدلية","صيدليه","سوبرماركت","سوبر","ماركت","مكان","اماكن","أحسن","احسن",
3455
- "افضل","أفضل","اقرب","أقرب","قريب","في","من","على","عن","باسم","اسمه","اسم","معلومات"
3456
- ]
3457
- for w in stop:
3458
- t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t)
3459
- return re.sub(r"\s+", " ", t).strip()
3460
 
3461
- def _is_known_item_text_final(text: str) -> bool:
3462
- t = norm(text)
3463
- return _contains_any_final(t, _FOOD_ITEM_WORDS_FINAL | _DRINK_ITEM_WORDS_FINAL)
 
 
 
 
 
3464
 
3465
- def _looks_like_item_search(text: str) -> bool:
3466
- """
3467
- Safer override:
3468
- - NOT every sentence containing "فيه" is an item.
3469
- - Study/work/housing/open-pharmacy/general dinner queries go to category search.
3470
- - "مطعم فيه شاورما" / "مكان عنده اسموزي" goes to item search.
3471
- """
3472
- t = norm(text)
3473
- if _contains_any_final(t, _STUDY_WORK_FINAL) or _contains_any_final(t, _HOUSING_FINAL):
3474
  return False
3475
- if _infer_category_final(t) in ("pharmacy", "supermarket", "housing"):
3476
  return False
3477
- if _looks_like_menu_request_final(t):
3478
  return False
3479
-
3480
- # explicit food/drink words without a clear place-name lookup
3481
- if _is_known_item_text_final(t):
3482
- # "فين مطعم سبايكو" should be place lookup, but "فين شاورما" is item
3483
- if "باسم" in t or "اسمه" in t:
3484
- return False
 
 
3485
  return True
3486
-
3487
- # explicit patterns: "مكان عنده X", "فيه X", "بيعمل X" only if X remains meaningful
3488
- patterns = [
3489
- r"(مكان|مطعم|كافيه)\s+(فيه|فيها|عنده|عندها|بيعمل|بتعمل|بيقدم|بتقدم|بيبيع|بتبيع)\s+(.+)",
3490
- r"(عايز|عايزه|عايزة|نفسي في|محتاج)\s+(.+)"
3491
- ]
3492
- for pat in patterns:
3493
- m = re.search(pat, t)
3494
- if m:
3495
- candidate = clean_item_query(m.group(len(m.groups()))).strip()
3496
- if len(clean_text(candidate)) >= 3 and not _contains_any_final(candidate, _STUDY_WORK_FINAL | set(_HOUSING_FINAL)):
3497
- # unknown words are accepted only in explicit item verbs, not generic "عايزة مكان"
3498
- if any(v in t for v in ["فيه","فيها","عنده","عندها","بيعمل","بتعمل","بيقدم","بتقدم","بيبيع","بتبيع"]):
3499
- return True
3500
  return False
3501
 
3502
- def _detect_new_intent(text: str) -> str | None:
3503
- # Menu has priority over item for follow-up like "بيقدم ايه"
3504
- if _looks_like_menu_request_final(text):
 
3505
  return "show_menu"
3506
- if _looks_like_item_search(text):
3507
  return "search_by_item"
3508
  return None
3509
 
3510
- def extract_item_query(text: str) -> str | None:
 
 
 
3511
  t = norm(text)
3512
- # Try explicit item phrases first
3513
- explicit_verbs = ["فيه","فيها","عنده","عندها","بيعمل","بتعمل","بيقدم","بتقدم","بيبيع","بتبيع"]
3514
- for v in explicit_verbs:
3515
- if v in t:
3516
- candidate = t.split(v, 1)[1]
3517
- # remove trailing constraints
3518
- for cut in ["ويكون","و يكون","يكون","في الاباصيري","في الكورنيش","في مقبل","قريب","فاتح","دلوقتي"]:
3519
- candidate = candidate.replace(cut, " ")
3520
- candidate = clean_item_query(candidate)
3521
- if candidate and len(clean_text(candidate)) >= 2:
3522
- return candidate
3523
- # Known food/drink item from sentence
3524
- words = [w for w in clean_text(text).split() if w not in _FOOD_STOP_WORDS and len(w) > 1]
3525
- keep = []
3526
- for w in words:
3527
- if _contains_any_final(w, _FOOD_ITEM_WORDS_FINAL | _DRINK_ITEM_WORDS_FINAL):
3528
- keep.append(w)
3529
- elif keep and w not in ["قريب","دلوقتي","فاتح","احسن","افضل"]:
3530
- keep.append(w)
3531
- candidate = " ".join(keep).strip()
3532
- if candidate:
3533
- return candidate
3534
- # fallback only when function was called after item detection
3535
- candidate = _strip_category_location_words_final(text)
3536
- return candidate if len(clean_text(candidate)) >= 3 else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3537
 
3538
- def _extract_place_name_final(text: str, category: str | None = None) -> str | None:
3539
- # Avoid treating food/item/mood/housing as place names
3540
- if _looks_like_item_search(text) or _contains_any_final(text, _STUDY_WORK_FINAL):
 
3541
  return None
3542
- candidate = _strip_category_location_words_final(text)
3543
- if not candidate or len(clean_text(candidate)) < 3:
3544
  return None
3545
- # no place name for generic category requests
3546
- if candidate in {"مكان","حاجه","حاجة","مطعم","كافيه","صيدلية","سوبرماركت","سكن"}:
3547
  return None
3548
- return candidate
3549
 
3550
- def extract_menu_place_name(text: str) -> str | None:
3551
- t = norm(text)
3552
- # "on public ايه الموجود عند" => before phrase
3553
- for marker in ["ايه الموجود عند", "الموجود عند"]:
3554
- if marker in t:
3555
- before = t.split(marker, 1)[0].strip()
3556
- after = t.split(marker, 1)[1].strip()
3557
- cand = after or before
3558
- cand = _strip_category_location_words_final(cand)
3559
- return cand if len(clean_text(cand)) >= 3 else None
3560
- # "بيقدم ايه" follow-up => no place name; handler will use last_place
3561
- if t.strip() in ["بيقدم ايه","بتقدم ايه","عنده ايه","عندها ايه"]:
3562
- return None
3563
- # normal menu request
3564
- cand = t
3565
- for w in ["هات","هاتي","عايز","عايزة","عايزه","وريني","اعرض","اشوف","منيو","menu","القائمة","القا��مه","الاصناف","الأصناف","بتاع","بتاعت","ايه"]:
3566
- cand = cand.replace(w, " ")
3567
- cand = _strip_category_location_words_final(cand)
3568
- return cand if len(clean_text(cand)) >= 3 else None
3569
-
3570
- def _sort_best_final(rows: list[dict]) -> list[dict]:
3571
- def key(p):
3572
- r = p.get("rating_norm", p.get("rating", 0)) or 0
3573
- try: r = float(r)
3574
- except: r = 0
3575
- fs = p.get("final_score", 0) or 0
3576
- try: fs = float(fs)
3577
- except: fs = 0
3578
- return (r, fs)
3579
- return sorted(rows, key=key, reverse=True)
3580
-
3581
- def _response_from_places_final(text, intent, category, entities, results, user_lat=None, user_lon=None):
3582
- if not results:
3583
- return {
3584
- "reply": smart_no_result(intent, category=category, location=entities.get("location"),
3585
- place_name=entities.get("place_name"), open_now_only=entities.get("open_now_only", False)),
3586
- "intent": "no_result",
3587
- "confidence": 0.95,
3588
- "entities": entities,
3589
- "best_place": None,
3590
- "all_results": []
3591
- }
3592
- if _is_best_final(text):
3593
- results = _sort_best_final(results)
3594
- best = results[0]
3595
- # explicit open question should answer status clearly, not dump hours only
3596
- if entities.get("open_now_only"):
3597
- name = best.get("name", "المكان")
3598
- on = best.get("open_now")
3599
- if on == 1 or on is True:
3600
- reply = f"🟢 أيوه، *{name}* مفتوح دلوقتي."
3601
- elif on == 0 or on is False:
3602
- reply = f"🔴 *{name}* مغلق حاليًا."
3603
- else:
3604
- reply = f"لقيت *{name}*، بس المواعيد مش واضحة عندي."
3605
- elif _is_nearest_final(text) and user_lat is not None and user_lon is not None:
3606
- d = best.get("distance_km")
3607
- d_txt = f" — {float(d):.1f} كم" if d is not None else ""
3608
- reply = f"📍 الأقرب ليك: *{best.get('name','')}*{d_txt}"
3609
- elif _is_best_final(text):
3610
- reply = f"🏆 أحسن اختيار: *{best.get('name','')}* — تقييمه {best.get('rating_norm', best.get('rating', 0))} ⭐"
3611
- else:
3612
- reply = build_response(best, intent, category=category, total_results=len(results))
3613
- return {
3614
- "reply": reply,
3615
- "intent": intent,
3616
- "confidence": 0.95,
3617
- "entities": entities,
3618
- "best_place": best,
3619
- "all_results": results
3620
- }
3621
 
3622
- def handle_show_menu(text: str, session, entities: dict) -> dict:
3623
- place = None
3624
- place_name = extract_menu_place_name(text) or (entities or {}).get("place_name")
3625
  if place_name:
3626
- hits = name_search(place_name, top_k=1)
3627
- if not hits.empty:
3628
- place = hits.iloc[0].to_dict()
3629
- if place is None and getattr(session, "last_place", None):
3630
- place = session.last_place
3631
- if place is None:
3632
- result = {"reply": "تقصد منيو أنهي مكان؟ اكتب اسم المطعم أو الكافيه. 😊",
3633
- "intent": "show_menu", "ui_type": CFG.UI_TEXT_ONLY, "menu_items": [], "best_place": None}
3634
- session.add(text, result["reply"], "show_menu", {}, None, [])
3635
- return result
3636
- place_id = str(place.get("place_id") or place.get("id") or "").strip()
3637
- menu_items = get_place_menu(place_id) if place_id else []
3638
- result = format_menu_response(place, menu_items)
3639
- # keep last place for "رقمه/فينه" later
3640
- cleanp = clean_place(place)
3641
- session.add(text, result["reply"], "show_menu", {"place_name": place.get("name")}, cleanp, [])
3642
- session.last_place = cleanp
3643
- return result
3644
-
3645
- def handle_search_by_item(text: str, session, user_lat=None, user_lon=None) -> dict:
3646
- category = _infer_category_final(text) or "restaurant"
3647
- location = _extract_location_final(text)
3648
- item_query = extract_item_query(text)
3649
- if not item_query:
3650
- # degrade to category search instead of wrong item
3651
- return chat(text, session, user_lat, user_lon)
3652
- places = search_places_by_item(item_query)
3653
- places = filter_item_results_strict(places, item_query)
3654
- if not places:
3655
- places = scan_menus_for_item(item_query)
3656
- # enforce location if user specified one
3657
- if location and places:
3658
- loc_c = clean_text(location)
3659
- def ok_loc(p):
3660
- blob = clean_text(f"{p.get('location','')} {p.get('address','')}")
3661
- return any(part in blob for part in loc_c.split() if len(part)>1)
3662
- places = [p for p in places if ok_loc(p)]
3663
- if not places:
3664
- reply = f"مفيش أماكن بتقدم *{item_query}*"
3665
- if location:
3666
- reply += f" في {location}"
3667
- reply += " حاليًا 😔"
3668
- result = {"reply": reply, "intent": "no_result", "ui_type": CFG.UI_TEXT_ONLY, "place_cards": [], "menu_items": [], "best_place": None}
3669
- session.add(text, result["reply"], "no_result", {"item_query": item_query, "location": location} if location else {"item_query": item_query}, None, [])
3670
- return result
3671
- # sort by distance or rating depending query
3672
- if _is_best_final(text):
3673
- places = _sort_best_final(places)
3674
- else:
3675
- places = _sort_places_by_distance(places, user_lat, user_lon)
3676
- result = format_item_search_response(places, item_query, user_lat, user_lon)
3677
- result["intent"] = "search_by_item"
3678
  if location:
3679
- result["reply"] = result["reply"].replace("— اختار:", f" في {location} — اختار:")
3680
- bestp = result.get("best_place")
3681
- session.add(text, result["reply"], "search_by_item", {"item_query": item_query, "category": category, "location": location} if location else {"item_query": item_query, "category": category}, bestp, places)
3682
- if bestp:
3683
- session.last_place = bestp
3684
- return result
3685
 
3686
- def chat(text: str, session, user_lat=None, user_lon=None):
3687
- text = str(text or "").strip()
3688
- if not text:
3689
- return {"reply": "اكتب سؤالك 😊", "intent": "fallback", "confidence": 0.0, "entities": {}, "best_place": None, "all_results": []}
3690
 
3691
- # 1) static intents
3692
- override = apply_keyword_override(text)
3693
- if override:
3694
- reply = random.choice(RESPONSE_TEMPLATES.get(override, RESPONSE_TEMPLATES["fallback"]))
3695
- session.add(text, reply, override, {}, None, [])
3696
- return {"reply": reply, "intent": override, "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
3697
-
3698
- # 2) follow-up details/menu with last place
3699
- if getattr(session, "last_place", None):
3700
- if _is_menu_followup_final(text):
3701
- res = handle_show_menu(text, session, {})
3702
- return {"reply": res.get("reply",""), "intent": "show_menu", "confidence": 0.97,
3703
- "entities": {}, "best_place": session.last_place, "all_results": []}
3704
- if _is_detail_followup_final(text):
3705
- reply = handle_detail(text, session.last_place)
3706
- session.add(text, reply, "place_details", {}, session.last_place, [session.last_place])
3707
- return {"reply": reply, "intent": "place_details", "confidence": 0.97, "entities": {},
3708
- "best_place": session.last_place, "all_results": [session.last_place]}
3709
-
3710
- # 3) out of scope
3711
  if is_out_of_scope(text):
3712
- reply = "أنا متخصص في أماكن بني سويف: مطاعم، كافيهات، صيدليات، سوبرماركت وسكن 😊"
 
3713
  session.add(text, reply, "out_of_scope", {}, None, [])
3714
- return {"reply": reply, "intent": "out_of_scope", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
3715
 
3716
- # 4) menu request
3717
- if _looks_like_menu_request_final(text):
3718
- res = handle_show_menu(text, session, {})
3719
- return {"reply": res.get("reply",""), "intent": "show_menu", "confidence": 0.97,
3720
- "entities": {"place_name": extract_menu_place_name(text)}, "best_place": res.get("best_place"), "all_results": []}
 
 
3721
 
3722
- # 5) item request only when safe
3723
- if _looks_like_item_search(text):
3724
- res = handle_search_by_item(text, session, user_lat, user_lon)
3725
- return {"reply": res.get("reply",""), "intent": res.get("intent","search_by_item"), "confidence": 0.97,
3726
- "entities": {"item_query": extract_item_query(text)}, "best_place": res.get("best_place"), "all_results": res.get("place_cards", [])}
3727
-
3728
- # 6) category/place search
3729
- category = _infer_category_final(text)
3730
- location = _extract_location_final(text)
3731
- open_now = _is_open_query_final(text)
3732
- if open_now and not category:
3733
- # "أجيب دوا" -> pharmacy, "آكل" -> restaurant
3734
- category = "pharmacy" if any(w in norm(text) for w in ["دوا","دواء","علاج","ادويه","ادوية"]) else "restaurant"
3735
-
3736
- intent_map = {"restaurant":"nearest_restaurant","pharmacy":"nearest_pharmacy","cafe":"nearest_cafe","supermarket":"nearest_supermarket","housing":"housing_search"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3737
  intent = intent_map.get(category, "recommend_place")
3738
 
3739
- # reset old context if category changed
3740
- old_cat = session.context_slots.get("category") if hasattr(session, "context_slots") else None
3741
- if category and old_cat and normalize_category(old_cat) != normalize_category(category):
 
3742
  session.last_place = None
3743
  session.last_results = []
3744
- session.result_pointer = 0
3745
- session.context_slots = {}
3746
-
3747
- place_name = None
3748
- # place lookup only for name-style queries, not generic category/mood
3749
- if any(w in norm(text) for w in ["فين مطعم","فين كافيه","فين صيدلية","دور على","معلومات عن","باسم","اسمه"]):
3750
- place_name = _extract_place_name_final(text, category)
3751
 
3752
- entities = {"category": category} if category else {}
3753
- if location: entities["location"] = location
3754
- if place_name: entities["place_name"] = place_name
3755
- if open_now: entities["open_now_only"] = True
3756
 
3757
- # missing info for vague "مكان" only
3758
- if not category and any(w in norm(text) for w in ["مكان","حاجه","حاجة"]):
3759
- reply = "تقصد مكان من أي نوع؟ مطعم، كافيه، صيدلية، سوبرماركت ولا سكن؟ 😊"
 
3760
  session.add(text, reply, "missing_info", {}, None, [])
3761
- return {"reply": reply, "intent": "missing_info", "confidence": 0.9, "entities": {}, "best_place": None, "all_results": []}
3762
-
3763
- results_df = search_places(text, top_k_final=5, category=category, location=location,
3764
- open_now_only=open_now, user_lat=user_lat, user_lon=user_lon,
3765
- intent=intent, place_name=place_name)
3766
- results = results_df.to_dict("records") if hasattr(results_df, "to_dict") and not results_df.empty else []
3767
-
3768
- # If location was requested and no places there, give explicit no-location reply.
3769
- if not results and location:
3770
- cat_ar = _CAT_AR.get(category or "", "أماكن")
3771
- reply = f"مفيش {cat_ar} متاحة حاليًا في {location} 😔"
3772
- session.add(text, reply, "no_result", entities, None, [])
3773
- return {"reply": reply, "intent": "no_result", "confidence": 0.95, "entities": entities, "best_place": None, "all_results": []}
3774
-
3775
- out = _response_from_places_final(text, intent, category, entities, results, user_lat, user_lon)
3776
- session.add(text, out["reply"], out["intent"], entities, out.get("best_place"), out.get("all_results", []))
3777
- if out.get("best_place"):
3778
- session.last_place = clean_place(out["best_place"])
3779
- session.context_slots["category"] = category or ""
3780
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
  "بيعمل", "يعمل", "بتعمل",
539
  "عنده", "عندها",
540
  "فيه", "فيها",
541
+ "بيقدم", "بتقدم"
542
+ "عندو", "نفسى", "عندك", "عندكم",
543
+ "لو سمحت", "من فضلك", "لو ممكن", "ممكن"
544
  ]
545
 
546
  for w in remove_words:
 
910
 
911
  RESPONSE_TEMPLATES = {
912
  "find_restaurant": [
913
+ "🍽️ لقيتلك *{name}* في {location}. {rating_info}{hours_info}",
914
  "أنصحك بـ *{name}* — هتلاقيه في {location}. {rating_info}{hours_info}",
915
  "في {location} فيه *{name}*. {description_short}{hours_info}",
916
  "دور على *{name}* في {location}. {rating_info}{hours_info}",
 
3354
  return ranked.drop_duplicates(subset=["place_id"]).head(top_k_final)
3355
 
3356
 
3357
+ # ═══════════════════════════════════════════════════════════════════════
3358
+ # FINAL_DOCTOR_DEMO_PATCH_V2 — single routing layer to stop case-by-case bugs
3359
+ # ═══════════════════════════════════════════════════════════════════════
3360
 
3361
+ _CAT_SYNONYMS_V2 = {
3362
+ "pharmacy": ["صيدلية", "صيدليه", "صيدليات", "صيدله", "دوا", "دواء", "ادويه", "ادوية", "علاج", "pharmacy", "drugstore", "medicine"],
3363
+ "supermarket": ["سوبرماركت", "سوبر ماركت", "سوبر", "ماركت", "هايبر", "بقاله", "بقالة", "جروسري", "supermarket", "market", "grocery", "hypermarket"],
3364
+ "housing": ["سكن", "شقه", "شقة", "شقق", "مفروشه", "مفروشة", "ايجار", "إيجار", "فندق", "هوستل", "apartment", "hotel", "housing", "rent"],
3365
+ "cafe": ["كافيه", "كافية", "كافيهات", "كوفي", "قهوة", "قهوه", "كافيتيريا", "اذاكر", "أذاكر", "مذاكره", "مذاكرة", "اشتغل", "شغل", "لابتوب", "هادي", "هادى", "اقعد", "cafe", "coffee"],
3366
+ "restaurant": ["مطعم", "مطاعم", "اكل", "أكل", "طعام", "وجبة", "وجبه", "اتعشى", "أتعشى", "عشا", "غدا", "جعان", "جعانة", "restaurant", "food", "eat", "dinner", "lunch"],
3367
+ }
3368
 
3369
+ _FOOD_HINTS_V2 = {
3370
+ "شاورما", "شورما", "برجر", "burger", "بيتزا", "pizza", "كريب", "crepe", "فراخ", "دجاج", "فرايد", "مشويات", "كباب", "كفته", "كفتة", "سمك", "سندوتش", "ساندوتش", "حواوشي", "كشري", "مكرونه", "مكرونة", "فتة", "فته", "بطاطس", "بروست", "بروستد", "سيبايكو", "سبايكو"
 
 
3371
  }
3372
+ _DRINK_HINTS_V2 = {
3373
+ "قهوة", "قهوه", "كوفي", "coffee", "لاتيه", "latte", "اسبريسو", "نسكافيه", "موهيتو", "mojito", "عصير", "سموذي", "سموزي", "اسموزي", "smoothie", "مانجو", "خوخ", "مشروب", "مشروبات", "ساقعة", "ساقعه"
 
3374
  }
3375
+ _ITEM_CONTEXT_V2 = ["فيه", "فيها", "عنده", "عندها", "بيعمل", "بتعمل", "بيقدم", "بتقدم", "بيبيع", "بتبيع", "عندكم", "موجود", "available", "has", "serve", "serves"]
3376
+ _MENU_WORDS_V2 = ["منيو", "مينيو", "menu", "القائمة", "قايمة", "قائمه", "الاصناف", "الأصناف", "بيقدم ايه", "بتقدم ايه", "ايه الموجود", "الموجود عند", "عنده ايه", "عندها ايه", "فيه ايه", "بيبيع ايه"]
3377
+ _RANK_WORDS_V2 = ["احسن", "أحسن", "افضل", "أفضل", "الاحسن", "الأحسن", "الافضل", "الأفضل", "اعلى", "أعلى", "تقييم", "رشح", "نضيف", "انضف"]
3378
+ _NEAR_WORDS_V2 = ["اقرب", "أقرب", "الاقرب", "الأقرب", "قريب", "قريبه", "قريبة", "جنبي", "حواليا", "حولي", "near", "nearest", "nearby", "close"]
3379
+ _OPEN_WORDS_V2 = ["فاتح", "فاتحه", "فاتحة", "مفتوح", "مفتوحة", "مفتوحه", "دلوقتي", "الان", "الآن", "شغال", "شغاله", "open now"]
3380
+ _LOCATIONS_V2 = [
3381
+ "الاباصيري", "الأباصيري", "اباصيري", "أباصيري", "الكورنيش", "كورنيش", "مقبل", "صلاح سالم", "عبدالسلام عارف", "احمد عرابي", "أحمد عرابي", "عرابي", "شرق النيل", "الحي الاول", "الحي الأول", "الحي الثاني", "الحي الثالث", "الحي الرابع", "الحي الخامس", "الزراعيين", "الروضه", "الروضة", "سيتي سنتر", "بني سويف", "بنى سويف"
3382
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3383
 
3384
+ _STOP_FOR_NAME_V2 = set(clean_text(x) for x in (
3385
+ list(sum(_CAT_SYNONYMS_V2.values(), [])) + _ITEM_CONTEXT_V2 + _MENU_WORDS_V2 + _RANK_WORDS_V2 + _NEAR_WORDS_V2 + _OPEN_WORDS_V2 +
3386
+ ["عايز", "عايزة", "عايزه", "عاوز", "عاوزه", "محتاج", "محتاجة", "محتاجه", "بدور", "دور", "هات", "هاتي", "فين", "مكان", "اماكن", "في", "من", "على", "عن", "لي", "ليا", "لو سمحت", "ممكن"]
3387
+ ))
3388
 
 
 
 
 
 
 
3389
 
3390
+ def _has_v2(text, words):
3391
  t = norm(text)
3392
+ toks = set(t.split())
3393
+ for w in words:
3394
+ ww = norm(w)
3395
+ if not ww:
3396
+ continue
3397
+ if (" " in ww and ww in t) or ww in toks or ww in t:
3398
+ return True
3399
+ return False
 
 
 
 
 
 
3400
 
 
 
3401
 
3402
+ def infer_category(query): # noqa: F811
3403
+ """Deterministic category with safe precedence."""
3404
+ q = norm(query)
3405
+ # pharmacy/supermarket/housing should not be stolen by food/item words
3406
+ for cat in ["pharmacy", "supermarket", "housing", "cafe", "restaurant"]:
3407
+ if _has_v2(q, _CAT_SYNONYMS_V2[cat]):
3408
+ return cat
3409
+ return None
3410
 
 
 
3411
 
3412
+ def _extract_location_v2(text: str) -> str | None:
3413
+ t = norm(text)
3414
+ for loc in sorted(_LOCATIONS_V2, key=len, reverse=True):
3415
+ if norm(loc) in t:
3416
+ return clean_text(loc)
3417
+ # simple pattern after في
3418
+ m = re.search(r"(?:في|فى)\s+([\w\s]{2,30})", clean_text(text))
3419
+ if m:
3420
+ cand = m.group(1).strip()
3421
+ # stop before item/open/ranking words
3422
+ for stop in ["ويكون", "يكون", "فاتح", "قريب", "عنده", "فيه"]:
3423
+ cand = cand.split(stop)[0].strip()
3424
+ if cand and cand not in _STOP_FOR_NAME_V2 and len(cand) > 2:
3425
+ return cand
3426
+ return None
3427
 
 
 
3428
 
3429
+ def _strip_known_parts_v2(text: str, category: str | None = None, location: str | None = None) -> str:
3430
+ q = clean_text(text)
3431
+ if location:
3432
+ q = q.replace(clean_text(location), " ")
3433
+ for loc in _LOCATIONS_V2:
3434
+ q = q.replace(clean_text(loc), " ")
3435
+ words = set(_STOP_FOR_NAME_V2)
3436
+ if category:
3437
+ words.update(clean_text(w) for w in _CAT_SYNONYMS_V2.get(category, []))
3438
+ toks = [w for w in q.split() if w not in words and len(w) > 1]
3439
+ return " ".join(toks).strip()
3440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3441
 
3442
+ def _item_candidate_v2(text: str) -> str:
3443
+ cat = infer_category(text)
3444
+ loc = _extract_location_v2(text)
3445
+ cand = _strip_known_parts_v2(text, cat, loc)
3446
+ # remove generic verbs that are not item names
3447
+ bad_phrases = ["اقدر", "اقدر اذاكر", "اقدر اشتغل", "اقعد", "اشتغل", "اذاكر", "مفروشه", "مفروشة", "اتعشى", "امشي", "كتير", "حاجه", "حاجة"]
3448
+ toks = [w for w in cand.split() if w not in set(clean_text(x) for x in bad_phrases)]
3449
+ return " ".join(toks).strip()
3450
 
3451
+
3452
+ def _is_real_item_query_v2(text: str) -> bool:
3453
+ cat = infer_category(text)
3454
+ cand = _item_candidate_v2(text)
3455
+ # never item for pharmacy/supermarket/housing/mood/study/work/housing
3456
+ if cat in ("pharmacy", "supermarket", "housing"):
 
 
 
3457
  return False
3458
+ if _has_v2(text, ["اذاكر", "أذاكر", "مذاكرة", "مذاكره", "اشتغل", "شغل", "لابتوب", "شقة", "شقه", "سكن"]):
3459
  return False
3460
+ if not cand:
3461
  return False
3462
+ # direct food/drink words
3463
+ if _has_v2(cand, _FOOD_HINTS_V2 | _DRINK_HINTS_V2):
3464
+ return True
3465
+ # unknown item only when explicit item context exists and not just generic lifestyle words
3466
+ if _has_v2(text, _ITEM_CONTEXT_V2) and len(cand) >= 3:
3467
+ return True
3468
+ # short demand with unknown item and no category: "عايز موهيتو"
3469
+ if cat is None and _has_v2(text, ["عايز", "عايزة", "عايزه", "نفسي", "محتاج"]) and len(cand) >= 3:
3470
  return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3471
  return False
3472
 
3473
+
3474
+ def _detect_new_intent(text: str) -> str | None: # noqa: F811
3475
+ # Menu first, including follow-up "بيقدم ايه".
3476
+ if _has_v2(text, _MENU_WORDS_V2) and not _is_real_item_query_v2(text):
3477
  return "show_menu"
3478
+ if _is_real_item_query_v2(text):
3479
  return "search_by_item"
3480
  return None
3481
 
3482
+
3483
+ def _detect_compare_intent(text: str) -> str | None: # noqa: F811
3484
+ if infer_category(text) or _is_real_item_query_v2(text):
3485
+ return None
3486
  t = norm(text)
3487
+ if any(w in t for w in ["فيهم", "منهم", "دول", "النتايج", "ايه الاحسن", "إيه الاحسن", "انهي واحد", "اختار"]):
3488
+ if _has_v2(text, _NEAR_WORDS_V2) and _has_v2(text, _RANK_WORDS_V2):
3489
+ return "both"
3490
+ if _has_v2(text, _NEAR_WORDS_V2):
3491
+ return "nearest"
3492
+ return "best"
3493
+ return None
3494
+
3495
+
3496
+ def detect_ref_type(text): # noqa: F811
3497
+ if _has_v2(text, ["رقم", "رقمه", "رقمها", "نمره", "نمرته", "تليفون", "تليفونه", "تليفونها", "موبايل", "فون", "phone", "call"]):
3498
+ return "detail"
3499
+ if _has_v2(text, ["عنوان", "عنوانه", "فين", "فينه", "فينها", "مكانه", "مكانها", "لوكيشن", "موقع", "map", "اروح"]):
3500
+ return "detail"
3501
+ if _has_v2(text, ["مواعيد", "مواعيده", "بيفتح", "بيقفل", "فاتح", "شغال", "مفتوح"]):
3502
+ return "detail"
3503
+ if _has_v2(text, NEXT_WORDS):
3504
+ return "next"
3505
+ return "new"
3506
+
3507
+
3508
+ def _format_open_status_v2(place: dict) -> str:
3509
+ h = place.get("opening_hours", "")
3510
+ on = place.get("open_now")
3511
+ if on is None:
3512
+ on = check_open_now(h)
3513
+ name = place.get("name", "المكان")
3514
+ if on == 1:
3515
+ return f"🟢 *{name}* مفتوح دلوقتي."
3516
+ if on == 0:
3517
+ return f"🔴 *{name}* مغلق دلوقتي."
3518
+ return f"مواعيد *{name}* غير واضحة عندنا حاليًا."
3519
+
3520
+
3521
+ def handle_detail(text, place): # noqa: F811
3522
+ if not place:
3523
+ return "تقصد أنهي مكان؟ اكتب اسم المكان أو اسألني الأول عن مكان معيّن. 😊"
3524
+ name = place.get("name", "المكان")
3525
+ if _has_v2(text, ["رقم", "رقمه", "رقمها", "نمره", "نمرته", "تليفون", "تليفونه", "تليفونها", "موبايل", "فون", "phone", "call"]):
3526
+ ph = place.get("phone", "")
3527
+ if isinstance(ph, (list, tuple)):
3528
+ ph = ", ".join(str(x) for x in ph if x)
3529
+ elif isinstance(ph, str) and ph.startswith("[") and ph.endswith("]"):
3530
+ ph = ph.strip("[]").replace("'", "").replace('"', "").strip()
3531
+ return f"📞 رقم *{name}*: {ph}" if ph and str(ph).strip().lower() not in ("", "nan", "none", "[]") else f"مش عندنا رقم *{name}* حاليًا."
3532
+ if _has_v2(text, ["فاتح", "شغال", "مفتوح"]):
3533
+ return _format_open_status_v2(place)
3534
+ if _has_v2(text, ["مواعيد", "مواعيده", "بيفتح", "بيقفل", "امتى", "امتي"]):
3535
+ h = place.get("opening_hours", "")
3536
+ return f"🕐 مواعيد *{name}*: {h}" if h and str(h).strip().lower() not in ("", "nan", "none") else f"المواعيد غير متاحة لـ *{name}*."
3537
+ if _has_v2(text, ["عنوان", "عنوانه", "فين", "فينه", "فينها", "مكانه", "مكانها", "لوكيشن", "موقع", "map", "اروح"]):
3538
+ addr = place.get("address", "") or place.get("location", "")
3539
+ lat = place.get("lat") or place.get("latitude")
3540
+ lon = place.get("lon") or place.get("lng") or place.get("longitude")
3541
+ parts = [f"📍 {addr}" if addr and str(addr).strip().lower() not in ("", "nan", "none") else "العنوان غير متاح."]
3542
+ if lat and lon:
3543
+ parts.append(f"🗺️ https://maps.google.com/?q={lat},{lon}")
3544
+ return "\n".join(parts)
3545
+ if _has_v2(text, ["تقييم", "نجمة", "نجمه", "rating"]):
3546
+ return fmt_rating(place.get("rating_norm", place.get("rating", 0))) or "مش عندنا تقييم لهذا المكان."
3547
+ return build_response(place, "place_details", category=place.get("category"), total_results=1)
3548
 
3549
+
3550
+ def _extract_place_name_v2(text: str, category: str | None, location: str | None) -> str | None:
3551
+ # only for explicit place lookup, not item/mood/open/ranking queries
3552
+ if _is_real_item_query_v2(text) or _has_v2(text, _RANK_WORDS_V2) or _has_v2(text, _NEAR_WORDS_V2) or _has_v2(text, _OPEN_WORDS_V2):
3553
  return None
3554
+ cand = _strip_known_parts_v2(text, category, location)
3555
+ if not cand or len(cand) < 2:
3556
  return None
3557
+ # if candidate is a known food/drink, it is not a place name
3558
+ if _has_v2(cand, _FOOD_HINTS_V2 | _DRINK_HINTS_V2):
3559
  return None
3560
+ return cand
3561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3562
 
3563
+ def smart_no_result(intent, category=None, location=None, place_name=None, open_now_only=False): # noqa: F811
3564
+ cat_ar = _CAT_AR.get((category or "").lower(), "أماكن")
3565
+ cat_single = _CAT_SINGLE.get((category or "").lower(), "مكان")
3566
  if place_name:
3567
+ return f"مش لاقي {cat_single} باسم *{place_name}* حاليًا 😔\nممكن تكتبه بطريقة تانية؟"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3568
  if location:
3569
+ return f"مفيش {cat_ar} متاحة حاليًا في {location} 😔\nجرب منطقة تانية."
3570
+ if open_now_only:
3571
+ return f"مش لاقي {cat_ar} مفتوحة دلوقتي 😔"
3572
+ if category:
3573
+ return f"مش لاقي {cat_ar} مناسبة حاليًا 😔"
3574
+ return "مش لاقي نتيجة مناسبة حاليًا 😔"
3575
 
 
 
 
 
3576
 
3577
+ def _rank_postprocess_v2(rows: list[dict], text: str) -> list[dict]:
3578
+ if not rows:
3579
+ return rows
3580
+ if _has_v2(text, _RANK_WORDS_V2):
3581
+ rows = sorted(rows, key=lambda p: normalize_rating(p.get("rating_norm", p.get("rating", 0))), reverse=True)
3582
+ if _has_v2(text, _NEAR_WORDS_V2):
3583
+ rows = sorted(rows, key=lambda p: float(p.get("distance_km") if p.get("distance_km") is not None else 999999))
3584
+ return rows
3585
+
3586
+
3587
+ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
3588
+ result = dict(reply="", intent="", confidence=1.0, entities={}, best_place=None, all_results=[])
3589
+ if not text or not text.strip():
3590
+ result.update(reply="اكتب سؤالك 😊", intent="fallback")
3591
+ return result
3592
+
 
 
 
 
3593
  if is_out_of_scope(text):
3594
+ reply = "أنا متخصص في أماكن بني سويف: مطاعم، كافيهات، صيدليات، ماركت، وسكن. 😊"
3595
+ result.update(reply=reply, intent="out_of_scope", confidence=1.0)
3596
  session.add(text, reply, "out_of_scope", {}, None, [])
3597
+ return result
3598
 
3599
+ # Static intents
3600
+ ov = apply_keyword_override(text)
3601
+ if ov in STATIC_INTENTS:
3602
+ reply = random.choice(RESPONSE_TEMPLATES[get_template_key(ov)])
3603
+ result.update(reply=reply, intent=ov, confidence=1.0)
3604
+ session.add(text, reply, ov, {}, None, [])
3605
+ return result
3606
 
3607
+ # Detail follow-up must use last_place.
3608
+ if detect_ref_type(text) == "detail" and session.last_place:
3609
+ reply = handle_detail(text, session.last_place)
3610
+ result.update(reply=reply, intent="detail", best_place=session.last_place, all_results=[session.last_place])
3611
+ session.add(text, reply, "detail", {}, session.last_place, [session.last_place])
3612
+ return result
3613
+
3614
+ if detect_ref_type(text) == "detail" and not session.last_place:
3615
+ reply = "تقصد أنهي مكان؟ اكتب اسم المكان الأول. 😊"
3616
+ result.update(reply=reply, intent="missing_info")
3617
+ session.add(text, reply, "missing_info", {}, None, [])
3618
+ return result
3619
+
3620
+ # Compare previous result cards only when no new category/item is requested.
3621
+ cmp_kind = _detect_compare_intent(text)
3622
+ if cmp_kind and session.last_results:
3623
+ rows = _rank_postprocess_v2(list(session.last_results), text)
3624
+ best = rows[0]
3625
+ reply = f"🏆 أحسن اختيار: *{best.get('name','')}* — تقييمه {normalize_rating(best.get('rating_norm', best.get('rating', 0)))} ⭐"
3626
+ result.update(reply=reply, intent="compare_results", best_place=best, all_results=rows)
3627
+ session.add(text, reply, "compare_results", {}, best, rows)
3628
+ return result
3629
+
3630
+ category = infer_category(text)
3631
+ location = _extract_location_v2(text)
3632
+ open_only = _has_v2(text, _OPEN_WORDS_V2)
3633
+ is_near = _has_v2(text, _NEAR_WORDS_V2)
3634
+ is_best = _has_v2(text, _RANK_WORDS_V2)
3635
+
3636
+ # mood/study/work -> cafe
3637
+ if not category and _has_v2(text, ["اذاكر", "أذاكر", "مذاكرة", "مذاكره", "اشتغل", "شغل", "لابتوب", "هادي", "هادى", "اقعد"]):
3638
+ category = "cafe"
3639
+
3640
+ # dinner/hungry -> restaurant
3641
+ if not category and _has_v2(text, ["اتعشى", "أتعشى", "عشا", "جعان", "جعانة", "اكل", "أكل", "حاجة تتاكل", "حاجه تتاكل"]):
3642
+ category = "restaurant"
3643
+
3644
+ # drug/medicine -> pharmacy
3645
+ if not category and _has_v2(text, ["دوا", "دواء", "علاج", "ادويه", "ادوية"]):
3646
+ category = "pharmacy"
3647
+
3648
+ intent_map = {"restaurant":"nearest_restaurant", "pharmacy":"nearest_pharmacy", "cafe":"nearest_cafe", "supermarket":"nearest_supermarket", "housing":"housing_search"}
3649
  intent = intent_map.get(category, "recommend_place")
3650
 
3651
+ # New category clears old context.
3652
+ old_cat = normalize_category(session.context_slots.get("category")) if getattr(session, "context_slots", None) else None
3653
+ if category and old_cat and normalize_category(category) != old_cat:
3654
+ session.context_slots = {}
3655
  session.last_place = None
3656
  session.last_results = []
 
 
 
 
 
 
 
3657
 
3658
+ place_name = _extract_place_name_v2(text, category, location)
 
 
 
3659
 
3660
+ # no clear category and not place name -> missing/fallback
3661
+ if not category and not place_name:
3662
+ reply = "بتدور على إيه بالظبط؟ مطعم، كافيه، صيدلية، ماركت، أو سكن؟ 😊"
3663
+ result.update(reply=reply, intent="missing_info")
3664
  session.add(text, reply, "missing_info", {}, None, [])
3665
+ return result
3666
+
3667
+ rows_df = search_places(
3668
+ text,
3669
+ top_k_final=5,
3670
+ category=category,
3671
+ location=location,
3672
+ open_now_only=False, # filter open manually below to avoid silent fallback
3673
+ user_lat=user_lat,
3674
+ user_lon=user_lon,
3675
+ intent=intent,
3676
+ place_name=place_name,
3677
+ )
3678
+
3679
+ if rows_df is None or rows_df.empty:
3680
+ reply = smart_no_result(intent, category=category, location=location, place_name=place_name, open_now_only=open_only)
3681
+ result.update(reply=reply, intent="no_result", entities={"category": category, "location": location, "place_name": place_name})
3682
+ session.add(text, reply, "no_result", result["entities"], None, [])
3683
+ return result
3684
+
3685
+ rows = rows_df.to_dict(orient="records")
3686
+
3687
+ # strict open-now handling
3688
+ if open_only:
3689
+ opened = []
3690
+ closed_or_unknown = []
3691
+ for p in rows:
3692
+ p["open_now"] = check_open_now(p.get("opening_hours", ""))
3693
+ if p["open_now"] == 1:
3694
+ opened.append(p)
3695
+ else:
3696
+ closed_or_unknown.append(p)
3697
+ if opened:
3698
+ rows = opened
3699
+ else:
3700
+ reply = smart_no_result(intent, category=category, location=location, open_now_only=True)
3701
+ result.update(reply=reply, intent="no_result", entities={"category": category, "location": location})
3702
+ session.add(text, reply, "no_result", result["entities"], None, [])
3703
+ return result
3704
+
3705
+ rows = _rank_postprocess_v2(rows, text)
3706
+ best = rows[0]
3707
+
3708
+ if open_only:
3709
+ reply = _format_open_status_v2(best)
3710
+ elif is_near and user_lat is not None and user_lon is not None:
3711
+ d = best.get("distance_km")
3712
+ reply = f"📍 الأقرب ليك: *{best.get('name','')}*" + (f" — {float(d):.1f} كم" if d is not None else "")
3713
+ elif is_best:
3714
+ reply = f"🏆 أحسن اختيار: *{best.get('name','')}* — تقييمه {normalize_rating(best.get('rating_norm', best.get('rating', 0)))} ⭐"
3715
+ elif len(rows) > 1:
3716
+ reply = f"👇 دي {len(rows)} نتايج مناسبة لطلبك"
3717
+ else:
3718
+ reply = build_response(best, intent, category=category, total_results=1)
3719
+
3720
+ ents = {"category": category, "location": location, "place_name": place_name}
3721
+ result.update(reply=reply, intent=intent, confidence=1.0, entities={k:v for k,v in ents.items() if v}, best_place=best, all_results=rows)
3722
+ session.add(text, reply, intent, result["entities"], best, rows)
3723
+ return result