Youmnaaaa commited on
Commit
d8a388e
ยท
verified ยท
1 Parent(s): 1f601cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -247
app.py CHANGED
@@ -1819,220 +1819,90 @@ def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
1819
  session.add(text, reply, result_intent, entities, best, results)
1820
  return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results}
1821
  # =========================
1822
-
1823
- # =========================
1824
- # FINAL STABILITY PATCH (V22)
1825
  # =========================
1826
- # This patch removes the stacked V16/V19/V20/V21 overrides and keeps the
1827
- # original stable pipeline, then fixes only the real regressions seen in app tests:
1828
- # - greetings before any name search (ู‡ุงูŠ / ุงู„ุณู„ุงู… ุนู„ูŠูƒู…)
1829
- # - pharmacy/category words must not become ITEM_QUERY conflicts
1830
- # - safer phonetic place-name search without forcing false category context
1831
-
1832
- ISLAMIC_GREETING_REPLY = "ูˆุนู„ูŠูƒู… ุงู„ุณู„ุงู… ูˆุฑุญู…ุฉ ุงู„ู„ู‡ ูˆุจุฑูƒุงุชู‡ ๐ŸŒน\nุฃู‡ู„ุงู‹ ุจูŠูƒุŒ ู…ุญุชุงุฌ ุฅูŠู‡ ููŠ ุจู†ูŠ ุณูˆูŠูุŸ ู…ุทุนู…ุŒ ูƒุงููŠู‡ุŒ ุตูŠุฏู„ูŠุฉุŒ ู…ุงุฑูƒุช ุฃูˆ ุณูƒู†ุŸ"
1833
-
1834
- STRICT_GREETING_WORDS = {
1835
- "ุงู„ุณู„ุงู… ุนู„ูŠูƒู…", "ุณู„ุงู… ุนู„ูŠูƒู…", "ุงู„ุณู„ู… ุนู„ูŠูƒู…", "ุณู„ุงู…ูˆ ุนู„ูŠูƒู…",
1836
- "ู‡ุงูŠ", "ู‡ุงู‰", "hi", "hello", "ู‡ู„ุง", "ุงู‡ู„ุง", "ุงู‡ู„ุงู‹", "ู…ุฑุญุจุง",
1837
- "ุตุจุงุญ ุงู„ุฎูŠุฑ", "ู…ุณุงุก ุงู„ุฎูŠุฑ",
1838
- }
1839
-
1840
-
1841
- def is_islamic_greeting(text: str) -> bool:
1842
- t = norm(text)
1843
- return "ุงู„ุณู„ุงู… ุนู„ูŠูƒู…" in t or "ุณู„ุงู… ุนู„ูŠูƒู…" in t or "ุงู„ุณู„ู… ุนู„ูŠูƒู…" in t or "ุณู„ุงู…ูˆ ุนู„ูŠูƒู…" in t
1844
-
1845
-
1846
- def is_simple_greeting(text: str) -> bool:
1847
- t = norm(text)
1848
- if is_islamic_greeting(text):
1849
- return True
1850
- return t in {norm(x) for x in STRICT_GREETING_WORDS}
1851
-
1852
-
1853
- # Add common Arabic greeting that was not in the original keyword list.
1854
- try:
1855
- KEYWORD_INTENTS["greeting"] = list(dict.fromkeys(KEYWORD_INTENTS.get("greeting", []) + ["ู‡ุงูŠ", "ู‡ุงู‰"]))
1856
- except Exception:
1857
- pass
1858
-
1859
-
1860
- # ---------- safer item/category handling ----------
1861
- GENERIC_CATEGORY_WORDS = {
1862
- clean_text(x) for x in [
1863
- "ู…ุทุนู…", "ู…ุทุงุนู…", "ุงูƒู„", "ุฃูƒู„", "ูˆุฌุจุงุช", "ูˆุฌุจุฉ",
1864
- "ูƒุงููŠู‡", "ูƒุงููŠู‡ุงุช", "ูƒุงููŠุฉ", "ูƒูˆููŠ", "ู‚ู‡ูˆู‡", "ู‚ู‡ูˆุฉ",
1865
- "ุตูŠุฏู„ูŠู‡", "ุตูŠุฏู„ูŠุฉ", "ุตูŠุฏู„ูŠุงุช", "ุตูŠุฏู„ู‡", "ุตุฏูŠู„ูŠู‡",
1866
- "ู…ุงุฑูƒุช", "ุณูˆุจุฑ", "ุณูˆุจุฑู…ุงุฑูƒุช", "ุณูˆุจุฑ ู…ุงุฑูƒุช", "ู‡ุงูŠุจุฑ",
1867
- "ุณูƒู†", "ุดู‚ุฉ", "ุดู‚ู‡", "ูู†ุฏู‚",
1868
- ]
1869
- }
1870
-
1871
- ITEM_SYNONYMS = {
1872
- "ุงูŠุณูƒูˆูู‰": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณูƒูˆููŠ": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒูˆูู‰": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒูˆููŠ": "ุงูŠุณ ูƒูˆููŠ",
1873
- "ุงูŠุณ ูƒุงููŠ": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒุงููŠู‡": "ุงูŠุณ ูƒูˆููŠ", "ice coffee": "ุงูŠุณ ูƒูˆููŠ", "iced coffee": "ุงูŠุณ ูƒูˆููŠ",
1874
- "ุงูŠุณ ูƒุฑูŠู…": "ุงูŠุณ ูƒุฑูŠู…", "ุงูŠุณูƒุฑูŠู…": "ุงูŠุณ ูƒุฑูŠู…", "ุขูŠุณ ูƒุฑูŠู…": "ุงูŠุณ ูƒุฑูŠู…",
1875
- "ุฏูˆุง": "ุฏูˆุงุก", "ุฏูˆุงุก": "ุฏูˆุงุก", "ุนู„ุงุฌ": "ุฏูˆุงุก", "ุงุฏูˆูŠู‡": "ุฏูˆุงุก", "ุงุฏูˆูŠุฉ": "ุฏูˆุงุก", "ุฃุฏูˆูŠุฉ": "ุฏูˆุงุก",
1876
- "ุดูŠุจุณู‰": "ุดูŠุจุณูŠ", "ุดูŠุจุตูŠ": "ุดูŠุจุณูŠ", "ุดูŠุจุณูŠ": "ุดูŠุจุณูŠ",
1877
- "ุจูŠุจุณู‰": "ุจูŠุจุณูŠ", "ุจูŠุจุตูŠ": "ุจูŠุจุณูŠ", "ุจูŠุจุณูŠ": "ุจูŠุจุณูŠ",
1878
- "ุดูˆุฑู…ุง": "ุดุงูˆุฑู…ุง", "ุดุงูˆุฑู…ู‡": "ุดุงูˆุฑู…ุง", "ุจุชุฒุง": "ุจูŠุชุฒุง", "ุจูŠุชุฒุงุง": "ุจูŠุชุฒุง",
1879
- "ู…ูƒุณ ู„ุญูˆู…": "ู…ูŠูƒุณ ู„ุญูˆู…", "ู…ูŠูƒุณ ู„ุญูˆู…": "ู…ูŠูƒุณ ู„ุญูˆู…",
1880
- }
1881
-
1882
-
1883
- def normalize_item_query(item: str) -> str:
1884
- q = clean_text(item)
1885
- if not q:
1886
- return ""
1887
- q_no = q.replace(" ", "")
1888
- return ITEM_SYNONYMS.get(q, ITEM_SYNONYMS.get(q_no, q))
1889
 
