Youmnaaaa commited on
Commit
869eaaf
ยท
verified ยท
1 Parent(s): 8ccb441

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -16
app.py CHANGED
@@ -1109,23 +1109,23 @@ def search_places(query, top_k_final=5, category=None, sub_category=None,
1109
 
1110
  RESPONSE_TEMPLATES = {
1111
  "find_restaurant": [
1112
- "๐Ÿฝ๏ธ ู„ู‚ูŠุชู„ูƒ {name} ููŠ {location}. {rating_info}{hours_info}",
1113
- "ุฃู†ุตุญูƒ ุจู€ {name} โ€” ู‡ุชู„ุงู‚ูŠู‡ ููŠ {location}. {rating_info}{hours_info}",
1114
- "ููŠ {location} ููŠู‡ {name}. {description_short}{hours_info}",
1115
- "ุฏูˆุฑ ุนู„ู‰ {name} ููŠ {location}. {rating_info}{hours_info}",
1116
- "ู…ู…ูƒู† ุชุฌุฑุจ {name} โ€” {location}. {description_short}{hours_info}",
1117
  ],
1118
  "find_pharmacy": [
1119
- "๐Ÿ’Š {name} ููŠ {location}.{hours_info}{rating_info}",
1120
- "ุฃู‚ุฑุจ ุตูŠุฏู„ูŠุฉ ู„ูŠูƒ: {name} โ€” {address_info}{hours_info}",
1121
- "ุตูŠุฏู„ูŠุฉ {name} ููŠ {location}. {hours_info}",
1122
- "ู„ุงู‚ูŠุชู„ูƒ {name} โ€” {address_info}{hours_info}",
1123
  ],
1124
  "find_cafe": [
1125
- "โ˜• ุฌุฑุจ {name} ููŠ {location}. {rating_info}{hours_info}",
1126
- "ููŠู‡ {name} โ€” ููŠ {location}. {description_short}{hours_info}",
1127
- "ุฃู†ุตุญูƒ ุจู€ {name} ููŠ {location}. {rating_info}",
1128
- "โ˜• {name} ููŠ {location} โ€” {description_short}{hours_info}",
1129
  ],
1130
  "find_supermarket": [
1131
  "๐Ÿ›’ *{name}* ููŠ {location}.{hours_info}{rating_info}",
@@ -4463,7 +4463,7 @@ def handle_show_menu(text: str, session, entities: dict) -> dict: # noqa: F811
4463
  if hits:
4464
  place = hits[0]
4465
  else:
4466
- result = {"reply": f"ู…ุด ู„ุงู‚ูŠ ู…ูƒุงู† ุจุงุณู… *{place_name}* ุญุงู„ูŠู‹ุง ", "intent": "show_menu", "ui_type": CFG.UI_TEXT_ONLY, "menu_items": [], "best_place": None}
4467
  session.add(text, result["reply"], "show_menu", {"place_name": place_name}, None, [])
4468
  return result
4469
  if place is None and not explicit_name and session.last_place:
@@ -4541,7 +4541,7 @@ def _handle_compare_hotfix(text: str, session, user_lat=None, user_lon=None) ->
4541
  if pid not in seen:
4542
  seen.add(pid); unique.append(p)
4543
  if len(unique) < 2:
4544
- return {"reply": "ุงูƒุชุจู„ูŠ ุงุณู…ูŠู† ูˆุงุถุญูŠู† ุนุดุงู† ุฃู‚ุงุฑู† ุจูŠู†ู‡ู… ", "intent": "compare_places", "confidence": 1.0, "entities": {"place_names": names}, "best_place": None, "all_results": []}
4545
  unique = _sort_rows_hotfix(unique, text, user_lat, user_lon)
4546
  if any(w in t for w in ["ุงู‚ุฑุจ", "ุฃู‚ุฑุจ"]):
4547
  winner = unique[0]
@@ -4599,7 +4599,7 @@ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
4599
  if opened:
4600
  rows = opened
4601
  elif "ุตูŠุฏู„ูŠ" in t or "pharmacy" in t:
4602
- reply = "ู…ุด ู„ุงู‚ูŠ ุตูŠุฏู„ูŠุงุช ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ "
4603
  res.update({"reply": reply, "intent": "no_result", "best_place": None, "all_results": []})
4604
  return res
4605
 
@@ -4616,3 +4616,181 @@ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
4616
 
4617
  return res
4618
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1109
 
1110
  RESPONSE_TEMPLATES = {
1111
  "find_restaurant": [
1112
+ "๐Ÿฝ๏ธ ู„ู‚ูŠุชู„ูƒ *{name}* ููŠ {location}. {rating_info}{hours_info}",
1113
+ "ุฃู†ุตุญูƒ ุจู€ *{name}* โ€” ู‡ุชู„ุงู‚ูŠู‡ ููŠ {location}. {rating_info}{hours_info}",
1114
+ "ููŠ {location} ููŠู‡ *{name}*. {description_short}{hours_info}",
1115
+ "ุฏูˆุฑ ุนู„ู‰ *{name}* ููŠ {location}. {rating_info}{hours_info}",
1116
+ "ู…ู…ูƒู† ุชุฌุฑุจ *{name}* โ€” {location}. {description_short}{hours_info}",
1117
  ],
1118
  "find_pharmacy": [
1119
+ "๐Ÿ’Š *{name}* ููŠ {location}.{hours_info}{rating_info}",
1120
+ "ุฃู‚ุฑุจ ุตูŠุฏู„ูŠุฉ ู„ูŠูƒ: *{name}* โ€” {address_info}{hours_info}",
1121
+ "ุตูŠุฏู„ูŠุฉ *{name}* ููŠ {location}. {hours_info}",
1122
+ "ู„ุงู‚ูŠุชู„ูƒ *{name}* โ€” {address_info}{hours_info}",
1123
  ],
1124
  "find_cafe": [
1125
+ "โ˜• ุฌุฑุจ *{name}* ููŠ {location}. {rating_info}{hours_info}",
1126
+ "ููŠู‡ *{name}* โ€” ููŠ {location}. {description_short}{hours_info}",
1127
+ "ุฃู†ุตุญูƒ ุจู€ *{name}* ููŠ {location}. {rating_info}",
1128
+ "โ˜• *{name}* ููŠ {location} โ€” {description_short}{hours_info}",
1129
  ],
1130
  "find_supermarket": [
1131
  "๐Ÿ›’ *{name}* ููŠ {location}.{hours_info}{rating_info}",
 
4463
  if hits:
4464
  place = hits[0]
4465
  else:
4466
+ result = {"reply": f"ู…ุด ู„ุงู‚ูŠ ู…ูƒุงู† ุจุงุณู… *{place_name}* ุญุงู„ูŠู‹ุง ๐Ÿ˜”", "intent": "show_menu", "ui_type": CFG.UI_TEXT_ONLY, "menu_items": [], "best_place": None}
4467
  session.add(text, result["reply"], "show_menu", {"place_name": place_name}, None, [])
4468
  return result
4469
  if place is None and not explicit_name and session.last_place:
 
4541
  if pid not in seen:
4542
  seen.add(pid); unique.append(p)
4543
  if len(unique) < 2:
4544
+ return {"reply": "ุงูƒุชุจู„ูŠ ุงุณู…ูŠู† ูˆุงุถุญูŠู† ุนุดุงู† ุฃู‚ุงุฑู† ุจูŠู†ู‡ู… ๐Ÿ˜Š", "intent": "compare_places", "confidence": 1.0, "entities": {"place_names": names}, "best_place": None, "all_results": []}
4545
  unique = _sort_rows_hotfix(unique, text, user_lat, user_lon)
4546
  if any(w in t for w in ["ุงู‚ุฑุจ", "ุฃู‚ุฑุจ"]):
4547
  winner = unique[0]
 
4599
  if opened:
4600
  rows = opened
4601
  elif "ุตูŠุฏู„ูŠ" in t or "pharmacy" in t:
4602
+ reply = "ู…ุด ู„ุงู‚ูŠ ุตูŠุฏู„ูŠุงุช ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ ๐Ÿ˜”"
4603
  res.update({"reply": reply, "intent": "no_result", "best_place": None, "all_results": []})
4604
  return res
4605
 
 
4616
 
4617
  return res
4618
 
4619
+
4620
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
4621
+ # ULTIMATE ROUTING PATCH โ€” category/open/best/nearest/menu fixes
4622
+ # Added after all previous definitions so FastAPI uses these globals at call-time.
4623
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
4624
+
4625
+ def _detect_new_intent(text: str) -> str | None: # noqa: F811
4626
+ """Menu words ALWAYS mean show_menu, even when the place name contains food words like Pizza Bike."""
4627
+ if _has_v2(text, _MENU_WORDS_V2) or _final_has_any(text, _MENU_TRIGGERS):
4628
+ return "show_menu"
4629
+ if _is_real_item_query_v2(text) or _looks_like_item_search(text):
4630
+ return "search_by_item"
4631
+ return None
4632
+
4633
+
4634
+ def _is_best_query_final(text: str) -> bool:
4635
+ return _has_v2(text, _RANK_WORDS_V2) or any(w in norm(text) for w in ["ุงุญุณู†", "ุฃุญุณู†", "ุงูุถู„", "ุฃูุถู„", "ุชู‚ูŠูŠู…"])
4636
+
4637
+
4638
+ def _is_nearest_query_final(text: str) -> bool:
4639
+ return _has_v2(text, _NEAR_WORDS_V2) or _is_proximity_query(text)
4640
+
4641
+
4642
+ def _is_open_query_final(text: str) -> bool:
4643
+ return _has_v2(text, _OPEN_WORDS_V2) or any(w in norm(text) for w in ["ู…ูุชูˆุญ", "ู…ูุชูˆุญุฉ", "ู…ูุชูˆุญู‡", "ูุงุชุญ", "ูุงุชุญู‡", "ูุงุชุญุฉ", "ุดุบุงู„", "ุดุบุงู„ู‡", "ุฏู„ูˆู‚ุชูŠ"])
4644
+
4645
+
4646
+ def _category_label_ar_final(cat: str) -> str:
4647
+ return _CAT_AR.get(cat, "ุฃู…ุงูƒู†")
4648
+
4649
+
4650
+ def _category_single_ar_final(cat: str) -> str:
4651
+ return _CAT_SINGLE.get(cat, "ู…ูƒุงู†")
4652
+
4653
+
4654
+ def _all_places_for_category_final(category: str, user_lat=None, user_lon=None) -> list[dict]:
4655
+ if places_df is None or places_df.empty or not category:
4656
+ return []
4657
+ rows = []
4658
+ for _, r in places_df.iterrows():
4659
+ p = r.to_dict()
4660
+ if not _category_match_value(str(p.get("category", "")), category):
4661
+ continue
4662
+ if p.get("open_now") is None:
4663
+ p["open_now"] = check_open_now(p.get("opening_hours", ""))
4664
+ p["rating_norm"] = normalize_rating(p.get("rating_norm", p.get("rating", 0)))
4665
+ if p.get("distance_km") is None and user_lat is not None and user_lon is not None:
4666
+ try:
4667
+ p["distance_km"] = round(haversine(float(user_lat), float(user_lon), float(p.get("lat")), float(p.get("lon", p.get("lng")))), 2)
4668
+ except Exception:
4669
+ p["distance_km"] = None
4670
+ rows.append(p)
4671
+ return rows
4672
+
4673
+
4674
+ def _filter_location_final(rows: list[dict], location: str | None) -> list[dict]:
4675
+ if not location:
4676
+ return rows
4677
+ loc_c = clean_text(location)
4678
+ loc_parts = [x for x in loc_c.split() if len(x) > 1]
4679
+ if not loc_parts:
4680
+ return rows
4681
+ out = []
4682
+ for p in rows:
4683
+ blob = clean_text(f"{p.get('location','')} {p.get('address','')}")
4684
+ if any(part in blob for part in loc_parts):
4685
+ out.append(p)
4686
+ return out
4687
+
4688
+
4689
+ def _sort_category_rows_final(rows: list[dict], text: str) -> list[dict]:
4690
+ rows = [dict(p) for p in (rows or [])]
4691
+ if _is_nearest_query_final(text):
4692
+ return sorted(rows, key=lambda p: (p.get("distance_km") if p.get("distance_km") is not None else 999999, -float(p.get("rating_norm") or p.get("rating") or 0)))
4693
+ if _is_best_query_final(text):
4694
+ return sorted(rows, key=lambda p: (float(p.get("rating_norm") or p.get("rating") or 0), int(p.get("rating_count") or p.get("review_count") or 0), -float(p.get("distance_km") if p.get("distance_km") is not None else 999999)), reverse=True)
4695
+ if _is_open_query_final(text):
4696
+ return sorted(rows, key=lambda p: (0 if p.get("open_now") == 1 else 1, p.get("distance_km") if p.get("distance_km") is not None else 999999, -float(p.get("rating_norm") or p.get("rating") or 0)))
4697
+ return rows
4698
+
4699
+
4700
+ def _deterministic_category_query_final(text: str, session, user_lat=None, user_lon=None) -> dict | None:
4701
+ """Handle explicit category searches before old context/detail logic can steal them."""
4702
+ category = infer_category(text)
4703
+ if not category:
4704
+ return None
4705
+ # Do not steal item/menu queries.
4706
+ if _detect_new_intent(text) in ("search_by_item", "show_menu"):
4707
+ return None
4708
+
4709
+ wants_best = _is_best_query_final(text)
4710
+ wants_near = _is_nearest_query_final(text)
4711
+ wants_open = _is_open_query_final(text)
4712
+
4713
+ # Handle explicit category if it is ranking/open/near or a normal category request.
4714
+ location = _extract_location_v2(text) or _extract_location_from_text(text)
4715
+ rows = _all_places_for_category_final(category, user_lat, user_lon)
4716
+ rows = _filter_location_final(rows, location)
4717
+
4718
+ if wants_open:
4719
+ rows = [p for p in rows if p.get("open_now") == 1 or _final_open_bool(p) is True]
4720
+
4721
+ if not rows:
4722
+ if location:
4723
+ reply = f"ู…ููŠุด {_category_label_ar_final(category)} ู…ุชุงุญุฉ ุญุงู„ูŠู‹ุง ููŠ {location} ๐Ÿ˜”"
4724
+ elif wants_open:
4725
+ reply = f"ู…ุด ู„ุงู‚ูŠ {_category_label_ar_final(category)} ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ ๐Ÿ˜”"
4726
+ else:
4727
+ reply = f"ู…ุด ู„ุงู‚ูŠ {_category_label_ar_final(category)} ู…ู†ุงุณุจุฉ ุญุงู„ูŠู‹ุง ๐Ÿ˜”"
4728
+ result = dict(reply=reply, intent="no_result", confidence=1.0, entities={"category": category, "location": location, "open_now": wants_open}, best_place=None, all_results=[])
4729
+ session.add(text, reply, "no_result", result["entities"], None, [])
4730
+ return result
4731
+
4732
+ rows = _sort_category_rows_final(rows, text)[:CFG.MAX_CARDS]
4733
+ top = rows[0]
4734
+ name = top.get("name", "")
4735
+ dist = top.get("distance_km")
4736
+ rating = normalize_rating(top.get("rating_norm", top.get("rating", 0)))
4737
+
4738
+ if wants_near:
4739
+ reply = f"๐Ÿ“ ุงู„ุฃู‚ุฑุจ ู„ูŠูƒ: *{name}*" + (f" โ€” {dist} ูƒู…" if dist is not None else "")
4740
+ intent = f"nearest_{category}" if category in ("restaurant", "pharmacy", "cafe", "supermarket") else "housing_search"
4741
+ elif wants_best and wants_open:
4742
+ reply = f"๐Ÿ† ุฃุญุณู† {_category_single_ar_final(category)} ู…ูุชูˆุญ ุฏู„ูˆู‚ุชูŠ: *{name}* โ€” ุชู‚ูŠูŠู…ู‡ {rating} โญ"
4743
+ intent = "best_of"
4744
+ elif wants_best:
4745
+ reply = f"๐Ÿ† ุฃุญุณู† ุงุฎุชูŠุงุฑ: *{name}* โ€” ุชู‚ูŠูŠู…ู‡ {rating} โญ"
4746
+ intent = "best_of"
4747
+ elif wants_open:
4748
+ reply = f"๐ŸŸข ู„ู‚ูŠุชู„ูƒ {_category_label_ar_final(category)} ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ ๐Ÿ‘‡"
4749
+ intent = "open_now"
4750
+ else:
4751
+ reply = f"ุฏูŠ {len(rows)} ู†ุชุงุฆุฌ ู…ู†ุงุณุจุฉ ู„ุทู„ุจูƒ ๐Ÿ‘‡"
4752
+ intent = INTENT_TO_CATEGORY.get(category) or {"restaurant":"nearest_restaurant","pharmacy":"nearest_pharmacy","cafe":"nearest_cafe","supermarket":"nearest_supermarket","housing":"housing_search"}.get(category, "recommend_place")
4753
+
4754
+ entities = {"category": category, "location": location, "open_now": wants_open}
4755
+ result = dict(reply=reply, intent=intent, confidence=1.0, entities=entities, best_place=top, all_results=rows)
4756
+ # Reset context because this is an explicit new category request.
4757
+ session.context_slots = {"category": category}
4758
+ if location:
4759
+ session.context_slots["location"] = location
4760
+ session.add(text, reply, intent, entities, top, rows)
4761
+ return result
4762
+
4763
+
4764
+ _prev_chat_after_ultimate_patch = chat
4765
+
4766
+ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
4767
+ # Explicit category queries must be handled before old detail/follow-up context.
4768
+ routed = _deterministic_category_query_final(text, session, user_lat, user_lon)
4769
+ if routed is not None:
4770
+ return routed
4771
+ return _prev_chat_after_ultimate_patch(text, session, user_lat, user_lon)
4772
+
4773
+
4774
+ # Patch endpoint function too: final card sorting must follow the user's wording,
4775
+ # not only the predicted intent (which may be nearest_* for "ุงุญุณู† ู…ุทุนู…").
4776
+ _prev_chat_endpoint_after_ultimate_patch = chat_endpoint
4777
+
4778
+ def _sort_cards_endpoint_final(cards: list[dict], message: str) -> list[dict]:
4779
+ if not cards:
4780
+ return cards
4781
+ if _is_nearest_query_final(message):
4782
+ return sorted(cards, key=lambda p: p.get("distance_km") if p.get("distance_km") is not None else 999999)
4783
+ if _is_best_query_final(message):
4784
+ return sorted(cards, key=lambda p: (float(p.get("rating") or 0), int(p.get("rating_count") or 0), -float(p.get("distance_km") if p.get("distance_km") is not None else 999999)), reverse=True)
4785
+ if _is_open_query_final(message):
4786
+ return sorted(cards, key=lambda p: (0 if p.get("is_open") is True or p.get("open_now") == 1 else 1, p.get("distance_km") if p.get("distance_km") is not None else 999999))
4787
+ return cards
4788
+
4789
+ # We cannot easily wrap the decorated route response without redecorating; instead
4790
+ # patch make_chat_response so every endpoint return gets a final deterministic card order.
4791
+ _prev_make_chat_response_after_ultimate_patch = make_chat_response
4792
+
4793
+ def make_chat_response(*args, **kwargs): # noqa: F811
4794
+ # message is not passed to make_chat_response, so endpoint-level sorting is handled
4795
+ # by chat() all_results order. Keep this wrapper only for backward compatibility.
4796
+ return _prev_make_chat_response_after_ultimate_patch(*args, **kwargs)