Youmnaaaa commited on
Commit
1f601cb
·
verified ·
1 Parent(s): 74ca6dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -395
app.py CHANGED
@@ -1819,90 +1819,220 @@ 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
- # 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,6 +2045,7 @@ def _name_similarity(query: str, names: str) -> float:
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,15 +2056,13 @@ def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.Data
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,160 +2070,84 @@ def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.Data
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):
@@ -2365,206 +2418,3 @@ def reset_session(session_id: str):
2365
  return {"status": "reset", "session_id": session_id}
2366
 
2367
  # =========================
2368
- # QA HARDENING PATCH (V19)
2369
- # =========================
2370
- # Last-mile protections for real users: fixed Islamic greetings, stronger
2371
- # phonetic place-name matching, and safer generic product/category routing.
2372
-
2373
- ISLAMIC_GREETING_REPLY = "وعليكم السلام ورحمة الله وبركاته 🌹\nأهلاً بيك، محتاج إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟"
2374
-
2375
- def is_islamic_greeting(text: str) -> bool:
2376
- t = norm(text)
2377
- return (
2378
- "السلام عليكم" in t
2379
- or "سلام عليكم" in t
2380
- or "السلم عليكم" in t
2381
- or "سلامو عليكم" in t
2382
- )
2383
-
2384
- # Strengthen generic item/product routing.
2385
- EXTRA_ITEM_SYNONYMS = {
2386
- "ايسكوفي": "ايس كوفي", "ايس كوفى": "ايس كوفي", "ايس كوفي": "ايس كوفي",
2387
- "ايس كافي": "ايس كوفي", "ايسكافي": "ايس كوفي", "ايس لاتيه": "ايس لاتيه",
2388
- "ايس كريم": "ايس كريم", "ايسكريم": "ايس كريم",
2389
- "دوا": "دواء", "دواء": "دواء", "دواء برد": "دواء", "علاج": "دواء", "ادويه": "دواء", "ادوية": "دواء",
2390
- "شيبسى": "شيبسي", "شيبصي": "شيبسي", "شيبسي": "شيبسي",
2391
- "بيبسى": "بيبسي", "بيبصي": "بيبسي", "بيبسي": "بيبسي",
2392
- "شورما": "شاورما", "شاورمه": "شاورما", "بتزا": "بيتزا", "بيتزاا": "بيتزا",
2393
- "مكس لحوم": "ميكس لحوم", "ميكس لحوم": "ميكس لحوم",
2394
- }
2395
- try:
2396
- ITEM_SYNONYMS.update(EXTRA_ITEM_SYNONYMS)
2397
- except NameError:
2398
- ITEM_SYNONYMS = EXTRA_ITEM_SYNONYMS.copy()
2399
-
2400
- # Generic transliteration tokens, not per-place aliases. These help new DB names
2401
- # that contain common English words written in Arabic.
2402
- EXTRA_PLACE_WORDS = {
2403
- "اند": "and", "ان": "and", "اندد": "and", "اندى": "and", "اندو": "and",
2404
- "كافيه": "cafe", "كافي": "cafe", "كافى": "cafe", "كوفي": "coffee", "كوفى": "coffee",
2405
- "مطعم": "restaurant", "ريست��رانت": "restaurant", "ماركت": "market", "هايبر": "hyper", "مول": "mall",
2406
- "بابلك": "public", "بوبلك": "public", "ببلك": "public", "بابليك": "public",
2407
- "جراند": "grand", "رويال": "royal", "كينج": "king", "كوين": "queen", "فاميلي": "family", "فاميلى": "family",
2408
- "ستار": "star", "ستارز": "stars", "سنتر": "center", "سينتر": "center", "سيتي": "city", "سيتى": "city",
2409
- "شوب": "shop", "ستور": "store", "هاوس": "house", "هوم": "home", "كورنر": "corner",
2410
- "بيتزا": "pizza", "بايك": "bike", "برجر": "burger", "تشكن": "chicken", "فرايد": "fried",
2411
- "بافي": "puffy", "بوفي": "puffy", "فلافي": "fluffy", "فلافى": "fluffy",
2412
- }
2413
-
2414
- _old_ar_to_latin_guess_v19 = ar_to_latin_guess
2415
-
2416
- def ar_to_latin_guess(text: Any) -> str:
2417
- src = clean_text(text)
2418
- if not src:
2419
- return ""
2420
- # Apply generic word replacements before falling back to character-level transliteration.
2421
- words = [EXTRA_PLACE_WORDS.get(w, w) for w in src.split()]
2422
- replaced = " ".join(words)
2423
- # If replacement produced Latin tokens, keep them and transliterate remaining Arabic chars.
2424
- guessed = _old_ar_to_latin_guess_v19(replaced)
2425
- return guessed or replaced
2426
-
2427
- _old_extract_item_query_v19 = extract_item_query
2428
-
2429
- def extract_item_query(text: str) -> str:
2430
- t = clean_text(text)
2431
- t_no = t.replace(" ", "")
2432
- for raw, canonical in ITEM_SYNONYMS.items():
2433
- raw_clean = clean_text(raw)
2434
- if raw_clean and (raw_clean in t or raw_clean.replace(" ", "") in t_no):
2435
- return canonical
2436
- item = _old_extract_item_query_v19(text)
2437
- return normalize_item_query(item) if item else ""
2438
-
2439
- _old_intended_item_category_v19 = intended_item_category
2440
-
2441
- def intended_item_category(item_query: str) -> str:
2442
- q = normalize_item_query(item_query)
2443
- if not q:
2444
- return ""
2445
- if any(x in q for x in ["دواء", "علاج", "مسكن", "مرهم", "فيتامين"]):
2446
- return "pharmacy"
2447
- if any(x in q for x in ["شيبسي", "بيبسي", "سناكس", "مياه", "لبن", "عيش", "سكر", "رز", "شوكولاته", "بسكوت"]):
2448
- return "supermarket"
2449
- if any(x in q for x in ["قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "موكا", "نسكافيه", "ايس كوفي", "ايس لاتيه", "شاي", "مشروبات", "ايس كريم", "وافل", "حلويات"]):
2450
- return "cafe"
2451
- return _old_intended_item_category_v19(q) or "restaurant"
2452
-
2453
- # Update place aliases conservatively only for common spelling families seen in production tests.
2454
- try:
2455
- PLACE_NAME_ALIASES.update({
2456
- "انتيكا": ["antika"], "انتكا": ["antika"], "انتيكه": ["antika"],
2457
- "بافي اند فلافي": ["puffy fluffy", "puffy and fluffy", "puffy & fluffy"],
2458
- "بافي فلافي": ["puffy fluffy", "puffy and fluffy", "puffy & fluffy"],
2459
- })
2460
- except NameError:
2461
- PLACE_NAME_ALIASES = {}
2462
-
2463
- _old_chat_v19 = chat
2464
-
2465
- def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2466
- # Absolute first gate: no model/NER/context should handle Islamic greeting.
2467
- if is_islamic_greeting(text):
2468
- reply = ISLAMIC_GREETING_REPLY
2469
- session.add(text, reply, "greeting", {}, None, [])
2470
- return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2471
- return _old_chat_v19(text, session, user_lat, user_lon)
2472
-
2473
- # =========================
2474
- # QA HARDENING PATCH (V20)
2475
- # =========================
2476
- # Fix priority: menu/detail phrases must not be swallowed by bare-name search.
2477
-
2478
- _old_looks_like_bare_place_name_v20 = looks_like_bare_place_name
2479
-
2480
- def looks_like_bare_place_name(text: str) -> bool:
2481
- t = norm(text)
2482
- if not t:
2483
- return False
2484
- # Commands/details with a name are not "bare names". Let the correct
2485
- # menu/details branch handle them first.
2486
- command_words = MENU_WORDS + [
2487
- "وريني", "اعرض", "هات", "ابعت", "قائمة", "منيو", "مينيو",
2488
- "مواعيد", "ميعاد", "معاد", "عنوان", "رقم", "تليفون", "لوكيشن",
2489
- "بيفتح", "بتفتح", "امتى", "امتي",
2490
- ]
2491
- if any(norm(w) in t for w in command_words):
2492
- return False
2493
- return _old_looks_like_bare_place_name_v20(text)
2494
-
2495
-
2496
- def _resolve_menu_place(text: str):
2497
- place_name = extract_menu_place_name(text) or extract_place_name_from_text(text)
2498
- if not place_name:
2499
- return None, place_name
2500
- # Menu belongs to restaurants/cafes, but fallback to all names for mixed/dirty DB categories.
2501
- hits = name_search(place_name, category="restaurant", top_k=1)
2502
- if hits.empty:
2503
- hits = name_search(place_name, category="cafe", top_k=1)
2504
- if hits.empty:
2505
- hits = name_search(place_name, category="", top_k=1)
2506
- if hits.empty:
2507
- return None, place_name
2508
- return row_to_dict(hits.iloc[0]), place_name
2509
-
2510
- _old_chat_v20 = chat
2511
-
2512
- def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2513
- text = str(text or "").strip()
2514
- if not text:
2515
- return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2516
- if is_islamic_greeting(text):
2517
- reply = ISLAMIC_GREETING_REPLY
2518
- session.add(text, reply, "greeting", {}, None, [])
2519
- return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2520
- if has_any(text, MENU_WORDS) or has_any(text, ["وريني", "اعرض", "هات المنيو", "قائمة الطعام"]):
2521
- place, place_name = _resolve_menu_place(text)
2522
- if not place:
2523
- reply = f"مش لاقي مطعم أو كافيه باسم {place_name or 'ده'} عشان أجيب المنيو 😔"
2524
- session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or "")}, None, [])
2525
- return {"reply": reply, "intent": "show_menu", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or "")}, "best_place": None, "all_results": [], "menu_items": []}
2526
- items = fetch_menu(place)
2527
- reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔"
2528
- session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or place.get('name',''))}, place, [place])
2529
- return {"reply": reply, "intent": "show_menu", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or place.get('name',''))}, "best_place": place, "all_results": [place], "menu_items": items}
2530
- return _old_chat_v20(text, session, user_lat, user_lon)
2531
-
2532
- # =========================
2533
- # QA HARDENING PATCH (V21)
2534
- # =========================
2535
- # Follow-up menu requests: "المنيو" after a shown place should use last_place.
2536
-
2537
- _old_extract_menu_place_name_v21 = extract_menu_place_name
2538
-
2539
- def extract_menu_place_name(text: str) -> str:
2540
- t = clean_text(text)
2541
- for w in ["هات", "ابعت", "وريني", "اعرض", "منيو", "المنيو", "مينيو", "المينيو", "menu", "قائمة", "قائمه", "القائمة", "قائمة الطعام", "بتاع", "بتاعت"]:
2542
- t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t)
2543
- return re.sub(r"\s+", " ", t).strip()
2544
-
2545
- _old_chat_v21 = chat
2546
-
2547
- def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict:
2548
- text = str(text or "").strip()
2549
- if not text:
2550
- return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2551
- if is_islamic_greeting(text):
2552
- reply = ISLAMIC_GREETING_REPLY
2553
- session.add(text, reply, "greeting", {}, None, [])
2554
- return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []}
2555
- if has_any(text, MENU_WORDS) or has_any(text, ["وريني", "اعرض", "هات المنيو", "قائمة الطعام", "المنيو", "المينيو"]):
2556
- place_name = extract_menu_place_name(text)
2557
- place = None
2558
- if not place_name and session.last_place:
2559
- place = session.last_place
2560
- else:
2561
- place, _ = _resolve_menu_place(text)
2562
- if not place:
2563
- reply = f"اكتب اسم المطعم أو الكافيه عشان أجيبلك المنيو 😊"
2564
- session.add(text, reply, "missing_info", {"place_name": clean_text(place_name or "")}, None, [])
2565
- return {"reply": reply, "intent": "missing_info", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or "")}, "best_place": None, "all_results": [], "menu_items": []}
2566
- items = fetch_menu(place)
2567
- reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔"
2568
- session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or place.get('name',''))}, place, [place])
2569
- return {"reply": reply, "intent": "show_menu", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or place.get('name',''))}, "best_place": place, "all_results": [place], "menu_items": items}
2570
- return _old_chat_v21(text, session, user_lat, user_lon)
 
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
  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
  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
  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):
 
2418
  return {"status": "reset", "session_id": session_id}
2419
 
2420
  # =========================