1890
-
1891
- _old_extract_item_query_stable = extract_item_query
1892
-
1893
- def extract_item_query(text: str) -> str:
1894
- t = clean_text(text)
1895
- # Generic category words should never become a menu/product item.
1896
- if t in GENERIC_CATEGORY_WORDS:
1897
- return ""
1898
- t_no = t.replace(" ", "")
1899
- for raw, canonical in ITEM_SYNONYMS.items():
1900
- raw_clean = clean_text(raw)
1901
- if raw_clean and (re.search(rf"\b{re.escape(raw_clean)}\b", t) or raw_clean.replace(" ", "") in t_no):
1902
- return canonical
1903
- item = _old_extract_item_query_stable(text)
1904
- item = normalize_item_query(item)
1905
- if clean_text(item) in GENERIC_CATEGORY_WORDS:
1906
- return ""
1907
- return item
1908
-
1909
-
1910
- def intended_item_category(item_query: str) -> str:
1911
- q = normalize_item_query(item_query)
1912
- if not q:
1913
- return ""
1914
- if q in GENERIC_CATEGORY_WORDS:
1915
- return ""
1916
- if any(x in q for x in ["ุฏูˆุงุก", "ุนู„ุงุฌ", "ู…ุณูƒู†", "ู…ุฑู‡ู…", "ููŠุชุงู…ูŠู†"]):
1917
- return "pharmacy"
1918
- if any(x in q for x in ["ุดูŠุจุณูŠ", "ุจูŠุจุณูŠ", "ุณู†ุงูƒุณ", "ู…ูŠุงู‡", "ู„ุจู†", "ุนูŠุด", "ุณูƒุฑ", "ุฑุฒ", "ุดูˆูƒูˆู„ุงุชู‡", "ุจุณูƒูˆุช"]):
1919
- return "supermarket"
1920
- if any(x in q for x in ["ู‚ู‡ูˆุฉ", "ู‚ู‡ูˆู‡", "ู„ุงุชูŠู‡", "ูƒุงุจุชุดูŠู†ูˆ", "ุงุณุจุฑูŠุณูˆ", "ู…ูˆูƒุง", "ู†ุณูƒุงููŠู‡", "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ู„ุงุชูŠู‡", "ุดุงูŠ", "ู…ุดุฑูˆุจุงุช", "ุงูŠุณ ูƒุฑูŠู…", "ูˆุงูู„", "ุญู„ูˆูŠุงุช"]):
1921
- return "cafe"
1922
- if any(x in q for x in ["ุจุฑุฌุฑ", "ุจูŠุชุฒุง", "ุดุงูˆุฑู…ุง", "ูƒุฑูŠุจ", "ู…ุดูˆูŠุงุช", "ูƒุจุงุจ", "ูƒูุชู‡", "ูƒูุชุฉ", "ูุฑุงุฎ", "ู†ุต ูุฑุงุฎ", "ููˆู„", "ุทุนู…ูŠุฉ", "ุณู…ูƒ", "ูƒุดุฑูŠ", "ุญูˆุงูˆุดูŠ", "ูุทูŠุฑ", "ู…ูŠูƒุณ ู„ุญูˆู…", "ู„ุญูˆู…"]):
1923
- return "restaurant"
1924
- return ""
1925
-
1926
-
1927
- def item_category_conflict(item_query: str, category: str) -> Optional[str]:
1928
- intended = intended_item_category(item_query)
1929
- category = normalize_category(category)
1930
- # Unknown item should not create a fake restaurant conflict.
1931
- if intended and category and intended != category:
1932
- # Cafe items can exist in mixed restaurant/cafe places and even restaurant menus.
1933
- if intended == "cafe" and category in {"restaurant", "restaurant_cafe", "cafe"}:
1934
- return None
1935
- return intended
1936
- return None
1937
-
1938
-
1939
- # ---------- safer place name matching ----------
1940
  VOWELS_LATIN = set("aeiouy")
1941
 
