Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 3360 |
-
|
| 3361 |
-
|
|
|
|
|
|
|
|
|
|
| 3362 |
|
| 3363 |
-
|
| 3364 |
-
"شاورما","برجر","بيتزا","كريب","
|
| 3365 |
-
"سمك","سندوتش","ساندوتش","حواوشي","كشري","مكرونه","مكرونة","فتة","فته","طعمية","فول",
|
| 3366 |
-
"اكل","اكلة","وجبة","وجبه","غدا","غداء","عشا","عشاء","burger","pizza","shawarma","crepe"
|
| 3367 |
}
|
| 3368 |
-
|
| 3369 |
-
"قهو
|
| 3370 |
-
"اسموزي","سموزي","سموذي","موهيتو","ساقعه","ساقعة","مانجو","خوخ","smoothie","juice","coffee"
|
| 3371 |
}
|
| 3372 |
-
|
| 3373 |
-
|
| 3374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 3396 |
-
|
| 3397 |
-
|
|
|
|
| 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
|
| 3407 |
t = norm(text)
|
| 3408 |
-
|
| 3409 |
-
|
| 3410 |
-
|
| 3411 |
-
|
| 3412 |
-
|
| 3413 |
-
|
| 3414 |
-
|
| 3415 |
-
|
| 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
|
| 3427 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3428 |
|
| 3429 |
-
def _is_nearest_final(text: str) -> bool:
|
| 3430 |
-
return _is_proximity_query(text)
|
| 3431 |
|
| 3432 |
-
def
|
| 3433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3434 |
|
| 3435 |
-
def _is_menu_followup_final(text: str) -> bool:
|
| 3436 |
-
return _contains_any_final(text, _MENU_FOLLOWUP_FINAL)
|
| 3437 |
|
| 3438 |
-
def
|
| 3439 |
-
|
| 3440 |
-
|
| 3441 |
-
|
| 3442 |
-
|
| 3443 |
-
|
| 3444 |
-
|
| 3445 |
-
|
|
|
|
|
|
|
|
|
|
| 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
|
| 3462 |
-
|
| 3463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3464 |
|
| 3465 |
-
|
| 3466 |
-
|
| 3467 |
-
|
| 3468 |
-
|
| 3469 |
-
|
| 3470 |
-
|
| 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
|
| 3476 |
return False
|
| 3477 |
-
if
|
| 3478 |
return False
|
| 3479 |
-
|
| 3480 |
-
|
| 3481 |
-
|
| 3482 |
-
|
| 3483 |
-
|
| 3484 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 3503 |
-
|
| 3504 |
-
|
|
|
|
| 3505 |
return "show_menu"
|
| 3506 |
-
if
|
| 3507 |
return "search_by_item"
|
| 3508 |
return None
|
| 3509 |
|
| 3510 |
-
|
|
|
|
|
|
|
|
|
|
| 3511 |
t = norm(text)
|
| 3512 |
-
|
| 3513 |
-
|
| 3514 |
-
|
| 3515 |
-
if
|
| 3516 |
-
|
| 3517 |
-
|
| 3518 |
-
|
| 3519 |
-
|
| 3520 |
-
|
| 3521 |
-
|
| 3522 |
-
|
| 3523 |
-
|
| 3524 |
-
|
| 3525 |
-
|
| 3526 |
-
|
| 3527 |
-
|
| 3528 |
-
|
| 3529 |
-
|
| 3530 |
-
|
| 3531 |
-
|
| 3532 |
-
|
| 3533 |
-
|
| 3534 |
-
|
| 3535 |
-
|
| 3536 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3537 |
|
| 3538 |
-
|
| 3539 |
-
|
| 3540 |
-
|
|
|
|
| 3541 |
return None
|
| 3542 |
-
|
| 3543 |
-
if not
|
| 3544 |
return None
|
| 3545 |
-
#
|
| 3546 |
-
if
|
| 3547 |
return None
|
| 3548 |
-
return
|
| 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
|
| 3623 |
-
|
| 3624 |
-
|
| 3625 |
if place_name:
|
| 3626 |
-
|
| 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 |
-
|
| 3680 |
-
|
| 3681 |
-
|
| 3682 |
-
if
|
| 3683 |
-
|
| 3684 |
-
return
|
| 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 |
-
|
| 3692 |
-
|
| 3693 |
-
|
| 3694 |
-
|
| 3695 |
-
|
| 3696 |
-
|
| 3697 |
-
|
| 3698 |
-
|
| 3699 |
-
|
| 3700 |
-
|
| 3701 |
-
|
| 3702 |
-
|
| 3703 |
-
|
| 3704 |
-
|
| 3705 |
-
|
| 3706 |
-
|
| 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
|
| 3715 |
|
| 3716 |
-
#
|
| 3717 |
-
|
| 3718 |
-
|
| 3719 |
-
|
| 3720 |
-
|
|
|
|
|
|
|
| 3721 |
|
| 3722 |
-
#
|
| 3723 |
-
if
|
| 3724 |
-
|
| 3725 |
-
|
| 3726 |
-
|
| 3727 |
-
|
| 3728 |
-
|
| 3729 |
-
|
| 3730 |
-
|
| 3731 |
-
|
| 3732 |
-
|
| 3733 |
-
|
| 3734 |
-
|
| 3735 |
-
|
| 3736 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3737 |
intent = intent_map.get(category, "recommend_place")
|
| 3738 |
|
| 3739 |
-
#
|
| 3740 |
-
old_cat = session.context_slots.get("category") if
|
| 3741 |
-
if category and old_cat and normalize_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 |
-
|
| 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 |
-
#
|
| 3758 |
-
if not category and
|
| 3759 |
-
reply = "ت
|
|
|
|
| 3760 |
session.add(text, reply, "missing_info", {}, None, [])
|
| 3761 |
-
return
|
| 3762 |
-
|
| 3763 |
-
|
| 3764 |
-
|
| 3765 |
-
|
| 3766 |
-
|
| 3767 |
-
|
| 3768 |
-
|
| 3769 |
-
|
| 3770 |
-
|
| 3771 |
-
|
| 3772 |
-
|
| 3773 |
-
|
| 3774 |
-
|
| 3775 |
-
|
| 3776 |
-
|
| 3777 |
-
|
| 3778 |
-
session.
|
| 3779 |
-
|
| 3780 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|