1942
- PLACE_WORD_TRANSLATIONS = {
1943
- "ุงู†ุฏ": "and", "ุงู†": "and", "ุงู†ุฏุฏ": "and", "ุงู†ุฏู‰": "and", "ุงู†ุฏูˆ": "and",
1944
- "ุฐุง": "the", "ุฏูŠ": "d",
1945
- "ูƒุงููŠู‡": "cafe", "ูƒุงููŠ": "cafe", "ูƒุงูู‰": "cafe", "ูƒูˆููŠ": "coffee", "ูƒูˆูู‰": "coffee",
1946
- "ู…ุทุนู…": "restaurant", "ุฑูŠุณุชูˆุฑุงู†ุช": "restaurant", "ู…ุงุฑูƒุช": "market", "ู‡ุงูŠุจุฑ": "hyper", "ู…ูˆู„": "mall",
1947
- "ุจุงุจู„ูƒ": "public", "ุจูˆุจู„ูƒ": "public", "ุจุจู„ูƒ": "public", "ุจุงุจู„ูŠูƒ": "public",
1948
- "ุฌุฑุงู†ุฏ": "grand", "ุฑูˆูŠุงู„": "royal", "ูƒูŠู†ุฌ": "king", "ูƒูˆูŠู†": "queen", "ูุงู…ูŠู„ูŠ": "family", "ูุงู…ูŠู„ู‰": "family",
1949
- "ุณุชุงุฑ": "star", "ุณุชุงุฑุฒ": "stars", "ุณู†ุชุฑ": "center", "ุณูŠู†ุชุฑ": "center", "ุณูŠุชูŠ": "city", "ุณูŠุชู‰": "city",
1950
- "ุดูˆุจ": "shop", "ุณุชูˆุฑ": "store", "ู‡ุงูˆุณ": "house", "ู‡ูˆู…": "home", "ูƒูˆุฑู†ุฑ": "corner",
1951
- "ุจูŠุชุฒุง": "pizza", "ุจุงูŠูƒ": "bike", "ุจุฑุฌุฑ": "burger", "ุชุดูƒู†": "chicken", "ูุฑุงูŠุฏ": "fried",
1952
- "ุจุงููŠ": "puffy", "ุจูˆููŠ": "puffy", "ูู„ุงููŠ": "fluffy", "ูู„ุงูู‰": "fluffy",
1953
- }
1954
-
1955
-
1956
- def ar_to_latin_guess(text: Any) -> str:
1957
- src = clean_text(text)
1958
- if not src:
1959
- return ""
1960
- if re.search(r"[a-zA-Z]", str(text or "")):
1961
- return src.replace("&", " and ").replace("+", " and ")
1962
- words = [PLACE_WORD_TRANSLATIONS.get(w, w) for w in src.split()]
1963
- src = " ".join(words)
1964
- pairs = {"ุด": "sh", "ุฎ": "kh", "ุบ": "gh", "ุซ": "th", "ุฐ": "z", "ุต": "s", "ุถ": "d", "ุท": "t", "ุธ": "z"}
1965
- single = {"ุง": "a", "ุจ": "b", "ุช": "t", "ุฌ": "g", "ุญ": "h", "ุฏ": "d", "ุฑ": "r", "ุฒ": "z", "ุณ": "s", "ุน": "a", "ู": "f", "ู‚": "q", "ูƒ": "k", "ู„": "l", "ู…": "m", "ู†": "n", "ู‡": "h", "ูˆ": "o", "ูŠ": "i", "ู‰": "i", "ุก": "", " ": " "}
1966
- out = []
1967
- for ch in src:
1968
- out.append(pairs.get(ch, single.get(ch, ch)))
1969
- guessed = re.sub(r"\s+", " ", "".join(out)).strip()
1970
- manual = {
1971
- "lamira": "lamera", "la mira": "lamera", "bolifar": "bolivar boulevard", "bolivard": "boulevard",
1972
- "sn shain": "sunshine", "sun shain": "sunshine", "san shain": "sunshine",
1973
- "aon bablk": "on public", "on bablk": "on public", "aon bablik": "on public", "on bablik": "on public",
1974
- "sanhok": "sanhok", "san hok": "sanhok", "bitza baik": "pizza bike", "pizza baik": "pizza bike",
1975
- "bafi and flafi": "puffy fluffy", "bafy and flafy": "puffy fluffy", "bafi flafi": "puffy fluffy",
1976
- }
1977
- return manual.get(guessed, guessed)
1978
-
1979
-
1980
  def _compact_key(text: Any) -> str:
1981
  return re.sub(r"\s+", "", clean_text(text))
1982
 
1983
-
1984
  def _phonetic_key(text: Any) -> str:
1985
- latin = ar_to_latin_guess(text) or clean_text(text)
1986
- latin = latin.lower().replace("&", " and ").replace("+", " and ").replace("cafe", "kafe")
 
 
1987
  latin = re.sub(r"\b(and|n|the|el|al)\b", " ", latin)
1988
  latin = re.sub(r"[^a-z0-9]+", "", latin)
1989
  latin = latin.replace("kh", "x").replace("sh", "s")
1990
  latin = latin.replace("ph", "f").replace("ck", "k").replace("c", "k").replace("q", "k")
 
 
 
1991
  latin = latin.replace("p", "b").replace("v", "f").replace("j", "g")
1992
  latin = latin.replace("x", "ks")
1993
  latin = "".join(ch for ch in latin if ch not in VOWELS_LATIN)
1994
  latin = re.sub(r"(.)\1+", r"\1", latin)
1995
  return latin
1996
 
1997
-
1998
  def _place_name_blob(row) -> str:
1999
- return clean_text(" ".join([str(row.get("name", "")), str(row.get("name_ar", "")), str(row.get("name_en", ""))]))
2000
-
 
 
 
 
 
 
2001
 
2002
  def expand_place_name_queries(place_name: str) -> list:
2003
  q = clean_text(place_name)
2004
  q_latin = ar_to_latin_guess(place_name)
2005
- queries = [q, q_latin]
 
 
2006
  for alias, values in PLACE_NAME_ALIASES.items():
2007
  a = clean_text(alias)
2008
  a_latin = ar_to_latin_guess(alias)
2009
- if q == a or (q and (q in a or a in q)) or (q_latin and (q_latin == a_latin or q_latin in a_latin or a_latin in q_latin)):
2010
- queries.extend(clean_text(v) for v in values)
 
 
 
 
 
 
2011
  out = []
2012
- for x in queries:
2013
- x = clean_text(x)
2014
- if x and len(_compact_key(x)) >= 3 and x not in out:
2015
- out.append(x)
 
 
 
 
2016
  return out
2017
 
2018
-
2019
  def _name_similarity(query: str, names: str) -> float:
2020
  q = clean_text(query)
2021
  n = clean_text(names)
2022
  if not q or not n:
2023
  return 0.0
2024
- q_no = q.replace(" ", "")
2025
- n_no = n.replace(" ", "")
2026
  q_words = [w for w in q.split() if len(w) > 1]
2027
  if q == n or q in n or n in q:
2028
  return 1.0
2029
- if q_no and (q_no in n_no or n_no in q_no):
2030
  return 0.98
2031
  if q_words and all(w in n for w in q_words):
2032
  return 0.92
2033
  common = sum(1 for w in q_words if w in n)
2034
  token_score = 0.45 + 0.35 * common / max(len(q_words), 1) if common else 0.0
2035
- fuzzy_score = difflib.SequenceMatcher(None, q_no, n_no).ratio() * 0.88
2036
  q_ph = _phonetic_key(q)
2037
  n_ph = _phonetic_key(n)
2038
  phonetic_score = 0.0
@@ -2045,7 +1915,6 @@ def _name_similarity(query: str, names: str) -> float:
2045
  phonetic_score = difflib.SequenceMatcher(None, q_ph, n_ph).ratio() * 0.92
2046
  return max(token_score, fuzzy_score, phonetic_score)
2047
 
2048
-
2049
  def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.DataFrame:
2050
  if places_df is None or places_df.empty or not place_name:
2051
  return pd.DataFrame()
@@ -2056,13 +1925,15 @@ def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.Data
2056
  def run_search(df: pd.DataFrame) -> pd.DataFrame:
2057
  if df.empty:
2058
  return df
 
 
 
2059
  out = df.copy()
2060
- out["name_score"] = out.apply(lambda row: max((_name_similarity(q, _place_name_blob(row)) for q in queries), default=0.0), axis=1)
2061
  out = out[out["name_score"] >= 0.50].sort_values("name_score", ascending=False)
2062
  if "semantic_score" not in out.columns:
2063
  out["semantic_score"] = out["name_score"]
2064
  return out.head(top_k).reset_index(drop=True)
2065
- # Try requested category first, but always fallback to all categories so old context cannot hide true place names.
2066
  if category:
2067
  filtered = base[base["category_norm"].apply(lambda c: category_matches(c, category))]
2068
  hit = run_search(filtered)
@@ -2070,84 +1941,160 @@ def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.Data
2070
  return hit
2071
  return run_search(base)
2072
 
 
 
 
 
 
 
 
 
2073
 
2074
- _old_apply_keyword_override_stable = apply_keyword_override
2075
-
2076
- def apply_keyword_override(text: str) -> Optional[str]:
2077
- t = norm(text)
2078
- if is_islamic_greeting(text) or t in {norm(x) for x in STRICT_GREETING_WORDS}:
2079
- return "greeting"
2080
- # Generic categories must win over item extraction.
2081
- cat = infer_category(text)
2082
- if cat and not extract_item_query(text):
2083
- return {
2084
- "restaurant": "nearest_restaurant",
2085
- "pharmacy": "nearest_pharmacy",
2086
- "cafe": "nearest_cafe",
2087
- "supermarket": "nearest_supermarket",
2088
- "housing": "housing_search",
2089
- }.get(cat)
2090
- return _old_apply_keyword_override_stable(text)
2091
-
2092
-
2093
- _old_looks_like_bare_place_name_stable = looks_like_bare_place_name
2094
-
2095
- def looks_like_bare_place_name(text: str) -> bool:
2096
- if is_simple_greeting(text):
2097
- return False
2098
- t = norm(text)
2099
- command_words = MENU_WORDS + ["ูˆุฑูŠู†ูŠ", "ุงุนุฑุถ", "ู‡ุงุช", "ู‚ุงุฆู…ุฉ", "ุงู„ู…ู†ูŠูˆ", "ู…ูˆุงุนูŠุฏ", "ุนู†ูˆุงู†", "ุฑู‚ู…", "ุชู„ูŠููˆู†", "ู„ูˆูƒูŠุดู†", "ุจูŠูุชุญ", "ุงู…ุชู‰", "ุงู…ุชูŠ"]
2100
- if any(norm(w) in t for w in command_words):
2101
- return False
2102
- return _old_looks_like_bare_place_name_stable(text)
2103
-
2104
-
2105
- _old_chat_stable = chat
2106
-
2107
- def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2108
- text = str(text or "").strip()
2109
- if not text:
2110
- return {"reply": "ุงูƒุชุจู„ูŠ ุจุชุฏูˆุฑ ุนู„ู‰ ุฅูŠู‡ ููŠ ุจู†ูŠ ุณูˆูŠู ๐Ÿ˜Š", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2111
- if is_islamic_greeting(text):
2112
- reply = ISLAMIC_GREETING_REPLY
2113
- session.add(text, reply, "greeting", {}, None, [])
2114
- return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2115
- if norm(text) in {norm(x) for x in ["ู‡ุงูŠ", "ู‡ุงู‰", "hi", "hello", "ู‡ู„ุง", "ุงู‡ู„ุง", "ุงู‡ู„ุงู‹", "ู…ุฑุญุจุง", "ุตุจุงุญ ุงู„ุฎูŠุฑ", "ู…ุณุงุก ุงู„ุฎูŠุฑ"]}:
2116
- reply = "ุฃู‡ู„ุงู‹ ุจูŠูƒ ๐Ÿ˜Š ู‚ูˆู„ูŠ ุจุชุฏูˆุฑ ุนู„ู‰ ุฅูŠู‡ ููŠ ุจู†ูŠ ุณูˆูŠู: ู…ุทุนู…ุŒ ูƒุงููŠู‡ุŒ ุตูŠุฏู„ูŠุฉุŒ ู…ุงุฑูƒุช ุฃูˆ ุณูƒู†ุŸ"
2117
- session.add(text, reply, "greeting", {}, None, [])
2118
- return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2119
- return _old_chat_stable(text, session, user_lat, user_lon)
2120
 
 
2121
 
 
 
 
 
 
 
 
 
2122
 
 
 
 
 
 
 
 
 
 
 
 
2123
 
2124
- # Extra guard: category + proper-name phrases like "ุตูŠุฏู„ูŠุฉ ู…ุนุงุฐ" are place-name/details, not item search.
2125
- _old_extract_place_name_from_text_v22b = extract_place_name_from_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2126
 
2127
- def extract_place_name_from_text(text: str) -> str:
2128
- original_clean = clean_text(text)
2129
- guessed = _old_extract_place_name_from_text_v22b(text)
2130
- if guessed:
2131
- return guessed
2132
- if any(w in original_clean for w in ["ุตูŠุฏู„ูŠู‡", "ุตูŠุฏู„ูŠุฉ", "ู…ุทุนู…", "ูƒุงููŠู‡", "ู…ุงุฑูƒุช", "ู‡ุงูŠุจุฑ"]):
2133
- tmp = original_clean
2134
- for w in ["ุนุงูŠุฒ", "ุนุงูŠุฒู‡", "ุนุงูŠุฒุฉ", "ุนุงูˆุฒ", "ุนุงูˆุฒู‡", "ู…ุญุชุงุฌ", "ู…ุญุชุงุฌู‡", "ู…ุญุชุงุฌุฉ", "ููŠู†", "ู…ูƒุงู†", "ุนู†ูˆุงู†", "ุฑู‚ู…", "ู…ูˆุงุนูŠุฏ", "ู…ู†ูŠูˆ", "ุตูŠุฏู„ูŠู‡", "ุตูŠุฏู„ูŠุฉ", "ุตูŠุฏู„ูŠุงุช", "ู…ุทุนู…", "ู…ุทุงุนู…", "ูƒุงููŠู‡", "ูƒุงููŠู‡ุงุช", "ู…ุงุฑูƒุช", "ุณูˆุจุฑ", "ู‡ุงูŠุจุฑ", "ูˆุงุญุฏ", "ู‚ุฑูŠุจ", "ุงู‚ุฑุจ"]:
2135
- tmp = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", tmp)
2136
- tmp = re.sub(r"\s+", " ", tmp).strip()
2137
- if tmp and 2 <= len(tmp) and len(tmp.split()) <= 4 and not is_generic_category_item(tmp):
2138
- return tmp
2139
- return ""
2140
 
2141
- _old_extract_item_query_v22b = extract_item_query
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2142
 
2143
- def extract_item_query(text: str) -> str:
2144
- t = clean_text(text)
2145
- # If user wrote category + a likely name, do not treat the name as product.
2146
- if any(w in t for w in ["ุตูŠุฏู„ูŠู‡", "ุตูŠุฏู„ูŠุฉ", "ู…ุทุนู…", "ูƒุงููŠู‡", "ู…ุงุฑูƒุช", "ู‡ุงูŠุจุฑ"]):
2147
- residual = extract_place_name_from_text(text)
2148
- if residual and not any(k in residual for k in ["ุฏูˆุงุก", "ุฏูˆุง", "ุดูŠุจุณูŠ", "ุจูŠุจุณูŠ", "ุงูŠุณ", "ุจุฑุฌุฑ", "ุจูŠุชุฒุง", "ุดุงูˆุฑู…ุง", "ูƒุฑูŠุจ", "ูˆุงูู„"]):
2149
- return ""
2150
- return _old_extract_item_query_v22b(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2151
 
2152
  @asynccontextmanager
2153
  async def lifespan(app: FastAPI):
@@ -2416,5 +2363,3 @@ def reload_data(x_secret: Optional[str] = Header(default=None)):
2416
  def reset_session(session_id: str):
2417
  SESSIONS.pop(session_id, None)
2418
  return {"status": "reset", "session_id": session_id}
2419
-
2420
- # =========================
 
1819
  session.add(text, reply, result_intent, entities, best, results)
1820
  return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results}
1821
  # =========================
1822
+ # Production hardening patch (V16)
 
 
1823
  # =========================
1824
+ # Overrides search helpers without changing endpoints or response JSON.
1825
+ # Unified place-name resolver for bare names, menu, details, Arabic-written
1826
+ # English names, partial names, and fuzzy matching.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1827
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828
  VOWELS_LATIN = set("aeiouy")
1829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1830
  def _compact_key(text: Any) -> str:
1831
  return re.sub(r"\s+", "", clean_text(text))
1832
 
 
1833
  def _phonetic_key(text: Any) -> str:
1834
+ raw = str(text or "")
1835
+ latin = ar_to_latin_guess(raw) or clean_text(raw)
1836
+ latin = latin.lower().replace("&", " and ").replace("cafe", "kafe")
1837
+ # Normalize common English connector noise before compacting.
1838
  latin = re.sub(r"\b(and|n|the|el|al)\b", " ", latin)
1839
  latin = re.sub(r"[^a-z0-9]+", "", latin)
1840
  latin = latin.replace("kh", "x").replace("sh", "s")
1841
  latin = latin.replace("ph", "f").replace("ck", "k").replace("c", "k").replace("q", "k")
1842
+ # Arabic users usually write English P as ุจ and V as ู, and ุฌ can be g/j.
1843
+ # Normalize close sounds before removing vowels so phonetic matching works
1844
+ # for new DB names without manual aliases.
1845
  latin = latin.replace("p", "b").replace("v", "f").replace("j", "g")
1846
  latin = latin.replace("x", "ks")
1847
  latin = "".join(ch for ch in latin if ch not in VOWELS_LATIN)
1848
  latin = re.sub(r"(.)\1+", r"\1", latin)
1849
  return latin
1850
 
 
1851
  def _place_name_blob(row) -> str:
1852
+ # Name resolver must compare against names only. Including category/search_text
1853
+ # creates false positives (e.g. Antika matching any place that has
1854
+ # "restaurant cafe" because their phonetic keys overlap).
1855
+ return clean_text(" ".join([
1856
+ str(row.get("name", "")),
1857
+ str(row.get("name_ar", "")),
1858
+ str(row.get("name_en", "")),
1859
+ ]))
1860
 
1861
  def expand_place_name_queries(place_name: str) -> list:
1862
  q = clean_text(place_name)
1863
  q_latin = ar_to_latin_guess(place_name)
1864
+ q_compact = _compact_key(place_name)
1865
+ q_phonetic = _phonetic_key(place_name)
1866
+ queries = [x for x in [q, q_latin, q_compact, q_phonetic] if x]
1867
  for alias, values in PLACE_NAME_ALIASES.items():
1868
  a = clean_text(alias)
1869
  a_latin = ar_to_latin_guess(alias)
1870
+ a_ph = _phonetic_key(alias)
1871
+ if (
1872
+ q == a or (q and (q in a or a in q))
1873
+ or (q_latin and (q_latin == a_latin or q_latin in a_latin or a_latin in q_latin))
1874
+ or (q_phonetic and q_phonetic == a_ph)
1875
+ ):
1876
+ for v in values:
1877
+ queries.extend([clean_text(v), _compact_key(v), _phonetic_key(v)])
1878
  out = []
1879
+ for item in queries:
1880
+ item = clean_text(item)
1881
+ # Avoid extremely short generated keys like "n" from mixed
1882
+ # Arabic/English aliases; they cause false positives with almost
1883
+ # any name containing that letter. Real useful place-name queries
1884
+ # should have at least 3 compact characters (e.g. KFC = 3).
1885
+ if item and len(_compact_key(item)) >= 3 and item not in out:
1886
+ out.append(item)
1887
  return out
1888
 
 
1889
  def _name_similarity(query: str, names: str) -> float:
1890
  q = clean_text(query)
1891
  n = clean_text(names)
1892
  if not q or not n:
1893
  return 0.0
1894
+ q_no_space = q.replace(" ", "")
1895
+ n_no_space = n.replace(" ", "")
1896
  q_words = [w for w in q.split() if len(w) > 1]
1897
  if q == n or q in n or n in q:
1898
  return 1.0
1899
+ if q_no_space and (q_no_space in n_no_space or n_no_space in q_no_space):
1900
  return 0.98
1901
  if q_words and all(w in n for w in q_words):
1902
  return 0.92
1903
  common = sum(1 for w in q_words if w in n)
1904
  token_score = 0.45 + 0.35 * common / max(len(q_words), 1) if common else 0.0
1905
+ fuzzy_score = difflib.SequenceMatcher(None, q_no_space, n_no_space).ratio() * 0.88
1906
  q_ph = _phonetic_key(q)
1907
  n_ph = _phonetic_key(n)
1908
  phonetic_score = 0.0
 
1915
  phonetic_score = difflib.SequenceMatcher(None, q_ph, n_ph).ratio() * 0.92
1916
  return max(token_score, fuzzy_score, phonetic_score)
1917
 
 
1918
  def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.DataFrame:
1919
  if places_df is None or places_df.empty or not place_name:
1920
  return pd.DataFrame()
 
1925
  def run_search(df: pd.DataFrame) -> pd.DataFrame:
1926
  if df.empty:
1927
  return df
1928
+ def score(row):
1929
+ names = _place_name_blob(row)
1930
+ return max((_name_similarity(q, names) for q in queries), default=0.0)
1931
  out = df.copy()
1932
+ out["name_score"] = out.apply(score, axis=1)
1933
  out = out[out["name_score"] >= 0.50].sort_values("name_score", ascending=False)
1934
  if "semantic_score" not in out.columns:
1935
  out["semantic_score"] = out["name_score"]
1936
  return out.head(top_k).reset_index(drop=True)
 
1937
  if category:
1938
  filtered = base[base["category_norm"].apply(lambda c: category_matches(c, category))]
1939
  hit = run_search(filtered)
 
1941
  return hit
1942
  return run_search(base)
1943
 
1944
+ ITEM_SYNONYMS = {
1945
+ "ุงูŠุณูƒูˆูู‰": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณูƒูˆููŠ": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒูˆูู‰": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒูˆููŠ": "ุงูŠุณ ูƒูˆููŠ",
1946
+ "ุงูŠุณ ูƒุงููŠ": "ุงูŠุณ ูƒูˆููŠ", "ุงูŠุณ ูƒุงููŠู‡": "ุงูŠุณ ูƒูˆููŠ",
1947
+ "ุงูŠุณ ูƒุฑูŠู…": "ุงูŠุณ ูƒุฑูŠู…", "ุงูŠุณูƒุฑูŠู…": "ุงูŠุณ ูƒุฑูŠู…",
1948
+ "ุฏูˆุง": "ุฏูˆุงุก", "ุฏูˆุงุก": "ุฏูˆุงุก", "ุนู„ุงุฌ": "ุฏูˆุงุก", "ุงุฏูˆูŠู‡": "ุฏูˆุงุก", "ุงุฏูˆูŠุฉ": "ุฏูˆุงุก",
1949
+ "ุดูŠุจุณู‰": "ุดูŠุจุณูŠ", "ุด๏ฟฝ๏ฟฝุจุณูŠ": "ุดูŠุจุณูŠ", "ุจูŠุจุณู‰": "ุจูŠุจุณูŠ", "ุจูŠุจุณูŠ": "ุจูŠุจุณูŠ",
1950
+ "ุดูˆุฑู…ุง": "ุดุงูˆุฑู…ุง", "ุดุงูˆุฑู…ู‡": "ุดุงูˆุฑู…ุง", "ุจุชุฒุง": "ุจูŠุชุฒุง", "ุจูŠุชุฒุงุง": "ุจูŠุชุฒุง",
1951
+ }
1952
 
1953
+ def normalize_item_query(item: str) -> str:
1954
+ q = clean_text(item)
1955
+ q_no = q.replace(" ", "")
1956
+ return ITEM_SYNONYMS.get(q, ITEM_SYNONYMS.get(q_no, q))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1957
 
1958
+ _old_extract_item_query_v15 = extract_item_query
1959
 
1960
+ def extract_item_query(text: str) -> str:
1961
+ item = normalize_item_query(_old_extract_item_query_v15(text))
1962
+ t = clean_text(text)
1963
+ t_no = t.replace(" ", "")
1964
+ for raw, canonical in ITEM_SYNONYMS.items():
1965
+ if raw in t or raw in t_no:
1966
+ return canonical
1967
+ return item
1968
 
1969
+ def intended_item_category(item_query: str) -> str:
1970
+ q = normalize_item_query(item_query)
1971
+ if not q:
1972
+ return ""
1973
+ if any(x in q for x in ["ุฏูˆุงุก", "ุนู„ุงุฌ", "ู…ุณูƒู†", "ู…ุฑู‡ู…", "ููŠุชุงู…ูŠู†"]):
1974
+ return "pharmacy"
1975
+ if any(x in q for x in ["ุดูŠุจุณูŠ", "ุจูŠุจุณูŠ", "ุณู†ุงูƒุณ", "ู…ูŠุงู‡", "ู„ุจู†", "ุนูŠุด", "ุณูƒุฑ", "ุฑุฒ", "ุดูˆูƒูˆู„ุงุชู‡", "ุจุณูƒูˆุช"]):
1976
+ return "supermarket"
1977
+ if any(x in q for x in ["ู‚ู‡ูˆุฉ", "ู‚ู‡ูˆู‡", "ู„ุงุชูŠู‡", "ูƒุงุจุชุดูŠู†ูˆ", "ุงุณุจุฑูŠุณูˆ", "ู…ูˆูƒุง", "ู†ุณูƒุงููŠู‡", "ุงูŠุณ ูƒูˆููŠ", "ุดุงูŠ", "ู…ุดุฑูˆุจุงุช", "ุงูŠุณ ูƒุฑูŠู…", "ูˆุงูู„", "ุญู„ูˆูŠุงุช"]):
1978
+ return "cafe"
1979
+ return "restaurant"
1980
 
1981
+ def item_matches_place(place: dict, item_query: str, use_menu: bool = True) -> bool:
1982
+ item = normalize_item_query(item_query)
1983
+ if not item:
1984
+ return True
1985
+ text_blob = clean_text(" ".join([
1986
+ str(place.get("name", "")), str(place.get("name_ar", "")), str(place.get("name_en", "")),
1987
+ str(place.get("category", "")), str(place.get("sub_category", "")), str(place.get("description", "")),
1988
+ str(place.get("search_text_clean", "")),
1989
+ ]))
1990
+ candidates = {item, clean_text(item), clean_text(item).replace(" ", "")}
1991
+ for raw, canonical in ITEM_SYNONYMS.items():
1992
+ if canonical == item:
1993
+ candidates.add(clean_text(raw)); candidates.add(clean_text(raw).replace(" ", ""))
1994
+ blob_no = text_blob.replace(" ", "")
1995
+ if any(c and (c in text_blob or c in blob_no) for c in candidates):
1996
+ return True
1997
+ if use_menu:
1998
+ try:
1999
+ for m in fetch_menu(place):
2000
+ m_blob = clean_text(" ".join(str(m.get(k, "")) for k in ["name", "name_ar", "name_en", "title", "description", "category"]))
2001
+ m_no = m_blob.replace(" ", "")
2002
+ if any(c and (c in m_blob or c in m_no) for c in candidates):
2003
+ return True
2004
+ except Exception:
2005
+ return False
2006
+ return False
2007
 
2008
+ _old_search_places_v15 = search_places
 
 
 
 
 
 
 
 
 
 
 
 
2009
 
2010
+ def search_places(query: str, category: str = "", item_query: str = "", location: str = "", price_range: str = "", open_now_only: bool = False, place_name: str = "", user_lat=None, user_lon=None, intent: str = "", top_k: int = 12) -> pd.DataFrame:
2011
+ category = normalize_category(category)
2012
+ item_query = normalize_item_query(item_query)
2013
+ if place_name:
2014
+ named = name_search(place_name, category=category, top_k=10)
2015
+ if named.empty:
2016
+ return pd.DataFrame()
2017
+ filtered = apply_filters(named, category="", location=location, price_range=price_range, open_now_only=open_now_only)
2018
+ return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True)
2019
+ if item_query:
2020
+ intended = intended_item_category(item_query)
2021
+ if intended in {"pharmacy", "supermarket"}:
2022
+ category = intended
2023
+ item_query = ""
2024
+ else:
2025
+ if intended == "cafe":
2026
+ # Drinks/desserts can appear in pure cafes, mixed Restaurant & Cafรฉ,
2027
+ # and sometimes pure restaurants. Do not hide a real match just
2028
+ # because the item word itself made infer_category() return cafe.
2029
+ if category in {"", "cafe", "restaurant", "restaurant_cafe"}:
2030
+ cats_to_search = ["cafe", "restaurant"]
2031
+ else:
2032
+ cats_to_search = [category]
2033
+ elif category:
2034
+ cats_to_search = [category]
2035
+ else:
2036
+ cats_to_search = [intended or "restaurant"]
2037
+ frames = []
2038
+ for cat in cats_to_search:
2039
+ base = places_df.copy() if places_df is not None else pd.DataFrame()
2040
+ base = apply_filters(base, category=cat, location=location, price_range=price_range, open_now_only=open_now_only)
2041
+ if base.empty:
2042
+ continue
2043
+ rows = []
2044
+ for _, row in base.iterrows():
2045
+ place = row_to_dict(row)
2046
+ if item_matches_place(place, item_query, use_menu=True):
2047
+ rows.append(place)
2048
+ if rows:
2049
+ frames.append(pd.DataFrame(rows))
2050
+ if not frames:
2051
+ return pd.DataFrame()
2052
+ out = pd.concat(frames, ignore_index=True).drop_duplicates("place_id")
2053
+ if "semantic_score" not in out.columns:
2054
+ out["semantic_score"] = 0.80
2055
+ out = apply_filters(out, category="", location="", price_range=price_range, open_now_only=open_now_only)
2056
+ return rank_places(out, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True)
2057
+ return _old_search_places_v15(query, category=category, item_query=item_query, location=location, price_range=price_range, open_now_only=open_now_only, place_name=place_name, user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=top_k)
2058
 
2059
+ def build_response(results: List[dict], intent: str, category: str = "", item_query: str = "", place_name: str = "", location: str = "", open_now_only: bool = False, soft_reason: str = "", query: str = "", open_uncertain: bool = False, user_has_location: bool = False, related_item_used: str = "") -> str:
2060
+ category = normalize_category(category)
2061
+ if not results:
2062
+ if place_name:
2063
+ return f"ู…ุด ู„ุงู‚ูŠ ู…ูƒุงู† ุจุงุณู… {place_name} ุญุงู„ูŠู‹ุง ๐Ÿ˜”\nู…ู…ูƒู† ุชูƒุชุจู‡ ุจุทุฑูŠู‚ุฉ ุชุงู†ูŠุฉุŸ"
2064
+ if item_query:
2065
+ return f"ู…ุด ู„ุงู‚ูŠ ู…ูƒุงู† ุจูŠู‚ุฏู… {item_query} ููŠ ุงู„ุฏุงุชุง ุงู„ุญุงู„ูŠุฉ ๐Ÿ˜”\nุฌุฑุจ ุตู†ู ุชุงู†ูŠ ุฃูˆ ู…ู†ุทู‚ุฉ ุชุงู†ูŠุฉ."
2066
+ if location and category:
2067
+ return f"ู…ููŠุด {CAT_AR.get(category, 'ุฃู…ุงูƒู†')} ู…ุชุงุญุฉ ุญุงู„ูŠู‹ุง ููŠ {location} ๐Ÿ˜”\nุชุญุจ ุฃุฏูˆุฑ ููŠ ู…ู†ุทู‚ุฉ ุชุงู†ูŠุฉุŸ"
2068
+ if open_now_only and category:
2069
+ return f"ู…ุด ู„ุงู‚ูŠ {CAT_AR.get(category, 'ุฃู…ุงูƒู†')} ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ ๐Ÿ˜”\nุฃู‚ุฏุฑ ุฃุนุฑุถู„ูƒ ุงู„ู…ูˆุฌูˆุฏ ุจุณ ู…ุด ู…ุคูƒุฏ ุฅู†ู‡ ู…ูุชูˆุญ."
2070
+ return _dynamic_reply("fallback")
2071
+ if soft_reason == "open":
2072
+ header = _dynamic_reply("soft_open", category=category)
2073
+ elif soft_reason == "near_item":
2074
+ header = _dynamic_reply("soft_near_item", category=category or "restaurant", item_query=item_query)
2075
+ elif soft_reason == "area":
2076
+ header = _dynamic_reply("area_fallback", category=category, location=location)
2077
+ if open_uncertain:
2078
+ header += "\nูˆุจุฑุถูˆ ุญุงู„ุฉ ุงู„ูุชุญ ุฏู„ูˆู‚ุชูŠ ู…ุด ู…ุคูƒุฏุฉ ู„ูƒู„ ุงู„ุฃู…ุงูƒู† ุฏูŠุŒ ูŠูุถู„ ุชุชุฃูƒุฏ ุจู…ูƒุงู„ู…ุฉ ู‚ุจู„ ู…ุง ุชุฑูˆุญ ๐Ÿ“ž"
2079
+ elif item_query:
2080
+ header = _dynamic_reply("item", category=category or "restaurant", item_query=item_query)
2081
+ elif is_best_near_query(query, intent):
2082
+ header = _dynamic_reply("best_near", category=category, best_place=results[0])
2083
+ elif is_near_query(query) and user_has_location:
2084
+ header = _dynamic_reply("nearest", category=category, best_place=results[0])
2085
+ elif is_near_query(query) and not user_has_location:
2086
+ header = _dynamic_reply("near_no_location", category=category, best_place=results[0])
2087
+ elif is_best_query(query, intent):
2088
+ header = _dynamic_reply("best", category=category, best_place=results[0])
2089
+ elif open_now_only:
2090
+ header = _dynamic_reply("open", category=category, best_place=results[0])
2091
+ elif len(results) == 1:
2092
+ header = _dynamic_reply("one", category=category, best_place=results[0])
2093
+ else:
2094
+ header = _dynamic_reply("category", category=category, best_place=results[0])
2095
+ if len(results) > MAX_CARDS:
2096
+ header += "\n\nููŠ ุฃู…ุงูƒู† ุชุงู†ูŠุฉ ูƒู…ุงู†ุŒ ุงูƒุชุจูŠ ยซูƒู…ุงู†ยป ู„ูˆ ุนุงูŠุฒุงู‡ู…."
2097
+ return header
2098
 
2099
  @asynccontextmanager
2100
  async def lifespan(app: FastAPI):
 
2363
  def reset_session(session_id: str):
2364
  SESSIONS.pop(session_id, None)
2365
  return {"status": "reset", "session_id": session_id}