diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -2363,3818 +2363,208 @@ def reload_data(x_secret: Optional[str] = Header(default=None)): def reset_session(session_id: str): SESSIONS.pop(session_id, None) return {"status": "reset", "session_id": session_id} -INTENT_REPO = os.getenv("INTENT_REPO", "Youmnaaaa/Intent-model") -ENTITY_REPO = os.getenv("ENTITY_REPO", "Youmnaaaa/Entity-model") -SEMANTIC_MODEL_NAME = os.getenv( - "SEMANTIC_MODEL_NAME", - "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", -) - -AROUNDU_BASE = os.getenv( - "AROUNDU_BASE", - "https://aroundubackend-production.up.railway.app/api/v1/ai/data", -).rstrip("/") -AROUNDU_KEY = os.getenv("AROUNDU_API_KEY", os.getenv("PLACES_API_KEY", "")).strip() -RELOAD_SECRET = os.getenv("RELOAD_SECRET", "") - -INTENT_THRESHOLD = float(os.getenv("INTENT_THRESHOLD", "0.70")) -SEMANTIC_MIN_SCORE = float(os.getenv("SEMANTIC_MIN_SCORE", "0.35")) -SEMANTIC_TOP_K = int(os.getenv("SEMANTIC_TOP_K", "25")) -SESSION_TTL_SEC = int(os.getenv("SESSION_TTL_SEC", "3600")) -MAX_CARDS = int(os.getenv("MAX_CARDS", "4")) - -intent_pipe = None -ner_pipe = None -semantic_model = None -places_df: Optional[pd.DataFrame] = None -corpus_df: Optional[pd.DataFrame] = None -corpus_embeddings = None -STARTUP_COMPLETE = False -SESSIONS: Dict[str, "Session"] = {} -MENU_CACHE: Dict[str, list] = {} - - -class CFG: - UI_TEXT_ONLY = "text_only" - UI_PLACES_CARDS = "places_cards" - UI_MENU_LIST = "menu_list" - MSG_API_ERROR = "حصلت مشكلة مؤقتة في الاتصال بالخدمة. جرب تاني بعد لحظات." - - -SEARCH_INTENTS = { - "nearest_restaurant", "nearest_pharmacy", "nearest_cafe", "nearest_supermarket", - "housing_search", "recommend_place", "recommendation_by_mood", "open_now", - "open_now_extended", "place_details", "search_by_item", "best_of", "nearby_search", - "filter_results", "sort_results", "availability_question", "ask_location", - "ask_price", "ask_rating", "price_question", "ambiguous_place", -} - -NO_CARD_INTENTS = { - "fallback", "no_result", "missing_info", "out_of_scope", "clarification", - "clarification_response", "greeting", "thanks", "goodbye", "confirm", "deny", -} - -INTENT_TO_CATEGORY = { - "nearest_restaurant": "restaurant", - "nearest_pharmacy": "pharmacy", - "nearest_cafe": "cafe", - "nearest_supermarket": "supermarket", - "housing_search": "housing", -} - -CATEGORY_KEYWORDS = { - "restaurant": [ - "مطعم", "مطاعم", "اكل", "أكل", "وجبات", "مشويات", "كباب", "كفته", "كفتة", - "شاورما", "كريب", "سندوتش", "سندوتشات", "برجر", "بيتزا", "فراخ", "فول", - "طعمية", "سمك", "restaurant", "food", "burger", "pizza", "shawarma", "crepe", - ], - "pharmacy": [ - "صيدليه", "صيدلية", "صيدليات", "صيدله", "صديليه", "صديليه", "دوا", "دواء", "ادويه", "أدوية", - "ادوية", "علاج", "pharmacy", "drugstore", "medicine", - ], - "cafe": [ - "كافيه", "كافيهات", "كافية", "كوفي", "قهوه", "قهوة", "كافيتيريا", "لاتيه", - "كابتشينو", "اسبريسو", "cafe", "coffee", - ], - "supermarket": [ - "سوبرماركت", "سوبر ماركت", "سوبر", "ماركت", "هايبر", "بقاله", "بقالة", - "supermarket", "market", "grocery", "hypermarket", - ], - "housing": [ - "سكن", "شقه", "شقة", "شقق", "ايجار", "إيجار", "فندق", "هوستل", - "hotel", "apartment", "housing", "rent", - ], -} - -CAT_AR = { - "restaurant": "مطاعم", - "pharmacy": "صيدليات", - "cafe": "كافيهات", - "supermarket": "ماركت", - "housing": "أماكن سكن", -} -CAT_SINGLE = { - "restaurant": "مطعم", - "pharmacy": "صيدلية", - "cafe": "كافيه", - "supermarket": "ماركت", - "housing": "مكان سكن", -} - -KEYWORD_INTENTS = { - "greeting": ["السلام عليكم", "وعليكم السلام", "اهلا", "أهلا", "هلا", "مرحبا", "صباح الخير", "مساء الخير", "hi", "hello"], - "thanks": ["شكرا", "شكراً", "تسلم", "تسلمي", "يسلمو", "مشكور", "thanks", "thank you"], - "goodbye": ["مع السلامة", "مع السلامه", "باي", "وداعا", "bye", "goodbye"], - "confirm": ["تمام", "اوك", "أوك", "ماشي", "حاضر", "اه", "اها", "ايوه", "نعم"], - "deny": ["لا", "لأ", "مش عايز", "مش عايزة", "مش ده", "مش دي", "مش قصدي", "مش ده اللي قصدي"], -} - -OUT_OF_SCOPE_KW = [ - "الجو", "طقس", "درجة الحرارة", "كوره", "كرة", "أهلي", "زمالك", "ماتش", "سياسة", - "اخبار", "أخبار", "بنك", "رصيد", "تحويل", "امتحان", "مدرسة", "جامعة", "كود", - "برمجة", "python", "java", "ترجمة", "translate", "نكتة", "قصيدة", "دولار", "ذهب", -] - -DETAIL_WORDS = [ - "فين", "مكان", "مكانه", "مكانها", "عنوان", "عنوانه", "عنوانها", "لوكيشن", "الموقع", - "رقم", "رقمه", "رقمها", "تليفون", "تلفون", "بيفتح", "بتفتح", "مواعيد", "مواعيده", - "مواعيدها", "امتى", "امتي", "تقييم", "سعر", "بكام", "غالي", "رخيص", -] -# Words that signal the sentence is asking about a NEW category/item, not -# requesting details about the place already in context. If any of these -# appear alongside a DETAIL_WORD, the sentence is treated as "new" rather -# than "detail" — e.g. "فين أقرب كافيه" should search for cafes, not pull -# up the last place's address just because it contains "فين". -NEW_SEARCH_SIGNAL_WORDS = [ - "اقرب", "أقرب", "قريب", "قريبه", "قريبة", - "مطعم", "مطاعم", "كافيه", "كافيهات", "صيدليه", "صيدلية", "صيدليات", - "ماركت", "سوبر", "سوبرماركت", "هايبر", "شقه", "شقة", "سكن", -] -NEXT_WORDS = ["تاني", "غيره", "غيرها", "بديل", "حاجة تانية", "مش عاجبني", "فيه تاني", "كمان"] -REF_WORDS = ["هو", "هي", "ده", "دي", "المكان ده", "المحل ده"] - - -NEAR_WORDS = ["اقرب", "الأقرب", "الاقرب", "قريب", "قريبه", "قريبة", "جنبي", "حواليا", "حولي", "near", "nearest", "nearby"] -BEST_WORDS = ["احسن", "أحسن", "افضل", "أفضل", "اعلى تقييم", "أعلى تقييم", "كويس", "ممتاز", "رشحلي", "التوب"] -OPEN_WORDS = ["مفتوح", "فاتح", "شغال", "دلوقتي", "24 ساعه", "24 ساعة", "بليل"] -MENU_WORDS = ["منيو", "مينيو", "menu", "قائمة"] -ITEM_CUES = ["عايز", "عايزة", "عاوز", "محتاج", "نفسي", "بيعمل", "بتعمل", "عنده", "عندها", "فيه", "فيها"] -NON_ITEM_WORDS = { - "طب", "طيب", "تمام", "ماشي", "يعني", "بقا", "بقى", "كدا", "كده", "هو", "هي", "ده", "دي", - "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "تقييم", "ريتنج", "التوب", "توب", "top", - "قريب", "قريبه", "قريبة", "اقرب", "أقرب", "هنا", "هناك", "دلوقتي", "مفتوح", "فاتح", "شغال", - "ايه", "إيه", "مين", "واحد", "حاجة", "حاجه" -} - - -EXACT_GREETING_REPLIES = { - "السلام عليكم": "وعليكم السلام ورحمة الله وبركاته 😊 محتاج إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟", - "سلام عليكم": "وعليكم السلام ورحمة الله وبركاته 😊 محتاج إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟", -} - -# Arabic spellings / transliterations for places whose official DB name is English. -# This is intentionally conservative: it helps name search without changing API shape. -PLACE_NAME_ALIASES = { - "اون بابلك": ["on public", "اون public", "on بابلك"], - "اون بابللك": ["on public"], - "اون بابليك": ["on public"], - "بوليفار": ["bolivar", "bo livar", "boulevard", "bolivar cafe", "bo livar cafe"], - "بوليفار كافيه": ["bolivar", "bo livar"], - "صن شاين": ["sunshine", "sun shine", "sunshine cafe"], - "سن شاين": ["sunshine", "sun shine"], - "لاميرا": ["lamera", "la mera"], - "لميرا": ["lamera", "la mera"], - "سان هوك": ["sanhok", "san hok"], - "سانهوك": ["sanhok", "san hok"], - "بيتزا بايك": ["pizza bike"], -} - -ITEM_CATEGORY_HINTS = { - "restaurant": [ - "برجر", "بيتزا", "شاورما", "كريب", "مشويات", "كباب", "كفته", "كفتة", "فراخ", "نص فراخ", - "نص فرخه", "نص فرخة", "فول", "طعميه", "طعمية", "سمك", "كشري", "حواوشي", "فطير", - "اكل", "أكل", "وجبه", "وجبة", "ميكس لحوم", "مكس لحوم", "لحوم", "تشكن", "فرايد", "ساندوتش" - ], - "cafe": [ - "قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "موكا", "نسكافيه", "ايس كوفي", - "ايس كوفى", "ايس كافي", "آيس كوفي", "ice coffee", "ايس لاتيه", "شاي", "مشروبات", - "ايس كريم", "آيس كريم", "ice cream", "وافل", "حلويات" - ], - "pharmacy": ["دواء", "دوا", "علاج", "ادويه", "أدوية", "دواء برد", "مسكن", "مرهم", "فيتامين"], - "supermarket": ["شيبسي", "بيبسي", "مياه", "ميا", "لبن", "عيش", "سكر", "رز", "شوكولاته", "بسكوت", "سناكس", "مشروب"], -} - -DYNAMIC_TEMPLATES = { - "category": [ - "من عينيا! جمعتلك أحسن اختيارات {cat_ar} متاحة في بني سويف، شوف الكروت تحت واختار اللي يناسبك 👇", - "جاهز لمساعدتك! دي لستة {cat_ar} مناسبة ومترتبة عشان تختار بسرعة 🗺️", - "تأمر يا هندسة! لقيتلك شوية اختيارات كويسة من {cat_ar} في بني سويف ✨", - "تمام، دورتلك وطلعتلك أنسب {cat_ar} حسب طلبك 👇", - "دي أفضل نتايج لقيتها ليك من {cat_ar}، بص على الكروت وشوف الأنسب ", - ], - "nearest": [ - "حسبتلك المسافات بالملي! دي الأماكن مترتبة من الأقرب للأبعد من موقعك الحالي 📍", - "علطول كده! أول كارت هو الأقرب ليك، وبعده الباقي حسب المسافة 🚗", - "جبتلك الأقرب فالأقرب عشان المشوار يبقى سهل وسريع ⏱️", - "دي أقرب اختيارات حوالين موقعك الحالي، مرتبة من الأقرب للأبعد 👇", - "رتبتهم حسب المسافة الجغرافية من مكانك، شوف أول كارت هيبقى الأقرب 📌", - ], - "best": [ - "بناءً على التقييمات، {best_name} ظاهر كأقوى اختيار، وباقي الكروت مرتبة حسب الأعلى تقييمًا 🏆", - "عايز التوب؟ رتبتلك الأماكن حسب أعلى Rating وتجارب الناس ⭐", - "دي قمة الأماكن في التقييم، الأعلى تقييمًا ظاهرين في الأول 🌟", - "الناس بتقول إن دول الأفضل، رتبتهم حسب التقييم عشان تختار وانت مطمن ✨", - "جمعتلك الاختيارات الأعلى تقييمًا في بني سويف، أول كارت هو الأقوى تقييمًا 👇", - ], - "best_near": [ - "جمعتلك المعادلة الصح: أماكن تقييمها عالي وقريبة منك في نفس الوقت، أول كارت هو الأفضل توازنًا بين الجودة والمسافة ⭐📍", - "رتبتلك الاختيارات حسب التقييم مع مراعاة القرب، عشان تختار مكان كويس ومش بعيد 👇", - "دي أماكن قوية في الريتنج وقريبة نسبيًا من موقعك، يعني جودة ومشوار أسهل في نفس الوقت 🚗⭐", - "عملتلك ترتيب ذكي بين الأعلى تقييمًا والأقرب، شوف أول كارت هيبقى أنسب اختيار متوازن ✨", - "لو عايز حاجة كويسة وقريبة، دي أفضل النتائج حسب الريتنج والمسافة مع بعض 📌", - ], - "item": [ - "طلبك عندي! دورت في الأماكن المتاحة ولقيتلك اللي بيقدموا {item} 😋👇", - "جبتلك المفيد! دي الأماكن اللي ظاهر عندها {item} في الداتا 🎯", - "بال هنا مقدمًا! دي اختيارات مناسبة لطلب {item} 👇", - "دورتلك على {item} وطلعتلك الأماكن الأقرب للطلب ده ✨", - "دي الأماكن اللي ينفع تبدأ بيها لو نفسك في {item} 😋", - ], - "open": [ - "فلترتلك الأماكن المفتوحة دلوقتي قدر الإمكان، شوف الكروت تحت 🟢", - "دورت على المتاح دلوقتي، والنتايج تحت حسب حالة المواعيد المسجلة ⏰", - "دي الأماكن اللي باين إنها شغالة أو متاحة حاليًا في الداتا 👇", - "تمام، ركزت على الأماكن المفتوحة دلوقتي حسب المواعيد المتاحة 🟢", - "شوف دول، حاولت أجيبلك المتاح دلوقتي بأفضل ترتيب 👇", - ], - "soft_open": [ - "مش لاقي {cat_ar} باين إنها مفتوحة دلوقتي، بس دي {cat_ar} متاحة في الداتا وممكن تتأكد من المواعيد أو تتصل بيهم 👇", - "مفيش نتيجة مؤكدة إنها مفتوحة حاليًا، فبعرضلك الموجود مع توضيح حالة المواعيد عشان تختار 👇", - "مش ظاهر عندي مكان مفتوح دلوقتي بشكل مؤكد، بس دول أقرب بدائل متاحة في الداتا 👇", - "للأسف حالة الفتح مش مؤكدة للطلب ده، لكن دي اختيارات موجودة ممكن تنفعك 👇", - "مش لاقي مفتوح مؤكد حاليًا، فدي الأماكن المسجلة المتاحة وقدامك كروتها 👇", - ], - "soft_near_item": [ - "مفيش {cat_single} قريب واضح عنده {item}، بس دي أماكن بتقدم {item} ومترتبة من الأقرب للأبعد 👇", - "اللي قريب جدًا ومطابق للصنف مش ظاهر ��ندي، فجبتهالك حسب أقرب أماكن عندها {item} 📍", - "مش لاقي {item} قريب منك أوي، بس دول المتاحين للصنف ده مرتبين بالمسافة 👇", - "مفيش نتيجة قريبة كفاية للصنف ده، بس دي أقرب اختيارات فيها {item} 🚗", - "لقيت {item} بس مش واضح إنه قريب جدًا، فرتبتلك البدائل حسب المسافة 👇", - ], - "area_fallback": [ - "مفيش {cat_ar} متاحة حاليًا في {location}، بس لقيت بدائل قريبة/متاحة في بني سويف 👇", - "المنطقة دي مش ظاهر فيها {cat_ar} دلوقتي، فبعرضلك اختيارات تانية ممكن تنفعك 👇", - "مش لاقي {cat_ar} في {location} حاليًا، لكن دي نتائج بديلة من الداتا 👇", - "في {location} مفيش نتيجة مطابقة، فدي أقرب بدائل مناسبة عندي 👇", - "مفيش {cat_ar} مسجلة في {location} حاليًا، شوف البدائل دي 👇", - ], - "one": [ - "لقيتلك المكان ده، وده أقرب اختيار مناسب لطلبك 👇", - "فيه اختيار واضح مناسب للي بتدور عليه 👇", - "ده أفضل Match لطلبك حاليًا 👇", - "لقيت نتيجة واحدة مناسبة، شوفها كده 👇", - "ده المكان اللي طلع مطابق لطلبك 👇", - ], - "near_no_location": [ - "جبتلك اختيارات مناسبة، ولو بعتلي موقعك هرتبهم من الأقرب للأبعد بدقة 📍", - "دي نتايج مناسبة حسب الداتا المتاحة، ولترتيب المسافة الحقيقي ابعتلي موقعك الحالي 😊", - "أقدر أرتبهم بالأقرب لو وصلني موقعك، دلوقتي بعرضلك أنسب الاختيارات المتاحة 👇", - "لو عايزاهم بالمسافة بالظبط ابعتي موقعك، ودي أفضل نتايج متاحة حاليًا 👇", - "دي اختيارات ممكن تنفعك، ومع الموقع هقدر أحدد الأقرب ليكي بالملي 📌", - ], - "fallback": [ - "مش فاهم قصدك أوي 😊 اسألني عن مطعم، كافيه، صيدلية، ماركت أو سكن في بني سويف.", - "أنا أقدر أساعدك في أماكن بني سويف: مطاعم، كافيهات، صيدليات، ماركت أو سكن 😊", - "وضحلي بس بتدور على إيه؟ مطعم؟ صيدلية؟ كافيه؟ وأنا أجيبلك الكروت 👇", - "ممكن تعيد السؤال بطريقة أبسط؟ أنا متخصص في خدمات وأماكن بني سويف 😊", - "قولي نوع المكان أو اسم الأكلة أو المنطقة، وأنا أظبطهالك 👌", - ], -} - - -def clean_text(text: Any) -> str: - text = str(text or "").strip().lower() - text = text.replace("café", "cafe").replace("cafè", "cafe") - text = re.sub(r"ـ+", "", text) - replacements = [("[إأآا]", "ا"), ("ى", "ي"), ("ة", "ه"), ("ؤ", "و"), ("ئ", "ي")] - for old, new in replacements: - text = re.sub(old, new, text) - text = re.sub(r"[^\w\s]", " ", text) - return re.sub(r"\s+", " ", text).strip() - - -def norm(text: Any) -> str: - return clean_text(text) - - - -def ar_to_latin_guess(text: Any) -> str: - """Best-effort Arabic -> Latin place-name transliteration for name search. - - This runs only in RAM/search logic. It does not require DB aliases, and it - helps queries like "لاميرا" match DB names like "Lamera". - """ - src = clean_text(text) - if not src: - return "" - - # If the query is already Latin/English, just normalize spaces. - if re.search(r"[a-zA-Z]", str(text or "")): - return src - - pairs = { - "ش": "sh", "خ": "kh", "غ": "gh", "ث": "th", - "ذ": "z", "ص": "s", "ض": "d", "ط": "t", "ظ": "z", - } - single = { - "ا": "a", "ب": "b", "ت": "t", "ج": "g", "ح": "h", "د": "d", - "ر": "r", "ز": "z", "س": "s", "ع": "a", "ف": "f", "ق": "q", - "ك": "k", "ل": "l", "م": "m", "ن": "n", "ه": "h", "و": "o", - "ي": "i", "ى": "i", "ء": "", " ": " ", - } - - out = [] - for ch in src: - out.append(pairs.get(ch, single.get(ch, ch))) - guessed = re.sub(r"\s+", " ", "".join(out)).strip() - - # Very common Egyptian Arabic renderings of English brand/place names. - # These are fallback corrections on top of the generic transliteration. - manual_common = { - "lamira": "lamera", - "lamera": "lamera", - "l mira": "lamera", - "la mira": "lamera", - "bolifar": "bolivar boulevard", - "bolivar": "bolivar boulevard", - "bolivard": "boulevard", - "bolifard": "boulevard", - "sn shain": "sunshine sun shine", - "sun shain": "sunshine sun shine", - "san shain": "sunshine sun shine", - "sanhok": "sanhok san hok", - "san hok": "sanhok san hok", - "aon bablk": "on public", - "on bablk": "on public", - "aon bablik": "on public", - "on bablik": "on public", - "on bablik": "on public", - "aon bablyk": "on public", - "aon public": "on public", - "ozi": "ouzi ozi", - "aozi": "ouzi ozi", - "siti krib": "city crepe", - "city krib": "city crepe", - "ai klas": "a class", - "a klas": "a class", - "bitza baik": "pizza bike", - "pizza baik": "pizza bike", - } - return manual_common.get(guessed, guessed) - - - -def normalize_category(cat: Any) -> str: - c = clean_text(cat) - if not c: - return "" - has_rest = "restaurant" in c or "مطعم" in c or "مطاعم" in c or "اكل" in c - has_cafe = "cafe" in c or "coffee" in c or "كافيه" in c or "كوفي" in c or "قهوه" in c or "قهوة" in c - if has_rest and has_cafe: - return "restaurant_cafe" - if "pharmacy" in c or "صيدلي" in c or "صيدله" in c or "صيدليه" in c or "صيدلية" in c or "دواء" in c or "دوا" in c: - return "pharmacy" - if "supermarket" in c or "market" in c or "grocery" in c or "ماركت" in c or "بقال" in c or "هايبر" in c: - return "supermarket" - if has_cafe: - return "cafe" - if "housing" in c or "hotel" in c or "hostel" in c or "سكن" in c or "شقه" in c or "فندق" in c: - return "housing" - if has_rest: - return "restaurant" - return c - - -def category_matches(raw_category: Any, target: str) -> bool: - """Strict but fair category matching. - Mixed categories like 'restaurant & café' should match both restaurant and cafe. - """ - if not target: - return True - target = normalize_category(target) - raw = clean_text(raw_category) - norm_cat = normalize_category(raw_category) - if norm_cat == target: - return True - if norm_cat == "restaurant_cafe" and target in {"restaurant", "cafe"}: - return True - if target == "restaurant": - return "restaurant" in raw or "مطعم" in raw or "مطاعم" in raw - if target == "cafe": - return "cafe" in raw or "coffee" in raw or "كافيه" in raw or "كوفي" in raw or "قهوه" in raw or "قهوة" in raw - if target == "pharmacy": - return "pharmacy" in raw or "صيدلي" in raw or "صيدله" in raw or "صيدليه" in raw or "صيدلية" in raw - if target == "supermarket": - return "supermarket" in raw or "market" in raw or "ماركت" in raw or "بقال" in raw or "هايبر" in raw - if target == "housing": - return "housing" in raw or "hotel" in raw or "hostel" in raw or "سكن" in raw or "شقه" in raw or "فندق" in raw - return norm_cat == target or target in raw - - -def infer_category(text: str, intent: str = "", entities: Optional[dict] = None) -> str: - entities = entities or {} - if entities.get("category"): - return normalize_category(entities["category"]) - if intent in INTENT_TO_CATEGORY: - return INTENT_TO_CATEGORY[intent] - t = norm(text) - for cat, words in CATEGORY_KEYWORDS.items(): - if any(norm(w) in t for w in words): - return cat - return "" - - -def is_out_of_scope(text: str) -> bool: - t = norm(text) - # Word-boundary match (not raw substring) — otherwise short keywords - # like "بنك" or "ذهب" wrongly match inside unrelated longer words - # ("بنكهة" = flavor, "مذهبي" = my taste/preference), incorrectly - # routing normal place/food queries into the out-of-scope rejection. - # Also allow an optional leading "ال" (definite article, attaches - # directly with no space — "السياسة" = "ال" + "سياسة") since a plain - # \b boundary can't separate them and would otherwise miss "سياسة" - # whenever the user writes it with the article attached. - return any(re.search(rf"\bال?{re.escape(norm(k))}\b", t) for k in OUT_OF_SCOPE_KW) - - -def get_cairo_now(): - return datetime.now(ZoneInfo("Africa/Cairo")) - - -def parse_time(token: str) -> Optional[str]: - token = norm(token).replace(" ", "") - m = re.match(r"^(\d{1,2})(?::(\d{1,2}))?(ص|م|ظهر)?$", token) - if not m: - return None - h = int(m.group(1)) - mn = int(m.group(2)) if m.group(2) else 0 - suf = m.group(3) - if not (0 <= mn <= 59): - return None - if suf == "ص": - if h == 12: - h = 0 - elif not 1 <= h <= 11: - return None - elif suf in ("م", "ظهر"): - if h != 12 and 1 <= h <= 11: - h += 12 - else: - if h == 24: - h = 0 - elif not 0 <= h <= 23: - return None - return f"{h:02d}:{mn:02d}" - - -def check_open_now(opening_hours_str: Any) -> Optional[int]: - if not opening_hours_str or str(opening_hours_str).strip().lower() in ("", "nan", "none"): - return None - text = norm(opening_hours_str) - if any(k in text for k in ["24", "always", "طول اليوم", "24/7"]): - return 1 - sep = re.search(r"(.+?)\s*-\s*(.+)", text) - if not sep: - return None - t1 = parse_time(sep.group(1).strip()) - t2 = parse_time(sep.group(2).strip()) - if not t1 or not t2: - return None - now_t = f"{get_cairo_now().hour:02d}:{get_cairo_now().minute:02d}" - if t1 <= t2: - return 1 if t1 <= now_t <= t2 else 0 - return 1 if (now_t >= t1 or now_t <= t2) else 0 - - -def haversine(lat1, lon1, lat2, lon2): - r = 6371 - p = math.pi / 180 - a = math.sin((lat2 - lat1) * p / 2) ** 2 + math.cos(lat1 * p) * math.cos(lat2 * p) * math.sin((lon2 - lon1) * p / 2) ** 2 - return 2 * r * math.asin(math.sqrt(a)) - - -def _headers() -> dict: - headers = {"Accept": "application/json"} - if AROUNDU_KEY: - headers["X-API-Key"] = AROUNDU_KEY - return headers - - -def _extract_payload_data(payload): - if isinstance(payload, list): - return payload - if isinstance(payload, dict): - for key in ["data", "results", "items", "places"]: - if isinstance(payload.get(key), list): - return payload[key] - nested = payload.get("data") - if isinstance(nested, dict): - for key in ["data", "results", "items", "places"]: - if isinstance(nested.get(key), list): - return nested[key] - return [] - - -def load_places_from_api() -> pd.DataFrame: - all_rows = [] - skip = 0 - limit = 100 - while True: - url = f"{AROUNDU_BASE}/places" - params = {"skip": skip, "limit": limit} - try: - resp = requests.get(url, headers=_headers(), params=params, timeout=30) - except requests.RequestException as exc: - log.error("Places API network error: %s", exc) - break - if resp.status_code == 401: - log.error("Places API unauthorized. Check X-API-Key secret.") - break - if resp.status_code == 404 and skip == 0: - try: - resp = requests.get(url, headers=_headers(), timeout=30) - except requests.RequestException as exc: - log.error("Places API network error: %s", exc) - break - if resp.status_code != 200: - log.error("Places API error %s: %s", resp.status_code, resp.text[:300]) - break - try: - chunk = _extract_payload_data(resp.json()) - except Exception: - log.error("Places API returned non-JSON response") - break - if not chunk: - break - all_rows.extend(chunk) - if len(chunk) < limit: - break - skip += limit - df = pd.DataFrame(all_rows) - log.info("Loaded %s places from AroundU API", len(df)) - return df - - -def prepare_places_df(df: pd.DataFrame) -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - df = df.copy() - if "lng" in df.columns and "lon" not in df.columns: - df = df.rename(columns={"lng": "lon"}) - required = [ - "id", "place_id", "name", "name_ar", "name_en", "category", "sub_category", - "location", "address", "price_range", "rating", "rating_count", "opening_hours", - "description", "lat", "lon", "phone", "image", "is_favorited", "is_open", - ] - for col in required: - if col not in df.columns: - df[col] = "" - for col in ["lat", "lon", "rating", "rating_count"]: - df[col] = pd.to_numeric(df[col], errors="coerce") - df["rating"] = df["rating"].fillna(0.0).apply(lambda r: round(r / 2, 1) if r > 5 else round(r, 1)) - df["rating_count"] = df["rating_count"].fillna(0).astype(int, errors="ignore") - df["place_id"] = df["place_id"].astype(str).replace({"nan": "", "None": ""}).str.strip() - missing_pid = df["place_id"].eq("") - df.loc[missing_pid, "place_id"] = df.loc[missing_pid, "id"].astype(str) - still_missing = df["place_id"].eq("") | df["place_id"].eq("nan") - df.loc[still_missing, "place_id"] = [f"API{i+1:04d}" for i in range(still_missing.sum())] - text_cols = [ - "id", "place_id", "name", "name_ar", "name_en", "category", "sub_category", "location", - "address", "price_range", "opening_hours", "description", "phone", "image", - ] - for col in text_cols: - df[col] = df[col].fillna("").astype(str) - df["category_norm"] = df["category"].apply(normalize_category) - df["name_clean"] = (df["name"] + " " + df["name_ar"] + " " + df["name_en"]).apply(clean_text) - df["category_clean"] = df["category"].apply(clean_text) - df["sub_category_clean"] = df["sub_category"].apply(clean_text) - df["location_clean"] = df["location"].apply(clean_text) - df["address_clean"] = df["address"].apply(clean_text) - df["price_range_clean"] = df["price_range"].apply(clean_text) - if "search_text_clean" not in df.columns or df["search_text_clean"].astype(str).str.strip().eq("").all(): - df["search_text_clean"] = ( - df["name"].astype(str) + " " + df["name_ar"].astype(str) + " " + df["name_en"].astype(str) + " " + - df["category"].astype(str) + " " + df["sub_category"].astype(str) + " " + - df["location"].astype(str) + " " + df["address"].astype(str) + " " + - df["price_range"].astype(str) + " " + df["description"].astype(str) - ).apply(clean_text) - else: - df["search_text_clean"] = df["search_text_clean"].apply(clean_text) - return df.reset_index(drop=True) - - -def rebuild_dynamic_index(force: bool = True) -> int: - global places_df, corpus_df, corpus_embeddings - raw_df = load_places_from_api() - places_df = prepare_places_df(raw_df) - MENU_CACHE.clear() # menu data may be stale after a places refresh - if places_df.empty: - corpus_df = pd.DataFrame() - corpus_embeddings = None - log.warning("Dynamic semantic index is empty") - return 0 - texts = places_df["search_text_clean"].fillna("").astype(str).tolist() - corpus_embeddings = semantic_model.encode( - texts, - convert_to_tensor=True, - show_progress_bar=False, - batch_size=32, - ) - corpus_df = places_df.copy().reset_index(drop=True) - log.info("Dynamic semantic index rebuilt: %s places", len(corpus_df)) - return len(corpus_df) - - -def apply_keyword_override(text: str) -> Optional[str]: - t = norm(text) - for intent, words in KEYWORD_INTENTS.items(): - for w in words: - wn = norm(w) - if not wn: - continue - if wn == t: - return intent - # Word-boundary match instead of raw substring containment. - # A plain `wn in t` check is catastrophic for short keywords: - # "لا" (deny) was matching inside "لاتيه" and "لاميرا" (a real - # place name!), "اه" (confirm) could match inside many longer - # words. \b in Python's re module works on word characters - # including Arabic letters, so this correctly requires the - # keyword to appear as its own token, not buried inside another word. - if re.search(rf"\b{re.escape(wn)}\b", t): - return intent - if is_out_of_scope(text): - return "out_of_scope" - if any(w in t for w in MENU_WORDS): - return "show_menu" - if any(w in t for w in NEXT_WORDS): - return "show_more" - if any(w in t for w in ["قارن", "مقارنة", "احسن واحد فيهم", "ايه الاحسن", "مين احسن"]): - return "compare_places" - if any(w in t for w in OPEN_WORDS): - cat = infer_category(text) - if cat: - return "open_now" - if any(w in t for w in [ - "مكان هادي", "مكان رايق", "مش زحمه", "مش زحمة", "للمذاكره", "للمذاكرة", "اذاكر", "أذاكر", "شغل", "دراسة", - "عائلات", "عائلي", "للعيله", "للعائلة", "للعيلة", "مع العيلة", "مع العيله", - "خروجات", "خروجه", "خروجة", "اطلع", "أطلع", "اسهر", "أسهر", "للسهر", - "رومانسي", "رومانسى", "شبابي", "شبابى", - ]): - return "recommendation_by_mood" - if any(w in t for w in ["رقم", "عنوان", "فين مكان", "مكانه", "مكانها", "لوكيشن", "مواعيد", "بيفتح"]): - return "place_details" - # Distinguish generic place-type words (مطعم/كافيه/صيدلية/ماركت/سكن) from - # specific food/item words (برجر/شاورما/قهوة...). Both live in - # CATEGORY_KEYWORDS, but only the generic ones should short-circuit to - # nearest_*; specific item words should still flow into search_by_item. - # Without this split, "عايز مطعم كويس" was previously misread by - # extract_item_query() (its trailing adjective "كويس" looked like a - # menu item) and forced into search_by_item instead of nearest_restaurant. - GENERIC_PLACE_WORDS = { - "restaurant": ["مطعم", "مطاعم", "اكل", "أكل", "وجبات", "وجبة", "restaurant", "food"], - "pharmacy": ["صيدليه", "صيدلية", "صيدليات", "صيدله", "pharmacy", "drugstore"], - "cafe": ["كافيه", "كافيهات", "كافية", "كوفي", "كافيتيريا", "cafe"], - "supermarket":["سوبرماركت", "سوبر ماركت", "سوبر", "ماركت", "هايبر", "بقاله", "بقالة", "supermarket", "market"], - "housing": ["سكن", "شقه", "شقة", "شقق", "ايجار", "إيجار", "فندق", "هوستل", "hotel", "apartment", "housing"], - } - item_guess = extract_item_query(text) - # Specific item requests must win before broad category inference. - # Example: "عايزة ايس كوفي" contains "كوفي" but should search the item, - # not list all cafes. - if item_guess and any(w in t for w in ITEM_CUES + sum(ITEM_CATEGORY_HINTS.values(), [])): - return "search_by_item" - - generic_cat = "" - for cat, words in GENERIC_PLACE_WORDS.items(): - if any(norm(w) in t for w in words): - generic_cat = cat - break - if generic_cat: - return { - "restaurant": "nearest_restaurant", - "pharmacy": "nearest_pharmacy", - "cafe": "nearest_cafe", - "supermarket": "nearest_supermarket", - "housing": "housing_search", - }.get(generic_cat) - cat = infer_category(text) - if cat: - return { - "restaurant": "nearest_restaurant", - "pharmacy": "nearest_pharmacy", - "cafe": "nearest_cafe", - "supermarket": "nearest_supermarket", - "housing": "housing_search", - }.get(cat) - return None - -def predict_intent(text: str, threshold: float = INTENT_THRESHOLD) -> dict: - override = apply_keyword_override(text) - if override: - return {"intent": override, "confidence": 1.0, "source": "rules"} - if intent_pipe is None: - return {"intent": "fallback", "confidence": 0.0, "source": "not_loaded"} - try: - pred = intent_pipe(text, truncation=True, max_length=128) - if isinstance(pred, list) and pred and isinstance(pred[0], list): - pred = pred[0] - item = pred[0] if isinstance(pred, list) and pred else pred - label = str(item.get("label", "fallback")) - score = float(item.get("score", 0.0)) - if label.upper().startswith("LABEL_"): - label = "fallback" - if score < threshold: - return {"intent": "fallback", "confidence": round(score, 4), "source": "model_low_conf"} - return {"intent": label, "confidence": round(score, 4), "source": "model"} - except Exception as exc: - log.error("Intent prediction error: %s", exc) - return {"intent": "fallback", "confidence": 0.0, "source": "error"} - - -def _clean_entity_value(value: Any) -> str: - value = str(value or "").replace("##", "") - value = re.sub(r"\s+", " ", value).strip() - return value - - -def _append_entity(entities: dict, key: str, value: str): - value = _clean_entity_value(value) - if not value: - return - value_clean = clean_text(value) - if not value_clean: - return - current = entities.get(key) - if not current: - entities[key] = value_clean - elif value_clean not in current: - entities[key] = f"{current} {value_clean}".strip() - - -def clean_item_query(text: str) -> str: - q = clean_text(text) - remove_words = [ - "عايز", "عايزه", "عايزة", "عاوز", "عاوزه", "عاوزة", "محتاج", "محتاجة", "نفسي", - "في", "فين", "مطعم", "مطاعم", "كافيه", "مكان", "بيعمل", "بتعمل", "عنده", "عندها", - "فيه", "فيها", "بيقدم", "بتقدم", "لو سمحت", "ممكن", "من فضلك", "قريب", "اقرب", - ] - for w in remove_words: - q = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", q) - q = re.sub(r"\s+", " ", q).strip() - words = [w for w in q.split() if clean_text(w) not in NON_ITEM_WORDS] - q = " ".join(words).strip() - if clean_text(q) in NON_ITEM_WORDS: - return "" - return q - - -def extract_item_query(text: str) -> str: - t = norm(text) - known_items = [ - "شاورما", "برجر", "بيتزا", "كريب", "مشويات", "كباب", "كفته", "كفتة", "فراخ", "نص فراخ", - "نص فرخه", "نص فرخة", "فول", "طعميه", "طعمية", "سمك", "كشري", "حواوشي", "فطير", - "ميكس لحوم", "مكس لحوم", "لحوم", - "لاتيه", "قهوه", "قهوة", "ايس كوفي", "ايس كوفى", "ايس كافي", "آيس كوفي", "ice coffee", - "شيبسي", "بيبسي", "دواء", "دوا", "علاج", "ادويه", "أدوية", - "وافل", "ايس كريم", "آيس كريم", "حلويات" - ] - found = [item for item in known_items if norm(item) in t] - if found: - return max(found, key=len) - cleaned = clean_item_query(text) - if not cleaned or clean_text(cleaned) in NON_ITEM_WORDS: - return "" - # Fuzzy typo correction: common typing mistakes (missing letter, doubled - # letter, swapped diacritic-adjacent letters) mean a word like "شورما" - # (missing alef from "شاورما") or "بتزا" (missing ي) won't substring-match - # any known_items entry above, so the user's literal (mis-typed) text - # would be searched verbatim and very likely return zero results even - # though the intended item clearly exists in the menu. Compare each - # word in the cleaned text against known_items by character similarity - # and snap to the closest match if it's close enough to be confident. - cleaned_words = cleaned.split() - for word in cleaned_words: - if len(word) < 3: - continue - best_match, best_ratio = None, 0.0 - for item in known_items: - ratio = difflib.SequenceMatcher(None, norm(word), norm(item)).ratio() - if ratio > best_ratio: - best_ratio, best_match = ratio, item - if best_match and best_ratio >= 0.78: - return best_match - return cleaned - - - - -def is_generic_category_item(value: str) -> bool: - q = clean_text(value) - generic = { - "مطعم", "مطاعم", "اكل", "أكل", "مكان", - "كافيه", "كافيهات", "قهوه", "قهوة", "كوفي", - "صيدليه", "صيدلية", "صيدليات", "صيدله", - "ماركت", "سوبر", "سوبرماركت", "سوبر ماركت", - } - return q in {clean_text(x) for x in generic} - -def extract_menu_place_name(text: str) -> str: - t = clean_text(text) - for w in ["هات", "ابعت", "وريني", "اعرض", "منيو", "مينيو", "menu", "بتاع", "قائمة"]: - t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t) - return re.sub(r"\s+", " ", t).strip() - - -def extract_entities(text: str, min_score: float = 0.35) -> dict: - entities = {} - if ner_pipe is not None: - try: - raw = ner_pipe(text) - for item in raw: - label = str(item.get("entity_group") or item.get("entity") or "").upper().replace("B-", "").replace("I-", "") - value = _clean_entity_value(item.get("word", "")) - score = float(item.get("score", 1.0)) - if score < min_score or len(value) < 2: - continue - mapped = { - "PLACE_NAME": "place_name", - "ITEM_QUERY": "item_query", - "LOCATION": "location", - "PRICE_RANGE": "price_range", - "PLACE_TYPE": "category", - "PLACE_MOOD": "place_mood", - "TIME_CONTEXT": "time_context", - "COMPARISON_CRITERIA": "comparison_criteria", - "HOUSING_TYPE": "housing_type", - "FURNISHING": "furnishing", - "ROOM_COUNT": "room_count", - }.get(label, label.lower()) - _append_entity(entities, mapped, value) - except Exception as exc: - log.warning("NER extraction error: %s", exc) - cat = infer_category(text, entities=entities) - if cat: - entities["category"] = cat - if "item_query" not in entities: - item = extract_item_query(text) - cat = infer_category(text) - # extract_item_query() can return a leftover adjective (e.g. "كويس", - # "نضيف") when the sentence is really just "عايز مطعم كويس" — a - # generic category request, not a specific food/drink ask. Only - # trust the fallback item_query if it actually matches one of the - # known food/drink keywords used elsewhere (ITEM_CATEGORY_HINTS), - # otherwise a plain category search would get wrongly redirected - # into search_by_item with a bogus item and return no_result. - known_item_words = set() - for words in ITEM_CATEGORY_HINTS.values(): - known_item_words.update(norm(w) for w in words) - item_is_real = item and any(norm(w) in norm(item) or norm(item) in norm(w) for w in known_item_words) - if item_is_real and (cat in {"restaurant", "cafe", "pharmacy", "supermarket"} or any(norm(x) in norm(text) for x in ["اكل", "أكل", "جعان", "نفسي", "شاورما", "برجر", "بيتزا", "كريب", "اشتري", "محتاج", "عنده", "عندها"])): - entities["item_query"] = item - if "place_name" not in entities: - name_guess = extract_place_name_from_text(text) - if name_guess: - entities["place_name"] = name_guess - return entities - - -def extract_place_name_from_text(text: str) -> str: - t = clean_text(text) - original = t - stop_phrases = [ - "فين", "مكان", "مكانه", "مكانها", "عنوان", "عنوانه", "عنوانها", "لوكيشن", "رقم", "تليفون", - "مطعم", "صيدليه", "صيدلية", "صديليه", "كافيه", "ماركت", "سوبر", "سوبرماركت", "هات", "منيو", "عايز", "عايزة", - "عايزه", "عاوزه", "عاوز", "اروح", "ازاي", "قريب", "اقرب", "مفتوح", "فاتح", "دلوقتي", "في", "من", "عند", - "رقمه", "رقمها", "تليفونه", "تليفونها", "ايه", "إيه", "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "توب", "التوب", - "طب", "طيب", "تمام", "ماشي", "كام", "بكام", "قد ايه", "مين", - "مواعيد", "معاد", "ميعاد", "بيفتح", "بتفتح", "بيقفل", "بتقفل", "امتى", "امتي", "شغال", "شغاله", "شغالة", - "الصبح", "بالليل", "بالنهار", "النهارده", "بكرة", "بكره", - ] - # Arabic words frequently carry attached possessive/verb suffixes - # (e.g. "مواعيده" = "مواعيد" + "ه", "بيفتحوا" = "بيفتح" + "وا") AND a - # leading "و" (conjunction "and" — "وعنوانه", "ورقمه", "ومواعيده" are - # extremely common in spoken Egyptian Arabic, e.g. "طب وعنوانه فين؟"). - # A plain \bword\b match misses both, since the prefix/suffix breaks - # the word boundary. Allow an optional leading "و" and a short trailing - # suffix so these collapse to nothing instead of leaving a fake place - # name like "وعنوانه" behind. - for w in stop_phrases: - cw = clean_text(w) - t = re.sub(rf"\bو?{re.escape(cw)}[ههاويوا]{{0,3}}\b", " ", t) - t = re.sub(r"\s+", " ", t).strip() - if not t or len(t) < 2: - return "" - if t in ["هنا", "هناك", "ده", "دي", "هو", "هي"]: - return "" - # English place names must be checked BEFORE the infer_category - # short-circuit below. Many real venue names legitimately contain a - # category word inside them (e.g. "Grand Cafe", "City Market", "Ouzi - # Restaurant") — if we ran the category check first, infer_category() - # would match "cafe"/"market"/"restaurant" and wrongly discard the - # whole name as a generic category mention instead of a specific place. - if re.search(r"[a-zA-Z]", t) and len(t.split()) <= 5: - return t - if infer_category(t) and len(t.split()) <= 2: - return "" - if any(w in original for w in ["فين", "مكان", "عنوان", "لوكيشن", "منيو", "رقم", "مواعيد", "بيفتح", "بتفتح"]) and len(t.split()) <= 5: - return t - return "" - - - -def has_any(text: str, words: list) -> bool: - t = norm(text) - return any(norm(w) in t for w in words if norm(w)) - - -def intended_item_category(item_query: str) -> str: - q = norm(item_query) - if not q: - return "" - for cat, items in ITEM_CATEGORY_HINTS.items(): - if any(norm(item) in q for item in items): - return cat - return "" - - -def item_category_conflict(item_query: str, category: str) -> Optional[str]: - intended = intended_item_category(item_query) - category = normalize_category(category) - if intended and category and intended != category: - return intended - return None - - -def item_matches_place(place: dict, item_query: str, use_menu: bool = True) -> bool: - item = clean_text(item_query) - if not item: - return True - text_blob = clean_text(" ".join([ - str(place.get("name", "")), str(place.get("name_ar", "")), str(place.get("name_en", "")), - str(place.get("category", "")), str(place.get("sub_category", "")), str(place.get("description", "")), - str(place.get("search_text_clean", "")), - ])) - if item in text_blob: - return True - if use_menu: - try: - for m in fetch_menu(place): - m_blob = clean_text(" ".join(str(m.get(k, "")) for k in ["name", "name_ar", "name_en", "title", "description", "category"])) - if item in m_blob: - return True - except Exception: - return False - return False - - -def is_near_query(text: str) -> bool: - return has_any(text, NEAR_WORDS) - - -def is_best_query(text: str, intent: str = "") -> bool: - return has_any(text, BEST_WORDS) or intent in {"best_of", "recommend_place"} - - -def is_best_near_query(text: str, intent: str = "") -> bool: - return is_best_query(text, intent) and is_near_query(text) - - -def compare_place_names(text: str) -> list: - t = clean_text(text) - for w in ["قارن", "قارني", "مقارنة", "بين", "ما بين", "مين احسن", "احسن"]: - t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t) - parts = [p.strip() for p in re.split(r"\s+و\s+|,|،|/|\\|\s+ولا\s+", t) if p.strip()] - cleaned = [] - for p in parts: - p = extract_place_name_from_text(p) or p - if p and p not in cleaned and not infer_category(p): - cleaned.append(p) - return cleaned[:4] - - -def clear_context_on_category_change(session: "Session", new_category: str, new_location: str = "") -> None: - old_category = normalize_category(session.context_slots.get("category", "")) - new_category = normalize_category(new_category) - if new_category and old_category and new_category != old_category: - keep_location = new_location or session.context_slots.get("location", "") - session.context_slots = {} - if keep_location: - session.context_slots["location"] = keep_location - -def semantic_candidates(query: str, top_k: int = SEMANTIC_TOP_K) -> pd.DataFrame: - if corpus_df is None or corpus_df.empty or corpus_embeddings is None: - return pd.DataFrame() - q_emb = semantic_model.encode(clean_text(query), convert_to_tensor=True) - scores = util.cos_sim(q_emb, corpus_embeddings)[0] - k = min(top_k, len(corpus_df)) - top = torch.topk(scores, k=k) - result = corpus_df.iloc[top.indices.cpu().numpy()].copy() - result["semantic_score"] = top.values.cpu().numpy() - return result.reset_index(drop=True) - - -def expand_place_name_queries(place_name: str) -> list: - q = clean_text(place_name) - q_latin = ar_to_latin_guess(place_name) - queries = [] - if q: - queries.append(q) - if q_latin and q_latin != q: - queries.append(q_latin) - # Some manual_common mappings intentionally return multiple words such - # as "bolivar boulevard". Add each token/group so fuzzy name search - # can match either spelling in the DB. - for part in re.split(r"\s{2,}|/|,|،", q_latin): - part = clean_text(part) - if part and part != q_latin: - queries.append(part) - for alias, values in PLACE_NAME_ALIASES.items(): - a = clean_text(alias) - a_latin = ar_to_latin_guess(alias) - if q == a or 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)): - queries.extend(clean_text(v) for v in values) - # remove duplicates but preserve order - out = [] - for item in queries: - if item and item not in out: - out.append(item) - return out - - -def _name_similarity(query: str, names: str) -> float: - q = clean_text(query) - n = clean_text(names) - if not q or not n: - return 0.0 - q_words = [w for w in q.split() if len(w) > 1] - if q == n or q in n or n in q: - return 1.0 - if q_words and all(w in n for w in q_words): - return 0.92 - common = sum(1 for w in q_words if w in n) - token_score = 0.45 + 0.35 * common / max(len(q_words), 1) if common else 0.0 - fuzzy_score = difflib.SequenceMatcher(None, q.replace(" ", ""), n.replace(" ", "")).ratio() - return max(token_score, fuzzy_score * 0.85) - - -def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.DataFrame: - if places_df is None or places_df.empty or not place_name: - return pd.DataFrame() - queries = expand_place_name_queries(place_name) - base = places_df.copy() - - def run_search(df: pd.DataFrame) -> pd.DataFrame: - if df.empty: - return df - def score(row): - names = clean_text(" ".join([str(row.get("name", "")), str(row.get("name_ar", "")), str(row.get("name_en", ""))])) - return max((_name_similarity(q, names) for q in queries), default=0.0) - out = df.copy() - out["name_score"] = out.apply(score, axis=1) - out = out[out["name_score"] >= 0.42].sort_values("name_score", ascending=False) - if "semantic_score" not in out.columns: - out["semantic_score"] = out["name_score"] - return out.head(top_k).reset_index(drop=True) - - # If the user explicitly supplied a category, try it first. If not found, - # fall back to all categories so old context never hides a real place name - # (e.g. previous query was pharmacy, current query is "بوليفار"). - if category: - filtered = base[base["category_norm"].apply(lambda c: category_matches(c, category))] - hit = run_search(filtered) - if not hit.empty: - return hit - return run_search(base) - - -def apply_filters(df: pd.DataFrame, category: str = "", location: str = "", price_range: str = "", open_now_only: bool = False) -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - f = df.copy() - if category and "category_norm" in f.columns: - f = f[f["category_norm"].apply(lambda c: category_matches(c, category))] - if location and not f.empty: - loc = clean_text(location) - parts = [p for p in loc.split() if len(p) > 1] - if parts: - mask = f.apply( - lambda r: any(p in clean_text(str(r.get("location", "")) + " " + str(r.get("address", ""))) for p in parts), - axis=1, - ) - loc_filtered = f[mask] - if not loc_filtered.empty: - f = loc_filtered - else: - return pd.DataFrame() - if price_range and not f.empty: - pr = clean_text(price_range) - mask = f["price_range_clean"].astype(str).str.contains(re.escape(pr), na=False) - if mask.any(): - f = f[mask] - if not f.empty: - f["open_now"] = f["opening_hours"].apply(check_open_now) - f["rating_norm"] = pd.to_numeric(f.get("rating", 0), errors="coerce").fillna(0.0) - f["rating_score"] = f["rating_norm"] / 5.0 - f["open_score"] = f["open_now"].apply(lambda x: 1.0 if x == 1 else (0.5 if x is None else 0.1)) - if open_now_only and not f.empty: - opened = f[f["open_now"] == 1] - if not opened.empty: - f = opened - return f.reset_index(drop=True) - - -def rank_places(df: pd.DataFrame, query: str, user_lat=None, user_lon=None, intent: str = "") -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - f = df.copy() - near = is_near_query(query) - best = is_best_query(query, intent) - if user_lat is not None and user_lon is not None and "lat" in f.columns and "lon" in f.columns: - def dist(row): - try: - lat = float(row.get("lat")) - lon = float(row.get("lon")) - if np.isnan(lat) or np.isnan(lon): - return None - return haversine(float(user_lat), float(user_lon), lat, lon) - except Exception: - return None - f["distance_km"] = f.apply(dist, axis=1) - else: - f["distance_km"] = None - valid = f["distance_km"].dropna() if "distance_km" in f.columns else pd.Series(dtype=float) - mx = valid.max() if not valid.empty else 1.0 - f["distance_score"] = f["distance_km"].apply(lambda d: 1 - d / (mx + 1) if d is not None and not pd.isna(d) else 0.5) - for col, default in [("semantic_score", 0.0), ("rating_score", 0.0), ("open_score", 0.5), ("name_score", 0.0), ("rating_norm", 0.0), ("rating_count", 0.0)]: - if col not in f.columns: - f[col] = default - f[col] = pd.to_numeric(f[col], errors="coerce").fillna(default) - if best and near and user_lat is not None and user_lon is not None: - f["final_score"] = 0.70 * f["rating_score"] + 0.30 * f["distance_score"] - return f.sort_values(["final_score", "rating_count", "semantic_score"], ascending=[False, False, False]).reset_index(drop=True) - if near and user_lat is not None and user_lon is not None: - return f.sort_values(["distance_km", "rating_norm"], ascending=[True, False], na_position="last").reset_index(drop=True) - if best: - return f.sort_values(["rating_norm", "rating_count", "semantic_score"], ascending=[False, False, False]).reset_index(drop=True) - if near and user_lat is None: - return f.sort_values(["semantic_score", "rating_norm"], ascending=[False, False]).reset_index(drop=True) - # "Auto nearest": a plain category request ("عايزة مطعم", "عايز كافيه") - # with NO explicit "أحسن"/"best" wording but WITH a device location - # should still sort strictly by distance, matching what users actually - # expect ("عايزة مطعم" + my location = nearest restaurants first). Without - # this branch, such requests fell through to the generic weighted-score - # path below, where a much-closer low-rated place could rank behind a - # far-away high-rated one — i.e. distance was only ~15% of the score, - # not the dominant factor the user asked for. - if not best and user_lat is not None and user_lon is not None: - return f.sort_values(["distance_km", "rating_norm"], ascending=[True, False], na_position="last").reset_index(drop=True) - if has_any(query, ["كويس", "قريب", "محترم", "نضيف"]) and user_lat is not None and user_lon is not None: - f["final_score"] = 0.55 * f["rating_score"] + 0.30 * f["distance_score"] + 0.15 * f["semantic_score"] - else: - f["final_score"] = 0.45 * f["semantic_score"] + 0.25 * f["rating_score"] + 0.15 * f["distance_score"] + 0.10 * f["open_score"] + 0.05 * f["name_score"] - return f.sort_values("final_score", ascending=False).reset_index(drop=True) - -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: - category = normalize_category(category) - intended_cat = intended_item_category(item_query) - if item_query and not category: - # Generic pharmacy/supermarket requests should become category searches. - # Food/drink items stay flexible enough to match restaurant & café data. - if intended_cat in {"pharmacy", "supermarket"}: - category = intended_cat - elif intended_cat == "restaurant": - category = "restaurant" - else: - category = "" - if item_category_conflict(item_query, category): - return pd.DataFrame() - if place_name: - named = name_search(place_name, category=category, top_k=10) - if named.empty: - return pd.DataFrame() - filtered = apply_filters(named, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - if item_query: - base = places_df.copy() if places_df is not None else pd.DataFrame() - # For item search, don't over-restrict drinks like ice coffee to cafes only; - # some restaurants in the DB also have drinks in their menu. Pharmacy and - # supermarket intents remain strict because "دوا" and "شيبسي" are category-like. - item_filter_category = "" if (category == "cafe" and intended_item_category(item_query) == "cafe") else category - base = apply_filters(base, category=item_filter_category, location=location, price_range=price_range, open_now_only=open_now_only) - if base.empty: - return pd.DataFrame() - rows = [] - for _, row in base.iterrows(): - place = row_to_dict(row) - if item_matches_place(place, item_query, use_menu=True): - rows.append(place) - if not rows: - return pd.DataFrame() - out = pd.DataFrame(rows) - if "semantic_score" not in out.columns: - out["semantic_score"] = 0.80 - post_category = "" if (category == "cafe" and intended_item_category(item_query) == "cafe") else category - out = apply_filters(out, category=post_category, location="", price_range=price_range, open_now_only=open_now_only) - return rank_places(out, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - # For broad category requests ("عايز كافيه", "احسن مطعم"), use the live DB directly. - # Semantic threshold can wrongly hide valid category results, especially mixed categories like restaurant & café. - if category and places_df is not None and not places_df.empty: - base = apply_filters(places_df.copy(), category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if not base.empty: - if "semantic_score" not in base.columns: - base["semantic_score"] = 0.80 - return rank_places(base, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - - # Pure category queries like "عايزه كافيه" or "احسن مطعم" should not be killed by semantic threshold. - if category and not item_query and not place_name: - base = places_df.copy() if places_df is not None else pd.DataFrame() - filtered = apply_filters(base, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if not filtered.empty: - if "semantic_score" not in filtered.columns: - filtered["semantic_score"] = 0.75 - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - - candidates = semantic_candidates(query, top_k=SEMANTIC_TOP_K) - if candidates.empty: - return pd.DataFrame() - filtered = apply_filters(candidates, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if filtered.empty: - return pd.DataFrame() - filtered = filtered[pd.to_numeric(filtered.get("semantic_score", 0), errors="coerce").fillna(0) >= SEMANTIC_MIN_SCORE] - if filtered.empty: - return pd.DataFrame() - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - -def format_place_line(place: dict) -> str: - name = place.get("name") or place.get("name_ar") or "المكان" - loc = place.get("location") or place.get("address") or "بني سويف" - rating = place.get("rating_norm", place.get("rating", 0)) - dist = place.get("distance_km") - rating_txt = f" — ⭐ {rating}" if rating else "" - open_now = place.get("open_now") - open_txt = " — 🟢 مفتوح" if open_now == 1 else (" — 🔴 مغلق" if open_now == 0 else "") - dist_txt = "" - try: - if dist is not None and not pd.isna(dist): - dist_txt = f" — 📍 {float(dist):.1f} كم" - except Exception: - dist_txt = "" - return f"{name} في {loc}{rating_txt}{open_txt}{dist_txt}" - - -def _dynamic_reply(kind: str, **kwargs) -> str: - templates = DYNAMIC_TEMPLATES.get(kind) or DYNAMIC_TEMPLATES["category"] - cat = normalize_category(kwargs.get("category", "")) - data = { - "cat_ar": CAT_AR.get(cat, "أماكن"), - "cat_single": CAT_SINGLE.get(cat, "مكان"), - "item": kwargs.get("item_query") or kwargs.get("item") or "الطلب ده", - "location": kwargs.get("location") or "المنطقة دي", - "best_name": (kwargs.get("best_place") or {}).get("name") or "أول اختيار", - } - try: - return random.choice(templates).format(**data) - except Exception: - return random.choice(templates) - - -RELATED_ITEM_GROUPS = [ - {"وافل", "كريب", "حلويات", "ايس كريم", "آيس كريم", "كنافة", "بسبوسة"}, - {"شاورما", "برجر", "كباب", "كفته", "كفتة", "فراخ", "مشويات"}, - {"بيتزا", "باستا", "مكرونة", "ايطالي", "إيطالي"}, - {"قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "نسكافيه", "شاي"}, - {"عصير", "سموزي", "موهيتو", "مشروبات بارده", "مشروبات باردة"}, -] - -def find_related_item_suggestion(item_query: str, category: str) -> str: - """ - When a requested item has zero results, scan the live places data for - a related/similar item that DOES exist (e.g. "وافل" -> "حلويات"), - instead of just telling the user nothing was found. Returns a short - Arabic phrase naming the related item group found, or "" if none. - """ - if not item_query or places_df is None or places_df.empty: - return "" - iq = norm(item_query) - related_words = set() - for group in RELATED_ITEM_GROUPS: - if any(norm(w) in iq or iq in norm(w) for w in group): - related_words = {w for w in group if norm(w) != iq} - break - if not related_words: - return "" - haystack_col = places_df.get("search_text_clean") - if haystack_col is None: - return "" - for word in related_words: - wn = norm(word) - mask = haystack_col.fillna("").astype(str).apply(lambda s: wn in norm(s)) - if mask.any(): - return word - return "" - - -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: - category = normalize_category(category) - if not results: - if place_name: - return f"مش لاقي {CAT_SINGLE.get(category, 'مكان')} باسم {place_name} حاليًا 😔\nممكن تكتبه بطريقة تانية؟" - if item_query: - return f"مش لاقي {CAT_SINGLE.get(category or 'restaurant', 'مكان')} بيقدم {item_query} في الداتا الحالية 😔\nجرب صنف تاني أو منطقة تانية." - if location and category: - return f"مفيش {CAT_AR.get(category, 'أماكن')} متاحة حاليًا في {location} 😔\nتحب أدور في منطقة تانية؟" - if open_now_only and category: - return f"مش لاقي {CAT_AR.get(category, 'أماكن')} مفتوحة دلوقتي 😔\nأقدر أعرضلك الموجود بس مش مؤكد إنه مفتوح." - return _dynamic_reply("fallback") - if related_item_used: - # These are REAL cards for the related item (e.g. حلويات instead of - # the unavailable وافل) — say so explicitly instead of the generic - # category header, so the text matches what's actually on screen. - return f"ملقتش {CAT_SINGLE.get(category or 'restaurant', 'مكان')} بيقدم {item_query}، لكن لقيت أماكن بتقدم {related_item_used} ممكن تعجبك 👇" - if soft_reason == "open": - header = _dynamic_reply("soft_open", category=category) - elif soft_reason == "near_item": - header = _dynamic_reply("soft_near_item", category=category or "restaurant", item_query=item_query) - elif soft_reason == "area": - header = _dynamic_reply("area_fallback", category=category, location=location) - # The area-fallback results come from dropping the location filter. - # If the original request also asked for open_now and that already - # failed before we dropped location, these alternatives are not - # guaranteed to be open either — say so explicitly instead of - # presenting them as a plain location-only fallback. - if open_uncertain: - header += "\nوبرضو حالة الفتح دلوقتي مش مؤكدة لكل الأماكن دي، يفضل تتأكد بمكالمة قبل ما تروح 📞" - elif item_query: - header = _dynamic_reply("item", category=category or "restaurant", item_query=item_query) - elif is_best_near_query(query, intent): - header = _dynamic_reply("best_near", category=category, best_place=results[0]) - elif is_near_query(query) and user_has_location: - header = _dynamic_reply("nearest", category=category, best_place=results[0]) - elif is_near_query(query) and not user_has_location: - header = _dynamic_reply("near_no_location", category=category, best_place=results[0]) - elif is_best_query(query, intent): - header = _dynamic_reply("best", category=category, best_place=results[0]) - elif open_now_only: - header = _dynamic_reply("open", category=category, best_place=results[0]) - elif len(results) == 1: - header = _dynamic_reply("one", category=category, best_place=results[0]) - else: - header = _dynamic_reply("category", category=category, best_place=results[0]) - if len(results) > MAX_CARDS: - header += "\n\nفي أماكن تانية كمان، اكتبي «كمان» لو عايزاهم." - return header - -def handle_detail(text: str, place: Optional[dict]) -> str: - if not place: - return "تقصد أنهي مكان؟ اكتب اسم المكان أو اسألني الأول عن مطعم/صيدلية/كافيه. 😊" - t = norm(text) - name = place.get("name") or place.get("name_ar") or "المكان" - if any(w in t for w in ["رقم", "تليفون", "تلفون", "phone", "اتصل"]): - phone = place.get("phone") or "" - return f"📞 {name}: {phone}" if phone else f"��� الرقم غير متاح لـ {name} حاليًا." - if any(w in t for w in ["عنوان", "فين", "مكان", "لوكيشن", "الموقع", "ازاي اروح"]): - addr = place.get("address") or place.get("location") or "العنوان غير متاح" - lat = place.get("lat") - lon = place.get("lon") - maps = f"\n🗺️ https://maps.google.com/?q={lat},{lon}" if lat not in (None, "", np.nan) and lon not in (None, "", np.nan) else "" - return f"📍 {name}: {addr}{maps}" - if any(w in t for w in ["مواعيد", "بيفتح", "بتفتح", "امتى", "امتي"]): - hours = place.get("opening_hours") or "" - status = check_open_now(hours) - status_txt = "\n🟢 مفتوح دلوقتي" if status == 1 else ("\n🔴 مغلق دلوقتي" if status == 0 else "") - return f"🕐 {name}: {hours or 'المواعيد غير متاحة'}{status_txt}" - if any(w in t for w in ["تقييم", "نجمة", "rating"]): - return f"⭐ {name}: {place.get('rating_norm', place.get('rating', 0)) or 'التقييم غير متاح'}" - if any(w in t for w in ["سعر", "بكام", "غالي", "رخيص"]): - return f"💰 {name}: {place.get('price_range') or 'السعر غير متاح'}" - return format_place_line(place) - - -def fetch_menu(place: dict) -> list: - place_id = str(place.get("id") or place.get("place_id") or "") - if not place_id: - return [] - if place_id in MENU_CACHE: - return MENU_CACHE[place_id] - endpoints = [ - f"{AROUNDU_BASE}/places/{place_id}/menu", - f"{AROUNDU_BASE.replace('/api/v1/ai/data', '')}/api/mobile/places/{place_id}/menu", - ] - for url in endpoints: - try: - resp = requests.get(url, headers=_headers(), timeout=20) - if resp.status_code != 200: - continue - items = _extract_payload_data(resp.json()) - if items: - MENU_CACHE[place_id] = items - return items - except Exception: - continue - MENU_CACHE[place_id] = [] - return [] - - -def detect_ref_type(text: str) -> str: - t = norm(text) - if any(w in t for w in NEXT_WORDS): - return "next" - if any(w in t for w in DETAIL_WORDS): - # "فين أقرب كافيه" contains "فين" (a DETAIL_WORD) but is clearly a - # brand-new category search, not a follow-up about the place - # already in context. Only treat it as "detail" if the sentence - # doesn't also introduce a new category/proximity request. - if any(w in t for w in NEW_SEARCH_SIGNAL_WORDS): - return "new" - return "detail" - if any(w in t for w in REF_WORDS): - return "reference" - return "new" - - -class Session: - def __init__(self, sid="default"): - self.sid = sid - self.last_active = time.time() - self.history = [] - self.last_intent = None - self.last_entities = {} - self.last_place = None - self.last_results = [] - self.result_pointer = 0 - self.context_slots = {} - self.turns = 0 - - def add(self, user, bot, intent, entities, place, results): - self.last_active = time.time() - self.history.append({"turn": self.turns, "user": user, "bot": bot, "intent": intent, "entities": entities}) - if len(self.history) > 10: - self.history = self.history[-10:] - if intent and intent not in NO_CARD_INTENTS and intent not in {"no_result", "out_of_scope"}: - self.last_intent = intent - self.last_entities = entities or {} - if place: - self.last_place = place - if results: - self.last_results = results - # First response shows MAX_CARDS cards; "كمان" starts after them. - self.result_pointer = min(MAX_CARDS, len(results)) - for key in ["category", "location", "price_range", "item_query", "place_name"]: - if entities and entities.get(key): - self.context_slots[key] = entities[key] - self.turns += 1 - - def merge(self, new_entities): - merged = dict(self.context_slots) - for k, v in (new_entities or {}).items(): - if v: - merged[k] = v - return merged - - -def row_to_dict(row) -> dict: - if isinstance(row, dict): - return row - if hasattr(row, "to_dict"): - d = row.to_dict() - else: - d = dict(row) - clean = {} - for k, v in d.items(): - if isinstance(v, (np.integer, np.floating)): - v = v.item() - if pd.isna(v) if not isinstance(v, (list, dict, tuple)) else False: - v = None - clean[k] = v - return clean - - -def looks_like_bare_place_name(text: str) -> bool: - """True when the user likely typed only a venue name, not a product/category request.""" - t = norm(text) - if not t: - return False - words = t.split() - if len(words) > 5: - return False - # If user uses verbs like عايز/اشتري, this is probably an item/category request, not a bare name. - if any(norm(w) in t for w in ITEM_CUES + ["اشتري", "اشتريه", "عايزه", "عايزة", "محتاجه", "محتاجة"]): - return False - # Pure generic category words are not place names. - if infer_category(t) and len(words) <= 2 and not re.search(r"[a-zA-Z]", text): - # Exception: known Arabic aliases like صن شاين / بوليفار / لاميرا are valid names. - if clean_text(text) not in {clean_text(k) for k in PLACE_NAME_ALIASES}: - return False - return True - - -def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict: - text = str(text or "").strip() - if not text: - return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} - - greeting_key = norm(text) - if greeting_key in {norm(k) for k in EXACT_GREETING_REPLIES}: - reply = EXACT_GREETING_REPLIES.get("السلام عليكم") if "السلام" in greeting_key else EXACT_GREETING_REPLIES.get("سلام عليكم") - session.add(text, reply, "greeting", {}, None, []) - return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} - - # Very common real use: user types only the place name, possibly in Arabic - # while DB has English only ("لاميرا", "بوليفار", "صن شاين"). Do name - # search before intent/NER so it doesn't get misread as fallback or item_query. - if looks_like_bare_place_name(text): - direct_hits = name_search(text, top_k=8) - if not direct_hits.empty and "name_score" in direct_hits.columns: - direct_hits = direct_hits[pd.to_numeric(direct_hits["name_score"], errors="coerce").fillna(0) >= 0.65] - if not direct_hits.empty: - direct_results = [row_to_dict(r) for _, r in direct_hits.iterrows()] - best_direct = direct_results[0] - reply = build_response(direct_results, "place_details", place_name=text, query=text) - session.add(text, reply, "place_details", {"place_name": clean_text(text)}, best_direct, direct_results) - return {"reply": reply, "intent": "place_details", "confidence": 1.0, "entities": {"place_name": clean_text(text)}, "best_place": best_direct, "all_results": direct_results} - - ref_type = detect_ref_type(text) - if ref_type == "next" and session.last_results: - start = int(session.result_pointer or 0) - if start >= len(session.last_results): - reply = "دي كانت كل النتائج المتاحة حاليًا 😊\nلو حابب، جرّب منطقة تانية أو نوع تاني." - session.add(text, reply, "show_more", session.last_entities, session.last_place, session.last_results) - session.result_pointer = len(session.last_results) - return {"reply": reply, "intent": "show_more", "confidence": 1.0, "entities": session.last_entities, "best_place": session.last_place, "all_results": []} - end = min(start + MAX_CARDS, len(session.last_results)) - batch = session.last_results[start:end] - session.result_pointer = end - place = batch[0] if batch else session.last_place - reply = "دي أماكن تانية كمان 👇" - if session.result_pointer < len(session.last_results): - reply += "\nوفيه كمان لو حبيتي." - else: - reply += "\nدي آخر الأماكن المتاحة عندي حاليًا." - session.add(text, reply, session.last_intent or "show_more", session.last_entities, place, session.last_results) - # Session.add() resets result_pointer to MAX_CARDS when results are passed. - # Preserve the real pagination offset so the next "كمان" returns the next batch. - session.result_pointer = end - return {"reply": reply, "intent": "show_more", "confidence": 1.0, "entities": session.last_entities, "best_place": place, "all_results": batch} - - if ref_type == "detail" and session.last_place and not extract_place_name_from_text(text): - reply = handle_detail(text, session.last_place) - session.add(text, reply, "place_details", session.last_entities, session.last_place, session.last_results) - return {"reply": reply, "intent": "place_details", "confidence": 1.0, "entities": session.last_entities, "best_place": session.last_place, "all_results": [session.last_place]} - - intent_info = predict_intent(text) - intent = intent_info["intent"] - confidence = intent_info["confidence"] - entities = extract_entities(text) - if intent == "place_details" and not session.last_place and not entities.get("place_name"): - reply = "تقصد رقم أو عنوان أنهي مكان؟ اكتب اسم المكان الأول 😊" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - # NER-derived category (entities.get("category")) is more precise than the - # generic keyword scan in infer_category(), since it comes from the - # trained PLACE_TYPE entity. Only fall back to infer_category() when NER - # found nothing, instead of letting the keyword scan overwrite it. - category = entities.get("category") or infer_category(text, intent, entities) - if category: - entities["category"] = category - location_from_text = entities.get("location", "") - clear_context_on_category_change(session, category, location_from_text) - - if (intent in {"best_of", "sort_results"} or has_any(text, BEST_WORDS)) and not category and not session.context_slots.get("category"): - reply = "أحسن إيه بالظبط؟ مطعم ولا كافيه ولا صيدلية ولا ماركت؟ 😊" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - - if intent in {"greeting", "thanks", "goodbye", "confirm", "deny", "fallback", "out_of_scope"}: - # Before giving up with a generic fallback/out_of_scope reply, check - # whether the message is actually just a bare place name ("لاميرا", - # "on public", "سلطان الشام"). The intent classifier has very little - # signal to work with on a 1-3 word input with no verb or category - # keyword, so it often mis-routes these to fallback/out_of_scope. - # Typing just a place name is one of the most common real-world - # search patterns, so we try a direct name_search before bailing out. - candidate_name = entities.get("place_name") or extract_place_name_from_text(text) - if intent != "out_of_scope" and candidate_name and len(candidate_name) >= 2: - named_df = name_search(candidate_name, top_k=5) - if not named_df.empty: - named_results = [row_to_dict(r) for _, r in named_df.iterrows()] - best = named_results[0] - reply = build_response(named_results, "place_details", place_name=candidate_name, query=text) - session.add(text, reply, "place_details", entities, best, named_results) - return {"reply": reply, "intent": "place_details", "confidence": confidence, "entities": entities, "best_place": best, "all_results": named_results} - replies = { - "greeting": "وعليكم السلام ورحمة الله وبركاته 😊 محتاج إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟", - "thanks": "العفو 😊 في حاجة تانية أساعدك فيها؟", - "goodbye": "مع السلامة 👋 أي وقت تحتاج مكان في بني سويف أنا موجود.", - "confirm": "تمام 😊 محتاج إيه تاني؟", - "deny": "تمام، قولي قصدك إيه بالظبط وأنا أظبطهولك 😊", - "out_of_scope": "أنا مخصص لمساعدة أهل وزوار بني سويف في الأماكن والخدمات زي المطاعم والكافيهات والصيدليات والماركت والسكن 😊", - "fallback": _dynamic_reply("fallback"), - } - reply = replies[intent] - session.add(text, reply, intent, entities, None, []) - return {"reply": reply, "intent": intent, "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - - if intent == "compare_places": - names = compare_place_names(text) - if len(names) < 2: - reply = "اكتب اسمين عشان أقارن بينهم 😊 مثال: قارن بين أريكا كافيه ولاميرا" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - found, missing = [], [] - for name in names: - hits = name_search(name, top_k=1) - if hits.empty: - missing.append(name) - else: - found.append(row_to_dict(hits.iloc[0])) - if not found: - reply = "مش لاقي الأماكن اللي عايز تقارن بينها حاليًا 😔\nاكتب الاسمين بشكل أوضح." - session.add(text, reply, "no_result", entities, None, []) - return {"reply": reply, "intent": "no_result", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - found = rank_places(pd.DataFrame(found), text, user_lat, user_lon, "best_of").to_dict("records") - if missing: - reply = f"لقيت {', '.join([p.get('name','') for p in found])}، لكن مش لاق�� {', '.join(missing)} حاليًا في قاعدة البيانات.\nرتبتلك الموجود حسب التقييم 👇" - else: - reply = _dynamic_reply("best", category=normalize_category(found[0].get("category", "")), best_place=found[0]) - session.add(text, reply, "compare_places", entities, found[0], found) - return {"reply": reply, "intent": "compare_places", "confidence": confidence, "entities": entities, "best_place": found[0], "all_results": found} - - if intent == "show_menu": - menu_cat = infer_category(text, intent, entities) - if menu_cat in {"pharmacy", "supermarket", "housing"}: - reply = "المنيو متاح للمطاعم والكافيهات بس 😊\nلو عايز عنوان أو رقم صيدلية/ماركت اكتب اسمها." - session.add(text, reply, "show_menu", entities, None, []) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": None, "all_results": [], "menu_items": []} - place_name = entities.get("place_name") or extract_menu_place_name(text) - hits = name_search(place_name, category="restaurant", top_k=1) if place_name else pd.DataFrame() - if hits.empty: - hits = name_search(place_name, category="cafe", top_k=1) if place_name else pd.DataFrame() - if hits.empty: - reply = f"مش لاقي مطعم أو كافيه باسم {place_name or 'ده'} عشان أجيب المنيو 😔" - session.add(text, reply, "show_menu", entities, None, []) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": None, "all_results": [], "menu_items": []} - place = row_to_dict(hits.iloc[0]) - items = fetch_menu(place) - reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔" - session.add(text, reply, "show_menu", entities, place, [place]) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": place, "all_results": [place], "menu_items": items} - - if intent == "place_details" and entities.get("place_name"): - explicit_cat_for_name = entities.get("category") or infer_category(text, intent, entities) - hits = name_search(entities["place_name"], category=explicit_cat_for_name, top_k=1) - if not hits.empty: - place = row_to_dict(hits.iloc[0]) - reply = handle_detail(text, place) - session.add(text, reply, intent, entities, place, [place]) - return {"reply": reply, "intent": intent, "confidence": confidence, "entities": entities, "best_place": place, "all_results": [place]} - - merged = session.merge(entities) - if not category and merged.get("category"): - category = merged.get("category") - entities["category"] = category - item_query = entities.get("item_query", "") - if item_query and is_generic_category_item(item_query): - item_query = "" - entities.pop("item_query", None) - # Generic buying requests should search the right category, not a literal menu item. - # "اشتري دوا" => pharmacies, "شيبسي وبيبسي" => supermarkets. - generic_category_request = False - item_intended = intended_item_category(item_query) - if item_intended in {"pharmacy", "supermarket"}: - category = item_intended - entities["category"] = category - item_query = "" - entities.pop("item_query", None) - generic_category_request = True - place_name = entities.get("place_name", "") - # If current message contains a new explicit place name, don't inherit old category/location - # from the session. This fixes: previous pharmacy context + "بوليفار" => should search all places. - explicit_category_now = entities.get("category") or infer_category(text, intent, entities) - if item_query and place_name and (clean_text(item_query) == clean_text(place_name) or any(w in norm(text) for w in ITEM_CUES)): - place_name = "" - entities.pop("place_name", None) - if place_name and not explicit_category_now: - category = "" - entities.pop("category", None) - location = entities.get("location") or ("" if place_name else merged.get("location", "")) - price_range = entities.get("price_range", "") - if intent == "search_by_item" and not item_query and not generic_category_request: - item_query = extract_item_query(text) - if item_query: - entities["item_query"] = item_query - if item_query and not category: - category = intended_item_category(item_query) or "restaurant" - entities["category"] = category - if item_query and intended_item_category(item_query) in {"pharmacy", "supermarket"}: - category = intended_item_category(item_query) - entities["category"] = category - item_query = "" - entities.pop("item_query", None) - conflict = item_category_conflict(item_query, category) - if conflict: - reply = f"حاسس إن فيه تعارض في الطلب 😊\n{item_query} غالبًا تابع لـ {CAT_AR.get(conflict, conflict)} مش {CAT_AR.get(category, category)}. تقصدي أدورلك فين؟" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - open_now_only = intent in {"open_now", "open_now_extended", "availability_question"} or has_any(text, OPEN_WORDS) - if intent in {"recommendation_by_mood", "recommend_place"} and not category: - category = infer_category(text) or "cafe" - entities["category"] = category - - results_df = search_places(text, 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=12) - soft_reason = "" - open_also_failed = False - if results_df.empty and open_now_only and category: - results_df = search_places(text, category=category, item_query=item_query, location=location, price_range=price_range, open_now_only=False, place_name=place_name, user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - soft_reason = "open" if not results_df.empty else "" - if results_df.empty: - open_also_failed = True - if results_df.empty and location and category: - results_df = search_places(text, category=category, item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name=place_name, user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - if not results_df.empty: - soft_reason = "area" - # If the caller also asked for open_now and that already failed - # before we dropped location, the area-fallback results are not - # guaranteed to be open either — build_response should say so - # rather than presenting them as a plain alternative. - if open_now_only: - open_also_failed = True - if results_df.empty and item_query and is_near_query(text): - results_df = search_places(text, category=category or "restaurant", item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name="", user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - soft_reason = "near_item" if not results_df.empty else soft_reason - related_item_used = "" - # No automatic substitute cards here. If the exact item is unavailable, - # say it is unavailable instead of showing unrelated alternatives. - results = [row_to_dict(r) for _, r in results_df.iterrows()] if not results_df.empty else [] - best = results[0] if results else None - result_intent = intent if results else "no_result" - reply = build_response( - results, - intent, - category=category, - item_query=item_query, - place_name=place_name, - location=location, - open_now_only=open_now_only, - soft_reason=soft_reason, - query=text, - open_uncertain=open_also_failed and soft_reason == "area", - user_has_location=(user_lat is not None and user_lon is not None), - related_item_used=related_item_used, - ) - session.add(text, reply, result_intent, entities, best, results) - return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results} -@asynccontextmanager -async def lifespan(app: FastAPI): - global intent_pipe, ner_pipe, semantic_model, STARTUP_COMPLETE - log.info("Starting AroundU chatbot backend") - - # Each model loads in its own try block: one model failing to load - # should not block the others from working. STARTUP_COMPLETE is set - # True as long as intent + NER (the core chat path) are usable, even - # if the semantic model or the live places index fails to load. - try: - intent_pipe = pipeline("text-classification", model=INTENT_REPO, tokenizer=INTENT_REPO, return_all_scores=False) - log.info("Intent pipeline loaded from %s", INTENT_REPO) - except Exception as exc: - intent_pipe = None - log.exception("Intent model failed to load: %s", exc) - - try: - ner_pipe = pipeline("ner", model=ENTITY_REPO, tokenizer=ENTITY_REPO, aggregation_strategy="simple") - log.info("Entity pipeline loaded from %s", ENTITY_REPO) - except Exception as exc: - ner_pipe = None - log.exception("Entity model failed to load: %s", exc) - - try: - semantic_model = SentenceTransformer(SEMANTIC_MODEL_NAME) - log.info("Semantic model loaded: %s", SEMANTIC_MODEL_NAME) - except Exception as exc: - semantic_model = None - log.exception("Semantic model failed to load: %s", exc) - - try: - if semantic_model is not None: - rebuild_dynamic_index(force=True) - else: - log.warning("Skipping places index build — semantic model unavailable") - except Exception as exc: - log.exception("Places index build failed: %s", exc) - - STARTUP_COMPLETE = intent_pipe is not None and ner_pipe is not None - if STARTUP_COMPLETE: - log.info("Startup complete (core chat path ready)") - else: - log.error("Startup incomplete — intent/NER unavailable, chat endpoint will return 503") - yield - - -app = FastAPI( - title="Beni Suef Chatbot API", - description="شات بوت ذكي للبحث عن الأماكن في بني سويف 🇪🇬", - version="4.0.0", - lifespan=lifespan, -) -app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) - - -class ChatRequest(BaseModel): - message: str - session_id: str = "default" - lat: Optional[float] = None - lon: Optional[float] = None - user_lat: Optional[float] = None - user_lon: Optional[float] = None - - def resolved_lat(self): - return self.lat if self.lat is not None else self.user_lat - - def resolved_lon(self): - return self.lon if self.lon is not None else self.user_lon - - -class ChatData(BaseModel): - reply: str - intent: str - confidence: float - entities: dict = Field(default_factory=dict) - session_id: str - ui_type: str = CFG.UI_TEXT_ONLY - best_place: Optional[dict] = None - place_cards: List[dict] = Field(default_factory=list) - menu_items: List[dict] = Field(default_factory=list) - - -class ChatResponse(BaseModel): - data: ChatData - - -def _first_value(place: dict, *keys, default=None): - for key in keys: - value = place.get(key) - if value is not None and value != "" and str(value).lower() not in ("nan", "none"): - return value - return default - - -def _safe_float(value): - try: - if value is None or value == "": - return None - x = float(value) - if np.isnan(x) or np.isinf(x): - return None - return round(x, 2) - except Exception: - return None - - -def _safe_int(value): - try: - if value is None or value == "": - return 0 - return int(float(value)) - except Exception: - return 0 - - -def clean_place(place: dict) -> dict: - if not place: - return {} - lat = _safe_float(_first_value(place, "lat", "latitude")) - lon = _safe_float(_first_value(place, "lon", "lng", "longitude")) - distance = _safe_float(_first_value(place, "distance_km")) - rating = _safe_float(_first_value(place, "rating_norm", "rating", default=0.0)) or 0.0 - open_raw = _first_value(place, "is_open", "open_now") - if isinstance(open_raw, bool): - is_open = open_raw - elif open_raw in (1, "1", "true", "True", "open", "مفتوح"): - is_open = True - elif open_raw in (0, "0", "false", "False", "closed", "مغلق"): - is_open = False - else: - is_open = None - phone_val = _first_value(place, "phone", "mobile", "telephone", default="") - if isinstance(phone_val, (list, tuple)): - phone_val = ", ".join(str(x) for x in phone_val if x) - elif isinstance(phone_val, str) and phone_val.startswith("[") and phone_val.endswith("]"): - phone_val = phone_val.strip("[]").replace("'", "").replace('"', "").strip() - phone_val = (phone_val or "").strip() - has_phone = bool(phone_val) - return { - "id": str(_first_value(place, "id", "place_id", default="")), - "place_id": str(_first_value(place, "place_id", "id", default="")), - "name": _first_value(place, "name", "name_ar", "name_en", default=""), - "category": str(_first_value(place, "category", default="")).lower().strip(), - "sub_category": _first_value(place, "sub_category", "subcategory", default=""), - "rating": rating, - "rating_count": _safe_int(_first_value(place, "rating_count", "review_count", "reviews_count", default=0)), - "address": _first_value(place, "address", "location", default=""), - "description": _first_value(place, "description", default=""), - "is_open": is_open, - "opening_hours": _first_value(place, "opening_hours", "openning_hours", default=""), - "distance_km": distance, - "image": _first_value(place, "image", "image_url", "main_image_url", "photo", "photo_url", default="") or "", - "phone": phone_val if has_phone else None, - "has_phone": has_phone, - "lat": lat, - "lon": lon, - "is_favorited": bool(_first_value(place, "is_favorited", "is_favorite", default=False)), - "final_score": _safe_float(_first_value(place, "final_score")), - } - - -def make_chat_response( - *, reply: str, intent: str, confidence: float, entities: dict, session_id: str, - ui_type: str = CFG.UI_TEXT_ONLY, best_place: Optional[dict] = None, - place_cards: Optional[list] = None, menu_items: Optional[list] = None, -) -> ChatResponse: - place_cards = place_cards or [] - menu_items = menu_items or [] - if intent in NO_CARD_INTENTS or ui_type == CFG.UI_TEXT_ONLY: - place_cards = [] - best_place = None - if ui_type != CFG.UI_MENU_LIST: - menu_items = [] - ui_type = CFG.UI_TEXT_ONLY - return ChatResponse(data=ChatData( - reply=reply, - intent=intent, - confidence=confidence, - entities=entities or {}, - session_id=session_id, - ui_type=ui_type, - best_place=best_place, - place_cards=place_cards, - menu_items=menu_items, - )) - - -def cleanup_sessions(): - now = time.time() - expired = [sid for sid, sess in SESSIONS.items() if now - getattr(sess, "last_active", now) > SESSION_TTL_SEC] - for sid in expired: - del SESSIONS[sid] - - -@app.get("/", tags=["General"]) -def root(): - return {"status": "ok", "message": "Beni Suef Chatbot is running 🚀", "version": "4.0.0"} - - -@app.get("/health", tags=["General"]) -def health(): - return { - "status": "healthy" if STARTUP_COMPLETE else "starting", - "models_loaded": bool(intent_pipe and ner_pipe and semantic_model), - "places_count": len(places_df) if places_df is not None else 0, - "embeddings_ok": corpus_embeddings is not None, - } - - -@app.post("/chat", response_model=ChatResponse, tags=["Chat"]) -@app.post("/ai/chat", response_model=ChatResponse, tags=["Chat"]) -def chat_endpoint(req: ChatRequest): - cleanup_sessions() - if not STARTUP_COMPLETE: - raise HTTPException(status_code=503, detail="الشات بوت لسه بيتحمل — استنى لحظة وجرب تاني 🔄") - if req.session_id not in SESSIONS: - SESSIONS[req.session_id] = Session(req.session_id) - session = SESSIONS[req.session_id] - try: - result = chat(req.message, session, req.resolved_lat(), req.resolved_lon()) - except Exception as exc: - log.exception("Chat error: %s", exc) - raise HTTPException(status_code=500, detail=str(exc)) - intent = result.get("intent", "fallback") - menu_items = result.get("menu_items", []) or [] - all_results = result.get("all_results", []) or [] - if not all_results and result.get("best_place"): - all_results = [result["best_place"]] - unique_cards = [] - seen = set() - if intent not in NO_CARD_INTENTS: - for place in all_results: - card = clean_place(place) - pid = card.get("id") or card.get("place_id") or card.get("name") - if pid and pid not in seen: - seen.add(pid) - unique_cards.append(card) - ui_type = CFG.UI_MENU_LIST if menu_items else (CFG.UI_PLACES_CARDS if unique_cards else CFG.UI_TEXT_ONLY) - return make_chat_response( - reply=result.get("reply", ""), - intent=intent, - confidence=float(result.get("confidence", 0.0) or 0.0), - entities=result.get("entities", {}) or {}, - session_id=req.session_id, - ui_type=ui_type, - best_place=unique_cards[0] if unique_cards else None, - place_cards=unique_cards[:MAX_CARDS], - menu_items=menu_items, - ) - - -@app.post("/reload-data", tags=["Admin"]) -def reload_data(x_secret: Optional[str] = Header(default=None)): - if RELOAD_SECRET and x_secret != RELOAD_SECRET: - raise HTTPException(status_code=403, detail="Forbidden") - try: - count = rebuild_dynamic_index(force=True) - return {"status": "ok", "places_count": count} - except Exception as exc: - log.exception("Reload failed: %s", exc) - raise HTTPException(status_code=500, detail=str(exc)) - - -@app.delete("/session/{session_id}", tags=["Session"]) -def reset_session(session_id: str): - SESSIONS.pop(session_id, None) - return {"status": "reset", "session_id": session_id} -INTENT_REPO = os.getenv("INTENT_REPO", "Youmnaaaa/Intent-model") -ENTITY_REPO = os.getenv("ENTITY_REPO", "Youmnaaaa/Entity-model") -SEMANTIC_MODEL_NAME = os.getenv( - "SEMANTIC_MODEL_NAME", - "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", -) - -AROUNDU_BASE = os.getenv( - "AROUNDU_BASE", - "https://aroundubackend-production.up.railway.app/api/v1/ai/data", -).rstrip("/") -AROUNDU_KEY = os.getenv("AROUNDU_API_KEY", os.getenv("PLACES_API_KEY", "")).strip() -RELOAD_SECRET = os.getenv("RELOAD_SECRET", "") - -INTENT_THRESHOLD = float(os.getenv("INTENT_THRESHOLD", "0.70")) -SEMANTIC_MIN_SCORE = float(os.getenv("SEMANTIC_MIN_SCORE", "0.35")) -SEMANTIC_TOP_K = int(os.getenv("SEMANTIC_TOP_K", "25")) -SESSION_TTL_SEC = int(os.getenv("SESSION_TTL_SEC", "3600")) -MAX_CARDS = int(os.getenv("MAX_CARDS", "4")) - -intent_pipe = None -ner_pipe = None -semantic_model = None -places_df: Optional[pd.DataFrame] = None -corpus_df: Optional[pd.DataFrame] = None -corpus_embeddings = None -STARTUP_COMPLETE = False -SESSIONS: Dict[str, "Session"] = {} -MENU_CACHE: Dict[str, list] = {} - - -class CFG: - UI_TEXT_ONLY = "text_only" - UI_PLACES_CARDS = "places_cards" - UI_MENU_LIST = "menu_list" - MSG_API_ERROR = "حصلت مشكلة مؤقتة في الاتصال بالخدمة. جرب تاني بعد لحظات." - - -SEARCH_INTENTS = { - "nearest_restaurant", "nearest_pharmacy", "nearest_cafe", "nearest_supermarket", - "housing_search", "recommend_place", "recommendation_by_mood", "open_now", - "open_now_extended", "place_details", "search_by_item", "best_of", "nearby_search", - "filter_results", "sort_results", "availability_question", "ask_location", - "ask_price", "ask_rating", "price_question", "ambiguous_place", -} - -NO_CARD_INTENTS = { - "fallback", "no_result", "missing_info", "out_of_scope", "clarification", - "clarification_response", "greeting", "thanks", "goodbye", "confirm", "deny", -} - -INTENT_TO_CATEGORY = { - "nearest_restaurant": "restaurant", - "nearest_pharmacy": "pharmacy", - "nearest_cafe": "cafe", - "nearest_supermarket": "supermarket", - "housing_search": "housing", -} - -CATEGORY_KEYWORDS = { - "restaurant": [ - "مطعم", "مطاعم", "اكل", "أكل", "وجبات", "مشويات", "كباب", "كفته", "كفتة", - "شاورما", "كريب", "سندوتش", "سندوتشات", "برجر", "بيتزا", "فراخ", "فول", - "طعمية", "سمك", "restaurant", "food", "burger", "pizza", "shawarma", "crepe", - ], - "pharmacy": [ - "صيدليه", "صيدلية", "صيدليات", "صيدله", "صديليه", "صديليه", "دوا", "دواء", "ادويه", "أدوية", - "ادوية", "علاج", "pharmacy", "drugstore", "medicine", - ], - "cafe": [ - "كافيه", "كافيهات", "كافية", "كوفي", "قهوه", "قهوة", "كافيتيريا", "لاتيه", - "كابتشينو", "اسبريسو", "cafe", "coffee", - ], - "supermarket": [ - "سوبرماركت", "سوبر ماركت", "سوبر", "ماركت", "هايبر", "بقاله", "بقالة", - "supermarket", "market", "grocery", "hypermarket", - ], - "housing": [ - "سكن", "شقه", "شقة", "شقق", "ايجار", "إيجار", "فندق", "هوستل", - "hotel", "apartment", "housing", "rent", - ], -} - -CAT_AR = { - "restaurant": "مطاعم", - "pharmacy": "صيدليات", - "cafe": "كافيهات", - "supermarket": "ماركت", - "housing": "أماكن سكن", -} -CAT_SINGLE = { - "restaurant": "مطعم", - "pharmacy": "صيدلية", - "cafe": "كافيه", - "supermarket": "ماركت", - "housing": "مكان سكن", -} - -KEYWORD_INTENTS = { - "greeting": ["السلام عليكم", "وعليكم السلام", "اهلا", "أهلا", "هلا", "مرحبا", "صباح الخير", "مساء الخير", "hi", "hello"], - "thanks": ["شكرا", "شكراً", "تسلم", "تسلمي", "يسلمو", "مشكور", "thanks", "thank you"], - "goodbye": ["مع السلامة", "مع السلامه", "باي", "وداعا", "bye", "goodbye"], - "confirm": ["تمام", "اوك", "أوك", "ماشي", "حاضر", "اه", "اها", "ايوه", "نعم"], - "deny": ["لا", "لأ", "مش عايز", "مش عايزة", "مش ده", "مش دي", "مش قصدي", "مش ده اللي قصدي"], -} - -OUT_OF_SCOPE_KW = [ - "الجو", "طقس", "درجة الحرارة", "كوره", "كرة", "أهلي", "زمالك", "ماتش", "سياسة", - "اخبار", "أخبار", "بنك", "رصيد", "تحويل", "امتحان", "مدرسة", "جامعة", "كود", - "برمجة", "python", "java", "ترجمة", "translate", "نكتة", "قصيدة", "دولار", "ذهب", -] - -DETAIL_WORDS = [ - "فين", "مكان", "مكانه", "مكانها", "عنوان", "عنوانه", "عنوانها", "لوكيشن", "الموقع", - "رقم", "رقمه", "رقمها", "تليفون", "تلفون", "بيفتح", "بتفتح", "مواعيد", "مواعيده", - "مواعيدها", "امتى", "امتي", "تقييم", "سعر", "بكام", "غالي", "رخيص", -] -# Words that signal the sentence is asking about a NEW category/item, not -# requesting details about the place already in context. If any of these -# appear alongside a DETAIL_WORD, the sentence is treated as "new" rather -# than "detail" — e.g. "فين أقرب كافيه" should search for cafes, not pull -# up the last place's address just because it contains "فين". -NEW_SEARCH_SIGNAL_WORDS = [ - "اقرب", "أقرب", "قريب", "قريبه", "قريبة", - "مطعم", "مطاعم", "كافيه", "كافيهات", "صيدليه", "صيدلية", "صيدليات", - "ماركت", "سوبر", "سوبرماركت", "هايبر", "شقه", "شقة", "سكن", -] -NEXT_WORDS = ["تاني", "غيره", "غيرها", "بديل", "حاجة تانية", "مش عاجبني", "فيه تاني", "كمان"] -REF_WORDS = ["هو", "هي", "ده", "دي", "المكان ده", "المحل ده"] - - -NEAR_WORDS = ["اقرب", "الأقرب", "الاقرب", "قريب", "قريبه", "قريبة", "جنبي", "حواليا", "حولي", "near", "nearest", "nearby"] -BEST_WORDS = ["ا��سن", "أحسن", "افضل", "أفضل", "اعلى تقييم", "أعلى تقييم", "كويس", "ممتاز", "رشحلي", "التوب"] -OPEN_WORDS = ["مفتوح", "فاتح", "شغال", "دلوقتي", "24 ساعه", "24 ساعة", "بليل"] -MENU_WORDS = ["منيو", "مينيو", "menu", "قائمة"] -ITEM_CUES = ["عايز", "عايزة", "عاوز", "محتاج", "نفسي", "بيعمل", "بتعمل", "عنده", "عندها", "فيه", "فيها"] -NON_ITEM_WORDS = { - "طب", "طيب", "تمام", "ماشي", "يعني", "بقا", "بقى", "كدا", "كده", "هو", "هي", "ده", "دي", - "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "تقييم", "ريتنج", "التوب", "توب", "top", - "قريب", "قريبه", "قريبة", "اقرب", "أقرب", "هنا", "هناك", "دلوقتي", "مفتوح", "فاتح", "شغال", - "ايه", "إيه", "مين", "واحد", "حاجة", "حاجه" -} - -ITEM_CATEGORY_HINTS = { - "restaurant": ["برجر", "بيتزا", "شاورما", "كريب", "مشويات", "كباب", "كفته", "كفتة", "فراخ", "نص فراخ", "نص فرخه", "نص فرخة", "فول", "طعميه", "طعمية", "سمك", "كشري", "حواوشي", "فطير", "اكل", "أكل", "وجبه", "وجبة"], - "cafe": ["قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "موكا", "نسكافيه"], - "pharmacy": ["دواء", "دوا", "علاج", "ادويه", "أدوية", "دواء برد", "مسكن"], -} - -DYNAMIC_TEMPLATES = { - "category": [ - "من عينيا! جمعتلك أحسن اختيارات {cat_ar} متاحة في بني سويف، شوف الكروت تحت واختار اللي يناسبك 👇", - "جاهز لمساعدتك! دي لستة {cat_ar} مناسبة ومترتبة عشان تختار بسرعة 🗺️", - "تأمر يا هندسة! لقيتلك شوية اختيارات كويسة من {cat_ar} في بني سويف ✨", - "تمام، دورتلك وطلعتلك أنسب {cat_ar} حسب طلبك 👇", - "دي أفضل نتايج لقيتها ليك من {cat_ar}، بص على الكروت وشوف الأنسب 😊", - ], - "nearest": [ - "حسبتلك المسافات بالملي! دي الأماكن مترتبة من الأقرب للأبعد من موقعك الحالي 📍", - "علطول كده! أول كارت هو الأقرب ليك، وبعده الباقي حسب المسافة 🚗", - "جبتلك الأقرب فالأقرب عشان المشوار يبقى سهل وسريع ⏱️", - "دي أقرب اختيارات حوالين موقعك الحالي، مرتبة من الأقرب للأبعد 👇", - "رتبتهم حسب المسافة الجغرافية من مكانك، شوف أول كارت هيبقى الأقرب 📌", - ], - "best": [ - "بناءً على التقييمات، {best_name} ظاهر كأقوى اختيار، وباقي الكروت مرتبة حسب الأعلى تقييمًا 🏆", - "عايز التوب؟ رتبتلك الأماكن حسب أعلى Rating وتجارب الناس ⭐", - "دي قمة الأماكن في التقييم، الأعلى تقييمًا ظاهرين في الأول 🌟", - "الناس بتقول إن دول الأفضل، رتبتهم حسب التقييم عشان تختار وانت مطمن ✨", - "جمعتلك الاختيارات الأعلى تقييمًا في بني سويف، أول كارت هو الأقوى تقييمًا 👇", - ], - "best_near": [ - "جمعتلك المعادلة الصح: أماكن تقييمها عالي وقريبة منك في نفس الوقت، أول كارت هو الأفضل توازنًا بين الجودة والمسافة ⭐📍", - "رتبتلك الاختيارات حسب التقييم مع مراعاة القرب، عشان تختار مكان كويس ومش بعيد 👇", - "دي أماكن قوية في الريتنج وقريبة نسبيًا من موقعك، يعني جودة ومشوار أسهل في نفس الوقت 🚗⭐", - "عملتلك ترتيب ذكي بين الأعلى تقييمًا والأقرب، شوف أول كارت هيبقى أنسب اختيار متوازن ✨", - "لو عايز حاجة كويسة وقريبة، دي أفضل النتائج حسب الريتنج والمسافة مع بعض 📌", - ], - "item": [ - "طلبك عندي! دورت في الأماكن المتاحة ولقيتلك اللي بيقدموا {item} 😋👇", - "جبتلك المفيد! دي الأماكن اللي ظاهر عندها {item} في الداتا 🎯", - "بال هنا مقدمًا! دي اختيارات مناسبة لطلب {item} 👇", - "دورتلك على {item} وطلعتلك الأماكن الأقرب للطلب ده ✨", - "دي الأماكن اللي ينفع تبدأ بيها لو نفسك في {item} 😋", - ], - "open": [ - "فلترتلك الأماكن المفتوحة دلوقتي قدر الإمكان، شوف الكروت تحت 🟢", - "دورت على المتاح دلوقتي، والنتايج تحت حسب حالة المواعيد المسجلة ⏰", - "دي الأماكن اللي باين إنها شغالة أو متاحة حاليًا في الداتا 👇", - "تمام، ركزت على الأماكن المفتوحة دلوقتي حسب المواعيد المتاحة 🟢", - "شوف دول، حاولت أجيبلك المتاح دلوقتي بأفضل ترتيب 👇", - ], - "soft_open": [ - "مش لاقي {cat_ar} باين إنها مفتوحة دلوقتي، بس دي {cat_ar} متاحة في الداتا وممكن تتأكد من المواعيد أو تتصل بيهم 👇", - "مفيش نتيجة مؤكدة إنها مفتوحة حاليًا، فبعرضلك الموجود مع توضيح حالة المواعيد عشان تختار 👇", - "مش ظاهر عندي مكان مفتوح دلوقتي بشكل مؤكد، بس دول أقرب بدائل متاحة في الداتا 👇", - "للأسف حالة الفتح مش مؤكدة للطلب ده، لكن دي اختيارات موجودة ممكن تنفعك 👇", - "مش لاقي مفتوح مؤكد حاليًا، فدي الأماكن المسجلة المتاحة وقدامك كروتها 👇", - ], - "soft_near_item": [ - "مفيش {cat_single} قريب واضح عنده {item}، بس دي أماكن بتقدم {item} ومترتبة من الأقرب للأبعد 👇", - "اللي قريب جدًا ومطابق للصنف مش ظاهر عندي، فجبتهالك حسب أقرب أماكن عندها {item} 📍", - "مش لاقي {item} قريب منك أوي، بس دول المتاحين للصنف ده مرتبين بالمسافة 👇", - "مفيش نتيجة قريبة كفاية للصنف ده، بس دي أقرب اختيارات فيها {item} 🚗", - "لقيت {item} بس مش واضح إنه قريب جدًا، فرتبتلك البدائل حسب المسافة 👇", - ], - "area_fallback": [ - "مفيش {cat_ar} متاحة حاليًا في {location}، بس لقيت بدائل قريبة/متاحة في بني سويف 👇", - "المنطقة دي مش ظاهر فيها {cat_ar} دلوقتي، فبعرضلك اختيارات تانية ممكن تنفعك 👇", - "مش لاقي {cat_ar} في {location} حاليًا، لكن دي نتائج بديلة من الداتا 👇", - "في {location} مفيش نتيجة مطابقة، فدي أقرب بدائل مناسبة عندي 👇", - "مفيش {cat_ar} مسجلة في {location} حاليًا، شوف البدائل دي 👇", - ], - "one": [ - "لقيتلك المكان ده، وده أقرب اختيار مناسب لطلبك 👇", - "فيه اختيار واضح مناسب للي بتدور عليه 👇", - "ده أفضل Match لطلبك حاليًا 👇", - "لقيت نتيجة واحدة مناسبة، شوفها كده 👇", - "ده المكان اللي طلع مطابق لطلبك 👇", - ], - "near_no_location": [ - "جبتلك اختيارات مناسبة، ولو بعتلي موقعك هرتبهم من الأقرب للأبعد بدقة 📍", - "دي نتايج مناسبة حسب الداتا المتاحة، ولترتيب المسافة الحقيقي ابعتلي موقعك الحالي 😊", - "أقدر أرتبهم بالأقرب لو وصلني موقعك، دلوقتي بعرضلك أنسب الاختيارات المتاحة 👇", - "لو عايزاهم بالمسافة بالظبط ابعتي موقعك، ودي أفضل نتايج متاحة حاليًا 👇", - "دي اختيارات ممكن تنفعك، ومع الموقع هقدر أحدد الأقرب ليكي بالملي 📌", - ], - "fallback": [ - "مش فاهم قصدك أوي 😊 اسألني عن مطعم، كافيه، صيدلية، ماركت أو سكن في بني سويف.", - "أنا أقدر أساعدك في أماكن بني سويف: مطاعم، كافيهات، صيدليات، ماركت أو سكن 😊", - "وضحلي بس بتدور على إيه؟ مطعم؟ صيدلية؟ كافيه؟ وأنا أجيبلك الكروت 👇", - "ممكن تعيد السؤال بطريقة أبسط؟ أنا متخصص في خدمات وأماكن بني سويف 😊", - "قولي نوع المكان أو اسم الأكلة أو المنطقة، وأنا أظبطهالك 👌", - ], -} - - -def clean_text(text: Any) -> str: - text = str(text or "").strip().lower() - text = re.sub(r"ـ+", "", text) - replacements = [("[إأآا]", "ا"), ("ى", "ي"), ("ة", "ه"), ("ؤ", "و"), ("ئ", "ي")] - for old, new in replacements: - text = re.sub(old, new, text) - text = re.sub(r"[^\w\s]", " ", text) - return re.sub(r"\s+", " ", text).strip() - - -def norm(text: Any) -> str: - return clean_text(text) - - -def normalize_category(cat: Any) -> str: - c = clean_text(cat) - if not c: - return "" - has_rest = "restaurant" in c or "مطعم" in c or "مطاعم" in c or "اكل" in c - has_cafe = "cafe" in c or "coffee" in c or "كافيه" in c or "كوفي" in c or "قهوه" in c or "قهوة" in c - if has_rest and has_cafe: - return "restaurant_cafe" - if "pharmacy" in c or "صيدلي" in c or "صيدله" in c or "صيدليه" in c or "صيدلية" in c or "دواء" in c or "دوا" in c: - return "pharmacy" - if "supermarket" in c or "market" in c or "grocery" in c or "ماركت" in c or "بقال" in c or "هايبر" in c: - return "supermarket" - if has_cafe: - return "cafe" - if "housing" in c or "hotel" in c or "hostel" in c or "سكن" in c or "شقه" in c or "فندق" in c: - return "housing" - if has_rest: - return "restaurant" - return c - - -def category_matches(raw_category: Any, target: str) -> bool: - """Strict but fair category matching. - Mixed categories like 'restaurant & café' should match both restaurant and cafe. - """ - if not target: - return True - target = normalize_category(target) - raw = clean_text(raw_category) - norm_cat = normalize_category(raw_category) - if norm_cat == target: - return True - if norm_cat == "restaurant_cafe" and target in {"restaurant", "cafe"}: - return True - if target == "restaurant": - return "restaurant" in raw or "مطعم" in raw or "مطاعم" in raw - if target == "cafe": - return "cafe" in raw or "coffee" in raw or "كافيه" in raw or "كوفي" in raw or "قهوه" in raw or "قهوة" in raw - if target == "pharmacy": - return "pharmacy" in raw or "صيدلي" in raw or "صيدله" in raw or "صيدليه" in raw or "صيدلية" in raw - if target == "supermarket": - return "supermarket" in raw or "market" in raw or "ماركت" in raw or "بقال" in raw or "هايبر" in raw - if target == "housing": - return "housing" in raw or "hotel" in raw or "hostel" in raw or "سكن" in raw or "شقه" in raw or "فندق" in raw - return norm_cat == target or target in raw - - -def infer_category(text: str, intent: str = "", entities: Optional[dict] = None) -> str: - entities = entities or {} - if entities.get("category"): - return normalize_category(entities["category"]) - if intent in INTENT_TO_CATEGORY: - return INTENT_TO_CATEGORY[intent] - t = norm(text) - for cat, words in CATEGORY_KEYWORDS.items(): - if any(norm(w) in t for w in words): - return cat - return "" - - -def is_out_of_scope(text: str) -> bool: - t = norm(text) - # Word-boundary match (not raw substring) — otherwise short keywords - # like "بنك" or "ذهب" wrongly match inside unrelated longer words - # ("بنكهة" = flavor, "مذهبي" = my taste/preference), incorrectly - # routing normal place/food queries into the out-of-scope rejection. - # Also allow an optional leading "ال" (definite article, attaches - # directly with no space — "السياسة" = "ال" + "سياسة") since a plain - # \b boundary can't separate them and would otherwise miss "سياسة" - # whenever the user writes it with the article attached. - return any(re.search(rf"\bال?{re.escape(norm(k))}\b", t) for k in OUT_OF_SCOPE_KW) - - -def get_cairo_now(): - return datetime.now(ZoneInfo("Africa/Cairo")) - - -def parse_time(token: str) -> Optional[str]: - token = norm(token).replace(" ", "") - m = re.match(r"^(\d{1,2})(?::(\d{1,2}))?(ص|م|ظهر)?$", token) - if not m: - return None - h = int(m.group(1)) - mn = int(m.group(2)) if m.group(2) else 0 - suf = m.group(3) - if not (0 <= mn <= 59): - return None - if suf == "ص": - if h == 12: - h = 0 - elif not 1 <= h <= 11: - return None - elif suf in ("م", "ظهر"): - if h != 12 and 1 <= h <= 11: - h += 12 - else: - if h == 24: - h = 0 - elif not 0 <= h <= 23: - return None - return f"{h:02d}:{mn:02d}" - - -def check_open_now(opening_hours_str: Any) -> Optional[int]: - if not opening_hours_str or str(opening_hours_str).strip().lower() in ("", "nan", "none"): - return None - text = norm(opening_hours_str) - if any(k in text for k in ["24", "always", "طول اليوم", "24/7"]): - return 1 - sep = re.search(r"(.+?)\s*-\s*(.+)", text) - if not sep: - return None - t1 = parse_time(sep.group(1).strip()) - t2 = parse_time(sep.group(2).strip()) - if not t1 or not t2: - return None - now_t = f"{get_cairo_now().hour:02d}:{get_cairo_now().minute:02d}" - if t1 <= t2: - return 1 if t1 <= now_t <= t2 else 0 - return 1 if (now_t >= t1 or now_t <= t2) else 0 - - -def haversine(lat1, lon1, lat2, lon2): - r = 6371 - p = math.pi / 180 - a = math.sin((lat2 - lat1) * p / 2) ** 2 + math.cos(lat1 * p) * math.cos(lat2 * p) * math.sin((lon2 - lon1) * p / 2) ** 2 - return 2 * r * math.asin(math.sqrt(a)) - - -def _headers() -> dict: - headers = {"Accept": "application/json"} - if AROUNDU_KEY: - headers["X-API-Key"] = AROUNDU_KEY - return headers - - -def _extract_payload_data(payload): - if isinstance(payload, list): - return payload - if isinstance(payload, dict): - for key in ["data", "results", "items", "places"]: - if isinstance(payload.get(key), list): - return payload[key] - nested = payload.get("data") - if isinstance(nested, dict): - for key in ["data", "results", "items", "places"]: - if isinstance(nested.get(key), list): - return nested[key] - return [] - - -def load_places_from_api() -> pd.DataFrame: - all_rows = [] - skip = 0 - limit = 100 - while True: - url = f"{AROUNDU_BASE}/places" - params = {"skip": skip, "limit": limit} - try: - resp = requests.get(url, headers=_headers(), params=params, timeout=30) - except requests.RequestException as exc: - log.error("Places API network error: %s", exc) - break - if resp.status_code == 401: - log.error("Places API unauthorized. Check X-API-Key secret.") - break - if resp.status_code == 404 and skip == 0: - try: - resp = requests.get(url, headers=_headers(), timeout=30) - except requests.RequestException as exc: - log.error("Places API network error: %s", exc) - break - if resp.status_code != 200: - log.error("Places API error %s: %s", resp.status_code, resp.text[:300]) - break - try: - chunk = _extract_payload_data(resp.json()) - except Exception: - log.error("Places API returned non-JSON response") - break - if not chunk: - break - all_rows.extend(chunk) - if len(chunk) < limit: - break - skip += limit - df = pd.DataFrame(all_rows) - log.info("Loaded %s places from AroundU API", len(df)) - return df - - -def prepare_places_df(df: pd.DataFrame) -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - df = df.copy() - if "lng" in df.columns and "lon" not in df.columns: - df = df.rename(columns={"lng": "lon"}) - required = [ - "id", "place_id", "name", "name_ar", "name_en", "category", "sub_category", - "location", "address", "price_range", "rating", "rating_count", "opening_hours", - "description", "lat", "lon", "phone", "image", "is_favorited", "is_open", - ] - for col in required: - if col not in df.columns: - df[col] = "" - for col in ["lat", "lon", "rating", "rating_count"]: - df[col] = pd.to_numeric(df[col], errors="coerce") - df["rating"] = df["rating"].fillna(0.0).apply(lambda r: round(r / 2, 1) if r > 5 else round(r, 1)) - df["rating_count"] = df["rating_count"].fillna(0).astype(int, errors="ignore") - df["place_id"] = df["place_id"].astype(str).replace({"nan": "", "None": ""}).str.strip() - missing_pid = df["place_id"].eq("") - df.loc[missing_pid, "place_id"] = df.loc[missing_pid, "id"].astype(str) - still_missing = df["place_id"].eq("") | df["place_id"].eq("nan") - df.loc[still_missing, "place_id"] = [f"API{i+1:04d}" for i in range(still_missing.sum())] - text_cols = [ - "id", "place_id", "name", "name_ar", "name_en", "category", "sub_category", "location", - "address", "price_range", "opening_hours", "description", "phone", "image", - ] - for col in text_cols: - df[col] = df[col].fillna("").astype(str) - df["category_norm"] = df["category"].apply(normalize_category) - df["name_clean"] = (df["name"] + " " + df["name_ar"] + " " + df["name_en"]).apply(clean_text) - df["category_clean"] = df["category"].apply(clean_text) - df["sub_category_clean"] = df["sub_category"].apply(clean_text) - df["location_clean"] = df["location"].apply(clean_text) - df["address_clean"] = df["address"].apply(clean_text) - df["price_range_clean"] = df["price_range"].apply(clean_text) - if "search_text_clean" not in df.columns or df["search_text_clean"].astype(str).str.strip().eq("").all(): - df["search_text_clean"] = ( - df["name"].astype(str) + " " + df["name_ar"].astype(str) + " " + df["name_en"].astype(str) + " " + - df["category"].astype(str) + " " + df["sub_category"].astype(str) + " " + - df["location"].astype(str) + " " + df["address"].astype(str) + " " + - df["price_range"].astype(str) + " " + df["description"].astype(str) - ).apply(clean_text) - else: - df["search_text_clean"] = df["search_text_clean"].apply(clean_text) - return df.reset_index(drop=True) - - -def rebuild_dynamic_index(force: bool = True) -> int: - global places_df, corpus_df, corpus_embeddings - raw_df = load_places_from_api() - places_df = prepare_places_df(raw_df) - MENU_CACHE.clear() # menu data may be stale after a places refresh - if places_df.empty: - corpus_df = pd.DataFrame() - corpus_embeddings = None - log.warning("Dynamic semantic index is empty") - return 0 - texts = places_df["search_text_clean"].fillna("").astype(str).tolist() - corpus_embeddings = semantic_model.encode( - texts, - convert_to_tensor=True, - show_progress_bar=False, - batch_size=32, - ) - corpus_df = places_df.copy().reset_index(drop=True) - log.info("Dynamic semantic index rebuilt: %s places", len(corpus_df)) - return len(corpus_df) - - -def apply_keyword_override(text: str) -> Optional[str]: - t = norm(text) - for intent, words in KEYWORD_INTENTS.items(): - for w in words: - wn = norm(w) - if not wn: - continue - if wn == t: - return intent - # Word-boundary match instead of raw substring containment. - # A plain `wn in t` check is catastrophic for short keywords: - # "لا" (deny) was matching inside "لاتيه" and "لاميرا" (a real - # place name!), "اه" (confirm) could match inside many longer - # words. \b in Python's re module works on word characters - # including Arabic letters, so this correctly requires the - # keyword to appear as its own token, not buried inside another word. - if re.search(rf"\b{re.escape(wn)}\b", t): - return intent - if is_out_of_scope(text): - return "out_of_scope" - if any(w in t for w in MENU_WORDS): - return "show_menu" - if any(w in t for w in NEXT_WORDS): - return "show_more" - if any(w in t for w in ["قارن", "مقارنة", "احسن واحد فيهم", "ايه الاحسن", "مين احسن"]): - return "compare_places" - if any(w in t for w in OPEN_WORDS): - cat = infer_category(text) - if cat: - return "open_now" - if any(w in t for w in [ - "مكان هادي", "مكان رايق", "مش زحمه", "مش زحمة", "للمذاكره", "للمذاكرة", "اذاكر", "أذاكر", "شغل", "دراسة", - "عائلات", "عائلي", "للعيله", "للعائلة", "للعيلة", "مع العيلة", "مع العيله", - "خروجات", "خروجه", "خروجة", "اطلع", "أطلع", "اسهر", "أسهر", "للسهر", - "رومانسي", "رومانسى", "شبابي", "شبابى", - ]): - return "recommendation_by_mood" - if any(w in t for w in ["رقم", "عنوان", "فين مكان", "مكانه", "مكانها", "لوكيشن", "مواعيد", "بيفتح"]): - return "place_details" - # Distinguish generic place-type words (مطعم/كافيه/صيدلية/ماركت/سكن) from - # specific food/item words (برجر/شاورما/قهوة...). Both live in - # CATEGORY_KEYWORDS, but only the generic ones should short-circuit to - # nearest_*; specific item words should still flow into search_by_item. - # Without this split, "عايز مطعم كويس" was previously misread by - # extract_item_query() (its trailing adjective "كويس" looked like a - # menu item) and forced into search_by_item instead of nearest_restaurant. - GENERIC_PLACE_WORDS = { - "restaurant": ["مطعم", "مطاعم", "اكل", "أكل", "وجبات", "وجبة", "restaurant", "food"], - "pharmacy": ["صيدليه", "صيدلية", "صيدليات", "صيدله", "pharmacy", "drugstore"], - "cafe": ["كافيه", "كافيهات", "كافية", "كوفي", "كافيتيريا", "cafe"], - "supermarket":["سوبرماركت", "سوبر ماركت", "سوبر", "ماركت", "هايبر", "بقاله", "بقالة", "supermarket", "market"], - "housing": ["سكن", "شقه", "شقة", "شقق", "ايجار", "إيجار", "فندق", "هوستل", "hotel", "apartment", "housing"], - } - generic_cat = "" - for cat, words in GENERIC_PLACE_WORDS.items(): - if any(norm(w) in t for w in words): - generic_cat = cat - break - if generic_cat: - return { - "restaurant": "nearest_restaurant", - "pharmacy": "nearest_pharmacy", - "cafe": "nearest_cafe", - "supermarket": "nearest_supermarket", - "housing": "housing_search", - }.get(generic_cat) - item_guess = extract_item_query(text) - if item_guess and any(w in t for w in ITEM_CUES + sum(ITEM_CATEGORY_HINTS.values(), [])): - return "search_by_item" - cat = infer_category(text) - if cat: - return { - "restaurant": "nearest_restaurant", - "pharmacy": "nearest_pharmacy", - "cafe": "nearest_cafe", - "supermarket": "nearest_supermarket", - "housing": "housing_search", - }.get(cat) - return None - -def predict_intent(text: str, threshold: float = INTENT_THRESHOLD) -> dict: - override = apply_keyword_override(text) - if override: - return {"intent": override, "confidence": 1.0, "source": "rules"} - if intent_pipe is None: - return {"intent": "fallback", "confidence": 0.0, "source": "not_loaded"} - try: - pred = intent_pipe(text, truncation=True, max_length=128) - if isinstance(pred, list) and pred and isinstance(pred[0], list): - pred = pred[0] - item = pred[0] if isinstance(pred, list) and pred else pred - label = str(item.get("label", "fallback")) - score = float(item.get("score", 0.0)) - if label.upper().startswith("LABEL_"): - label = "fallback" - if score < threshold: - return {"intent": "fallback", "confidence": round(score, 4), "source": "model_low_conf"} - return {"intent": label, "confidence": round(score, 4), "source": "model"} - except Exception as exc: - log.error("Intent prediction error: %s", exc) - return {"intent": "fallback", "confidence": 0.0, "source": "error"} - - -def _clean_entity_value(value: Any) -> str: - value = str(value or "").replace("##", "") - value = re.sub(r"\s+", " ", value).strip() - return value - - -def _append_entity(entities: dict, key: str, value: str): - value = _clean_entity_value(value) - if not value: - return - value_clean = clean_text(value) - if not value_clean: - return - current = entities.get(key) - if not current: - entities[key] = value_clean - elif value_clean not in current: - entities[key] = f"{current} {value_clean}".strip() - - -def clean_item_query(text: str) -> str: - q = clean_text(text) - remove_words = [ - "عايز", "عايزه", "عايزة", "عاوز", "عاوزه", "عاوزة", "محتاج", "محتاجة", "نفسي", - "في", "فين", "مطعم", "مطاعم", "كافيه", "مكان", "بيعمل", "بتعمل", "عنده", "عندها", - "فيه", "فيها", "بيقدم", "بتقدم", "لو سمحت", "ممكن", "من فضلك", "قريب", "اقرب", - ] - for w in remove_words: - q = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", q) - q = re.sub(r"\s+", " ", q).strip() - words = [w for w in q.split() if clean_text(w) not in NON_ITEM_WORDS] - q = " ".join(words).strip() - if clean_text(q) in NON_ITEM_WORDS: - return "" - return q - - -def extract_item_query(text: str) -> str: - t = norm(text) - known_items = [ - "شاورما", "برجر", "بيتزا", "كريب", "مشويات", "كباب", "كفته", "كفتة", "فراخ", "نص فراخ", - "نص فرخه", "نص فرخة", "فول", "طعميه", "طعمية", "سمك", "كشري", "حواوشي", "فطير", "لاتيه", "قهوه", "قهوة", - ] - found = [item for item in known_items if norm(item) in t] - if found: - return max(found, key=len) - cleaned = clean_item_query(text) - if not cleaned or clean_text(cleaned) in NON_ITEM_WORDS: - return "" - # Fuzzy typo correction: common typing mistakes (missing letter, doubled - # letter, swapped diacritic-adjacent letters) mean a word like "شورما" - # (missing alef from "شاورما") or "بتزا" (missing ي) won't substring-match - # any known_items entry above, so the user's literal (mis-typed) text - # would be searched verbatim and very likely return zero results even - # though the intended item clearly exists in the menu. Compare each - # word in the cleaned text against known_items by character similarity - # and snap to the closest match if it's close enough to be confident. - cleaned_words = cleaned.split() - for word in cleaned_words: - if len(word) < 3: - continue - best_match, best_ratio = None, 0.0 - for item in known_items: - ratio = difflib.SequenceMatcher(None, norm(word), norm(item)).ratio() - if ratio > best_ratio: - best_ratio, best_match = ratio, item - if best_match and best_ratio >= 0.78: - return best_match - return cleaned - - - - -def is_generic_category_item(value: str) -> bool: - q = clean_text(value) - generic = { - "مطعم", "مطاعم", "اكل", "أكل", "مكان", - "كافيه", "كافيهات", "قهوه", "قهوة", "كوفي", - "صيدليه", "صيدلية", "صيدليات", "صيدله", - "ماركت", "سوبر", "سوبرماركت", "سوبر ماركت", - } - return q in {clean_text(x) for x in generic} - -def extract_menu_place_name(text: str) -> str: - t = clean_text(text) - for w in ["هات", "ابعت", "وريني", "اعرض", "منيو", "مينيو", "menu", "بتاع", "قائمة"]: - t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t) - return re.sub(r"\s+", " ", t).strip() - - -def extract_entities(text: str, min_score: float = 0.35) -> dict: - entities = {} - if ner_pipe is not None: - try: - raw = ner_pipe(text) - for item in raw: - label = str(item.get("entity_group") or item.get("entity") or "").upper().replace("B-", "").replace("I-", "") - value = _clean_entity_value(item.get("word", "")) - score = float(item.get("score", 1.0)) - if score < min_score or len(value) < 2: - continue - mapped = { - "PLACE_NAME": "place_name", - "ITEM_QUERY": "item_query", - "LOCATION": "location", - "PRICE_RANGE": "price_range", - "PLACE_TYPE": "category", - "PLACE_MOOD": "place_mood", - "TIME_CONTEXT": "time_context", - "COMPARISON_CRITERIA": "comparison_criteria", - "HOUSING_TYPE": "housing_type", - "FURNISHING": "furnishing", - "ROOM_COUNT": "room_count", - }.get(label, label.lower()) - _append_entity(entities, mapped, value) - except Exception as exc: - log.warning("NER extraction error: %s", exc) - cat = infer_category(text, entities=entities) - if cat: - entities["category"] = cat - if "item_query" not in entities: - item = extract_item_query(text) - cat = infer_category(text) - # extract_item_query() can return a leftover adjective (e.g. "كويس", - # "نضيف") when the sentence is really just "عايز مطعم كويس" — a - # generic category request, not a specific food/drink ask. Only - # trust the fallback item_query if it actually matches one of the - # known food/drink keywords used elsewhere (ITEM_CATEGORY_HINTS), - # otherwise a plain category search would get wrongly redirected - # into search_by_item with a bogus item and return no_result. - known_item_words = set() - for words in ITEM_CATEGORY_HINTS.values(): - known_item_words.update(norm(w) for w in words) - item_is_real = item and any(norm(w) in norm(item) or norm(item) in norm(w) for w in known_item_words) - if item_is_real and (cat == "restaurant" or any(norm(x) in norm(text) for x in ["اكل", "أكل", "جعان", "نفسي", "شاورما", "برجر", "بيتزا", "كريب"])): - entities["item_query"] = item - if "place_name" not in entities: - name_guess = extract_place_name_from_text(text) - if name_guess: - entities["place_name"] = name_guess - return entities - - -def extract_place_name_from_text(text: str) -> str: - t = clean_text(text) - original = t - stop_phrases = [ - "فين", "مكان", "مكانه", "مكانها", "عنوان", "عنوانه", "عنوانها", "لوكيشن", "رقم", "تليفون", - "مطعم", "صيدليه", "صيدلية", "صديليه", "كافيه", "ماركت", "سوبر", "سوبرماركت", "هات", "منيو", "عايز", "عايزة", - "عايزه", "عاوزه", "عاوز", "اروح", "ازاي", "قريب", "اقرب", "مفتوح", "فاتح", "دلوقتي", "في", "من", "عند", - "رقمه", "رقمها", "تليفونه", "تليفونها", "ايه", "إيه", "احسن", "أحسن", "افضل", "أفضل", "اعلى", "أعلى", "توب", "التوب", - "طب", "طيب", "تمام", "ماشي", "كام", "بكام", "قد ايه", "مين", - "مواعيد", "معاد", "ميعاد", "بيفتح", "بتفتح", "بيقفل", "بتقفل", "امتى", "امتي", "شغال", "شغاله", "شغالة", - "الصبح", "بالليل", "بالنهار", "النهارده", "بكرة", "بكره", - ] - # Arabic words frequently carry attached possessive/verb suffixes - # (e.g. "مواعيده" = "مواعيد" + "ه", "بيفتحوا" = "بيفتح" + "وا") AND a - # leading "و" (conjunction "and" — "وعنوانه", "ورقمه", "ومواعيده" are - # extremely common in spoken Egyptian Arabic, e.g. "طب وعنوانه فين؟"). - # A plain \bword\b match misses both, since the prefix/suffix breaks - # the word boundary. Allow an optional leading "و" and a short trailing - # suffix so these collapse to nothing instead of leaving a fake place - # name like "وعنوانه" behind. - for w in stop_phrases: - cw = clean_text(w) - t = re.sub(rf"\bو?{re.escape(cw)}[ههاويوا]{{0,3}}\b", " ", t) - t = re.sub(r"\s+", " ", t).strip() - if not t or len(t) < 2: - return "" - if t in ["هنا", "هناك", "ده", "دي", "هو", "هي"]: - return "" - # English place names must be checked BEFORE the infer_category - # short-circuit below. Many real venue names legitimately contain a - # category word inside them (e.g. "Grand Cafe", "City Market", "Ouzi - # Restaurant") — if we ran the category check first, infer_category() - # would match "cafe"/"market"/"restaurant" and wrongly discard the - # whole name as a generic category mention instead of a specific place. - if re.search(r"[a-zA-Z]", t) and len(t.split()) <= 5: - return t - if infer_category(t) and len(t.split()) <= 2: - return "" - if any(w in original for w in ["فين", "مكان", "عنوان", "لوكيشن", "منيو", "رقم", "مواعيد", "بيفتح", "بتفتح"]) and len(t.split()) <= 5: - return t - return "" - - - -def has_any(text: str, words: list) -> bool: - t = norm(text) - return any(norm(w) in t for w in words if norm(w)) - - -def intended_item_category(item_query: str) -> str: - q = norm(item_query) - if not q: - return "" - for cat, items in ITEM_CATEGORY_HINTS.items(): - if any(norm(item) in q for item in items): - return cat - return "" - - -def item_category_conflict(item_query: str, category: str) -> Optional[str]: - intended = intended_item_category(item_query) - category = normalize_category(category) - if intended and category and intended != category: - return intended - return None - - -def item_matches_place(place: dict, item_query: str, use_menu: bool = True) -> bool: - item = clean_text(item_query) - if not item: - return True - text_blob = clean_text(" ".join([ - str(place.get("name", "")), str(place.get("name_ar", "")), str(place.get("name_en", "")), - str(place.get("category", "")), str(place.get("sub_category", "")), str(place.get("description", "")), - str(place.get("search_text_clean", "")), - ])) - if item in text_blob: - return True - if use_menu: - try: - for m in fetch_menu(place): - m_blob = clean_text(" ".join(str(m.get(k, "")) for k in ["name", "name_ar", "name_en", "title", "description", "category"])) - if item in m_blob: - return True - except Exception: - return False - return False - - -def is_near_query(text: str) -> bool: - return has_any(text, NEAR_WORDS) - - -def is_best_query(text: str, intent: str = "") -> bool: - return has_any(text, BEST_WORDS) or intent in {"best_of", "recommend_place"} - - -def is_best_near_query(text: str, intent: str = "") -> bool: - return is_best_query(text, intent) and is_near_query(text) - - -def compare_place_names(text: str) -> list: - t = clean_text(text) - for w in ["قارن", "قارني", "مقارنة", "بين", "ما بين", "مين احسن", "احسن"]: - t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t) - parts = [p.strip() for p in re.split(r"\s+و\s+|,|،|/|\\|\s+ولا\s+", t) if p.strip()] - cleaned = [] - for p in parts: - p = extract_place_name_from_text(p) or p - if p and p not in cleaned and not infer_category(p): - cleaned.append(p) - return cleaned[:4] - - -def clear_context_on_category_change(session: "Session", new_category: str, new_location: str = "") -> None: - old_category = normalize_category(session.context_slots.get("category", "")) - new_category = normalize_category(new_category) - if new_category and old_category and new_category != old_category: - keep_location = new_location or session.context_slots.get("location", "") - session.context_slots = {} - if keep_location: - session.context_slots["location"] = keep_location - -def semantic_candidates(query: str, top_k: int = SEMANTIC_TOP_K) -> pd.DataFrame: - if corpus_df is None or corpus_df.empty or corpus_embeddings is None: - return pd.DataFrame() - q_emb = semantic_model.encode(clean_text(query), convert_to_tensor=True) - scores = util.cos_sim(q_emb, corpus_embeddings)[0] - k = min(top_k, len(corpus_df)) - top = torch.topk(scores, k=k) - result = corpus_df.iloc[top.indices.cpu().numpy()].copy() - result["semantic_score"] = top.values.cpu().numpy() - return result.reset_index(drop=True) - - -def name_search(place_name: str, category: str = "", top_k: int = 12) -> pd.DataFrame: - if places_df is None or places_df.empty or not place_name: - return pd.DataFrame() - q = clean_text(place_name) - q_words = [w for w in q.split() if len(w) > 1] - df = places_df.copy() - if category: - df = df[df["category_norm"].apply(lambda c: category_matches(c, category))] - if df.empty: - return df - - def score(row): - names = clean_text(" ".join([str(row.get("name", "")), str(row.get("name_ar", "")), str(row.get("name_en", ""))])) - if not names: - return 0.0 - if q == names or q in names or names in q: - return 1.0 - if q_words and all(w in names for w in q_words): - return 0.9 - common = sum(1 for w in q_words if w in names) - return 0.45 + 0.35 * common / max(len(q_words), 1) if common else 0.0 - - df["name_score"] = df.apply(score, axis=1) - df = df[df["name_score"] >= 0.45].sort_values("name_score", ascending=False) - if "semantic_score" not in df.columns: - df["semantic_score"] = df["name_score"] - return df.head(top_k).reset_index(drop=True) - - -def apply_filters(df: pd.DataFrame, category: str = "", location: str = "", price_range: str = "", open_now_only: bool = False) -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - f = df.copy() - if category and "category_norm" in f.columns: - f = f[f["category_norm"].apply(lambda c: category_matches(c, category))] - if location and not f.empty: - loc = clean_text(location) - parts = [p for p in loc.split() if len(p) > 1] - if parts: - mask = f.apply( - lambda r: any(p in clean_text(str(r.get("location", "")) + " " + str(r.get("address", ""))) for p in parts), - axis=1, - ) - loc_filtered = f[mask] - if not loc_filtered.empty: - f = loc_filtered - else: - return pd.DataFrame() - if price_range and not f.empty: - pr = clean_text(price_range) - mask = f["price_range_clean"].astype(str).str.contains(re.escape(pr), na=False) - if mask.any(): - f = f[mask] - if not f.empty: - f["open_now"] = f["opening_hours"].apply(check_open_now) - f["rating_norm"] = pd.to_numeric(f.get("rating", 0), errors="coerce").fillna(0.0) - f["rating_score"] = f["rating_norm"] / 5.0 - f["open_score"] = f["open_now"].apply(lambda x: 1.0 if x == 1 else (0.5 if x is None else 0.1)) - if open_now_only and not f.empty: - opened = f[f["open_now"] == 1] - if not opened.empty: - f = opened - return f.reset_index(drop=True) - - -def rank_places(df: pd.DataFrame, query: str, user_lat=None, user_lon=None, intent: str = "") -> pd.DataFrame: - if df is None or df.empty: - return pd.DataFrame() - f = df.copy() - near = is_near_query(query) - best = is_best_query(query, intent) - if user_lat is not None and user_lon is not None and "lat" in f.columns and "lon" in f.columns: - def dist(row): - try: - lat = float(row.get("lat")) - lon = float(row.get("lon")) - if np.isnan(lat) or np.isnan(lon): - return None - return haversine(float(user_lat), float(user_lon), lat, lon) - except Exception: - return None - f["distance_km"] = f.apply(dist, axis=1) - else: - f["distance_km"] = None - valid = f["distance_km"].dropna() if "distance_km" in f.columns else pd.Series(dtype=float) - mx = valid.max() if not valid.empty else 1.0 - f["distance_score"] = f["distance_km"].apply(lambda d: 1 - d / (mx + 1) if d is not None and not pd.isna(d) else 0.5) - for col, default in [("semantic_score", 0.0), ("rating_score", 0.0), ("open_score", 0.5), ("name_score", 0.0), ("rating_norm", 0.0), ("rating_count", 0.0)]: - if col not in f.columns: - f[col] = default - f[col] = pd.to_numeric(f[col], errors="coerce").fillna(default) - if best and near and user_lat is not None and user_lon is not None: - f["final_score"] = 0.70 * f["rating_score"] + 0.30 * f["distance_score"] - return f.sort_values(["final_score", "rating_count", "semantic_score"], ascending=[False, False, False]).reset_index(drop=True) - if near and user_lat is not None and user_lon is not None: - return f.sort_values(["distance_km", "rating_norm"], ascending=[True, False], na_position="last").reset_index(drop=True) - if best: - return f.sort_values(["rating_norm", "rating_count", "semantic_score"], ascending=[False, False, False]).reset_index(drop=True) - if near and user_lat is None: - return f.sort_values(["semantic_score", "rating_norm"], ascending=[False, False]).reset_index(drop=True) - # "Auto nearest": a plain category request ("عايزة مطعم", "عايز كافيه") - # with NO explicit "أحسن"/"best" wording but WITH a device location - # should still sort strictly by distance, matching what users actually - # expect ("عايزة مطعم" + my location = nearest restaurants first). Without - # this branch, such requests fell through to the generic weighted-score - # path below, where a much-closer low-rated place could rank behind a - # far-away high-rated one — i.e. distance was only ~15% of the score, - # not the dominant factor the user asked for. - if not best and user_lat is not None and user_lon is not None: - return f.sort_values(["distance_km", "rating_norm"], ascending=[True, False], na_position="last").reset_index(drop=True) - if has_any(query, ["كويس", "قريب", "محترم", "نضيف"]) and user_lat is not None and user_lon is not None: - f["final_score"] = 0.55 * f["rating_score"] + 0.30 * f["distance_score"] + 0.15 * f["semantic_score"] - else: - f["final_score"] = 0.45 * f["semantic_score"] + 0.25 * f["rating_score"] + 0.15 * f["distance_score"] + 0.10 * f["open_score"] + 0.05 * f["name_score"] - return f.sort_values("final_score", ascending=False).reset_index(drop=True) - -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: - category = normalize_category(category) - if item_query and not category: - category = intended_item_category(item_query) or "restaurant" - if item_category_conflict(item_query, category): - return pd.DataFrame() - if place_name: - named = name_search(place_name, category=category, top_k=10) - if named.empty: - return pd.DataFrame() - filtered = apply_filters(named, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - if item_query: - base = places_df.copy() if places_df is not None else pd.DataFrame() - base = apply_filters(base, category=category or "restaurant", location=location, price_range=price_range, open_now_only=open_now_only) - if base.empty: - return pd.DataFrame() - rows = [] - for _, row in base.iterrows(): - place = row_to_dict(row) - if item_matches_place(place, item_query, use_menu=True): - rows.append(place) - if not rows: - return pd.DataFrame() - out = pd.DataFrame(rows) - if "semantic_score" not in out.columns: - out["semantic_score"] = 0.80 - out = apply_filters(out, category=category or "restaurant", location="", price_range=price_range, open_now_only=open_now_only) - return rank_places(out, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - # For broad category requests ("عايز كافيه", "احسن مطعم"), use the live DB directly. - # Semantic threshold can wrongly hide valid category results, especially mixed categories like restaurant & café. - if category and places_df is not None and not places_df.empty: - base = apply_filters(places_df.copy(), category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if not base.empty: - if "semantic_score" not in base.columns: - base["semantic_score"] = 0.80 - return rank_places(base, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - - # Pure category queries like "عايزه كافيه" or "احسن مطعم" should not be killed by semantic threshold. - if category and not item_query and not place_name: - base = places_df.copy() if places_df is not None else pd.DataFrame() - filtered = apply_filters(base, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if not filtered.empty: - if "semantic_score" not in filtered.columns: - filtered["semantic_score"] = 0.75 - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - - candidates = semantic_candidates(query, top_k=SEMANTIC_TOP_K) - if candidates.empty: - return pd.DataFrame() - filtered = apply_filters(candidates, category=category, location=location, price_range=price_range, open_now_only=open_now_only) - if filtered.empty: - return pd.DataFrame() - filtered = filtered[pd.to_numeric(filtered.get("semantic_score", 0), errors="coerce").fillna(0) >= SEMANTIC_MIN_SCORE] - if filtered.empty: - return pd.DataFrame() - return rank_places(filtered, query, user_lat, user_lon, intent).drop_duplicates("place_id").head(top_k).reset_index(drop=True) - -def format_place_line(place: dict) -> str: - name = place.get("name") or place.get("name_ar") or "المكان" - loc = place.get("location") or place.get("address") or "بني سويف" - rating = place.get("rating_norm", place.get("rating", 0)) - dist = place.get("distance_km") - rating_txt = f" — ⭐ {rating}" if rating else "" - open_now = place.get("open_now") - open_txt = " — 🟢 مفتوح" if open_now == 1 else (" — 🔴 مغلق" if open_now == 0 else "") - dist_txt = "" - try: - if dist is not None and not pd.isna(dist): - dist_txt = f" — 📍 {float(dist):.1f} كم" - except Exception: - dist_txt = "" - return f"{name} في {loc}{rating_txt}{open_txt}{dist_txt}" - - -def _dynamic_reply(kind: str, **kwargs) -> str: - templates = DYNAMIC_TEMPLATES.get(kind) or DYNAMIC_TEMPLATES["category"] - cat = normalize_category(kwargs.get("category", "")) - data = { - "cat_ar": CAT_AR.get(cat, "أماكن"), - "cat_single": CAT_SINGLE.get(cat, "مكان"), - "item": kwargs.get("item_query") or kwargs.get("item") or "الطلب ده", - "location": kwargs.get("location") or "المنطقة دي", - "best_name": (kwargs.get("best_place") or {}).get("name") or "أول اختيار", - } - try: - return random.choice(templates).format(**data) - except Exception: - return random.choice(templates) - - -RELATED_ITEM_GROUPS = [ - {"وافل", "كريب", "حلويات", "ايس كريم", "آيس كريم", "كنافة", "بسبوسة"}, - {"شاورما", "برجر", "كباب", "كفته", "كفتة", "فراخ", "مشويات"}, - {"بيتزا", "باستا", "مكرونة", "ايطالي", "إيطالي"}, - {"قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "نسكافيه", "شاي"}, - {"عصير", "سموزي", "موهيتو", "مشروبات بارده", "مشروبات باردة"}, -] - -def find_related_item_suggestion(item_query: str, category: str) -> str: - """ - When a requested item has zero results, scan the live places data for - a related/similar item that DOES exist (e.g. "وافل" -> "حلويات"), - instead of just telling the user nothing was found. Returns a short - Arabic phrase naming the related item group found, or "" if none. - """ - if not item_query or places_df is None or places_df.empty: - return "" - iq = norm(item_query) - related_words = set() - for group in RELATED_ITEM_GROUPS: - if any(norm(w) in iq or iq in norm(w) for w in group): - related_words = {w for w in group if norm(w) != iq} - break - if not related_words: - return "" - haystack_col = places_df.get("search_text_clean") - if haystack_col is None: - return "" - for word in related_words: - wn = norm(word) - mask = haystack_col.fillna("").astype(str).apply(lambda s: wn in norm(s)) - if mask.any(): - return word - return "" - - -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: - category = normalize_category(category) - if not results: - if place_name: - return f"مش لاقي {CAT_SINGLE.get(category, 'مكان')} باسم {place_name} حاليًا 😔\nممكن تكتبه بطريقة تانية؟" - if item_query: - return f"مش لاقي {CAT_SINGLE.get(category or 'restaurant', 'مكان')} بيقدم {item_query} في الداتا الحالية 😔\nجرب صنف تاني أو منطقة تانية." - if location and category: - return f"مفيش {CAT_AR.get(category, 'أماكن')} متاحة حاليًا في {location} 😔\nتحب أدور في منطقة تانية؟" - if open_now_only and category: - return f"مش لاقي {CAT_AR.get(category, 'أماكن')} مفتوحة دلوقتي 😔\nأقدر أعرضلك الموجود بس مش مؤكد إنه مفتوح." - return _dynamic_reply("fallback") - if related_item_used: - # These are REAL cards for the related item (e.g. حلويات instead of - # the unavailable وافل) — say so explicitly instead of the generic - # category header, so the text matches what's actually on screen. - return f"ملقتش {CAT_SINGLE.get(category or 'restaurant', 'مكان')} بيقدم {item_query}، لكن لقيت أماكن بتقدم {related_item_used} ممكن تعجبك 👇" - if soft_reason == "open": - header = _dynamic_reply("soft_open", category=category) - elif soft_reason == "near_item": - header = _dynamic_reply("soft_near_item", category=category or "restaurant", item_query=item_query) - elif soft_reason == "area": - header = _dynamic_reply("area_fallback", category=category, location=location) - # The area-fallback results come from dropping the location filter. - # If the original request also asked for open_now and that already - # failed before we dropped location, these alternatives are not - # guaranteed to be open either — say so explicitly instead of - # presenting them as a plain location-only fallback. - if open_uncertain: - header += "\nوبرضو حالة الفتح دلوقتي مش مؤكدة لكل الأماكن دي، يفضل تتأكد بمكالمة قبل ما تروح 📞" - elif item_query: - header = _dynamic_reply("item", category=category or "restaurant", item_query=item_query) - elif is_best_near_query(query, intent): - header = _dynamic_reply("best_near", category=category, best_place=results[0]) - elif is_near_query(query) and user_has_location: - header = _dynamic_reply("nearest", category=category, best_place=results[0]) - elif is_near_query(query) and not user_has_location: - header = _dynamic_reply("near_no_location", category=category, best_place=results[0]) - elif is_best_query(query, intent): - header = _dynamic_reply("best", category=category, best_place=results[0]) - elif open_now_only: - header = _dynamic_reply("open", category=category, best_place=results[0]) - elif len(results) == 1: - header = _dynamic_reply("one", category=category, best_place=results[0]) - else: - header = _dynamic_reply("category", category=category, best_place=results[0]) - if len(results) > MAX_CARDS: - header += "\n\nفي أماكن تانية كمان، اكتبي «كمان» لو عايزاهم." - return header - -def handle_detail(text: str, place: Optional[dict]) -> str: - if not place: - return "تقصد أنهي مكان؟ اكتب اسم المكان أو اسألني الأول عن مطعم/صيدلية/كافيه. 😊" - t = norm(text) - name = place.get("name") or place.get("name_ar") or "المكان" - if any(w in t for w in ["رقم", "تليفون", "تلفون", "phone", "اتصل"]): - phone = place.get("phone") or "" - return f"📞 {name}: {phone}" if phone else f"😔 الرقم غير متاح لـ {name} حاليًا." - if any(w in t for w in ["عنوان", "فين", "مكان", "لوكيشن", "الموقع", "ازاي اروح"]): - addr = place.get("address") or place.get("location") or "العنوان غير متاح" - lat = place.get("lat") - lon = place.get("lon") - maps = f"\n🗺️ https://maps.google.com/?q={lat},{lon}" if lat not in (None, "", np.nan) and lon not in (None, "", np.nan) else "" - return f"📍 {name}: {addr}{maps}" - if any(w in t for w in ["مواعيد", "بيفتح", "بتفتح", "امتى", "امتي"]): - hours = place.get("opening_hours") or "" - status = check_open_now(hours) - status_txt = "\n🟢 مفتوح دلوقتي" if status == 1 else ("\n🔴 مغلق دلوقتي" if status == 0 else "") - return f"🕐 {name}: {hours or 'المواعيد غير متاحة'}{status_txt}" - if any(w in t for w in ["تقييم", "نجمة", "rating"]): - return f"⭐ {name}: {place.get('rating_norm', place.get('rating', 0)) or 'التقييم غير متاح'}" - if any(w in t for w in ["سعر", "بكام", "غالي", "رخيص"]): - return f"💰 {name}: {place.get('price_range') or 'السعر غير متاح'}" - return format_place_line(place) - - -def fetch_menu(place: dict) -> list: - place_id = str(place.get("id") or place.get("place_id") or "") - if not place_id: - return [] - if place_id in MENU_CACHE: - return MENU_CACHE[place_id] - endpoints = [ - f"{AROUNDU_BASE}/places/{place_id}/menu", - f"{AROUNDU_BASE.replace('/api/v1/ai/data', '')}/api/mobile/places/{place_id}/menu", - ] - for url in endpoints: - try: - resp = requests.get(url, headers=_headers(), timeout=20) - if resp.status_code != 200: - continue - items = _extract_payload_data(resp.json()) - if items: - MENU_CACHE[place_id] = items - return items - except Exception: - continue - MENU_CACHE[place_id] = [] - return [] - - -def detect_ref_type(text: str) -> str: - t = norm(text) - if any(w in t for w in NEXT_WORDS): - return "next" - if any(w in t for w in DETAIL_WORDS): - # "فين أقرب كافيه" contains "فين" (a DETAIL_WORD) but is clearly a - # brand-new category search, not a follow-up about the place - # already in context. Only treat it as "detail" if the sentence - # doesn't also introduce a new category/proximity request. - if any(w in t for w in NEW_SEARCH_SIGNAL_WORDS): - return "new" - return "detail" - if any(w in t for w in REF_WORDS): - return "reference" - return "new" - - -class Session: - def __init__(self, sid="default"): - self.sid = sid - self.last_active = time.time() - self.history = [] - self.last_intent = None - self.last_entities = {} - self.last_place = None - self.last_results = [] - self.result_pointer = 0 - self.context_slots = {} - self.turns = 0 - - def add(self, user, bot, intent, entities, place, results): - self.last_active = time.time() - self.history.append({"turn": self.turns, "user": user, "bot": bot, "intent": intent, "entities": entities}) - if len(self.history) > 10: - self.history = self.history[-10:] - if intent and intent not in NO_CARD_INTENTS and intent not in {"no_result", "out_of_scope"}: - self.last_intent = intent - self.last_entities = entities or {} - if place: - self.last_place = place - if results: - self.last_results = results - # First response shows MAX_CARDS cards; "كمان" starts after them. - self.result_pointer = min(MAX_CARDS, len(results)) - for key in ["category", "location", "price_range", "item_query", "place_name"]: - if entities and entities.get(key): - self.context_slots[key] = entities[key] - self.turns += 1 - - def merge(self, new_entities): - merged = dict(self.context_slots) - for k, v in (new_entities or {}).items(): - if v: - merged[k] = v - return merged - - -def row_to_dict(row) -> dict: - if isinstance(row, dict): - return row - if hasattr(row, "to_dict"): - d = row.to_dict() - else: - d = dict(row) - clean = {} - for k, v in d.items(): - if isinstance(v, (np.integer, np.floating)): - v = v.item() - if pd.isna(v) if not isinstance(v, (list, dict, tuple)) else False: - v = None - clean[k] = v - return clean - - -def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict: - text = str(text or "").strip() - if not text: - return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} - - ref_type = detect_ref_type(text) - if ref_type == "next" and session.last_results: - start = int(session.result_pointer or 0) - if start >= len(session.last_results): - reply = "دي كانت كل النتائج المتاحة حاليًا 😊\nلو حابب، جرّب منطقة تانية أو نوع تاني." - session.add(text, reply, "show_more", session.last_entities, session.last_place, session.last_results) - session.result_pointer = len(session.last_results) - return {"reply": reply, "intent": "show_more", "confidence": 1.0, "entities": session.last_entities, "best_place": session.last_place, "all_results": []} - end = min(start + MAX_CARDS, len(session.last_results)) - batch = session.last_results[start:end] - session.result_pointer = end - place = batch[0] if batch else session.last_place - reply = "دي أماكن تانية كمان 👇" - if session.result_pointer < len(session.last_results): - reply += "\nوفيه كمان لو حبيتي." - else: - reply += "\nدي آخر الأماكن المتاحة عندي حاليًا." - session.add(text, reply, session.last_intent or "show_more", session.last_entities, place, session.last_results) - # Session.add() resets result_pointer to MAX_CARDS when results are passed. - # Preserve the real pagination offset so the next "كمان" returns the next batch. - session.result_pointer = end - return {"reply": reply, "intent": "show_more", "confidence": 1.0, "entities": session.last_entities, "best_place": place, "all_results": batch} - - if ref_type == "detail" and session.last_place and not extract_place_name_from_text(text): - reply = handle_detail(text, session.last_place) - session.add(text, reply, "place_details", session.last_entities, session.last_place, session.last_results) - return {"reply": reply, "intent": "place_details", "confidence": 1.0, "entities": session.last_entities, "best_place": session.last_place, "all_results": [session.last_place]} - - intent_info = predict_intent(text) - intent = intent_info["intent"] - confidence = intent_info["confidence"] - entities = extract_entities(text) - if intent == "place_details" and not session.last_place and not entities.get("place_name"): - reply = "تقصد رقم أو عنوان أنهي مكان؟ اكتب اسم المكان الأول 😊" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - # NER-derived category (entities.get("category")) is more precise than the - # generic keyword scan in infer_category(), since it comes from the - # trained PLACE_TYPE entity. Only fall back to infer_category() when NER - # found nothing, instead of letting the keyword scan overwrite it. - category = entities.get("category") or infer_category(text, intent, entities) - if category: - entities["category"] = category - location_from_text = entities.get("location", "") - clear_context_on_category_change(session, category, location_from_text) - - if (intent in {"best_of", "sort_results"} or has_any(text, BEST_WORDS)) and not category and not session.context_slots.get("category"): - reply = "أحسن إيه بالظبط؟ مطعم ولا كافيه ولا صيدلية ولا ماركت؟ 😊" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - - if intent in {"greeting", "thanks", "goodbye", "confirm", "deny", "fallback", "out_of_scope"}: - # Before giving up with a generic fallback/out_of_scope reply, check - # whether the message is actually just a bare place name ("لاميرا", - # "on public", "سلطان الشام"). The intent classifier has very little - # signal to work with on a 1-3 word input with no verb or category - # keyword, so it often mis-routes these to fallback/out_of_scope. - # Typing just a place name is one of the most common real-world - # search patterns, so we try a direct name_search before bailing out. - candidate_name = entities.get("place_name") or extract_place_name_from_text(text) - if intent != "out_of_scope" and candidate_name and len(candidate_name) >= 2: - named_df = name_search(candidate_name, top_k=5) - if not named_df.empty: - named_results = [row_to_dict(r) for _, r in named_df.iterrows()] - best = named_results[0] - reply = build_response(named_results, "place_details", place_name=candidate_name, query=text) - session.add(text, reply, "place_details", entities, best, named_results) - return {"reply": reply, "intent": "place_details", "confidence": confidence, "entities": entities, "best_place": best, "all_results": named_results} - replies = { - "greeting": "أهلاً 😊 قولي بتدور على إيه في بني سويف: مطعم، كافيه، صيدلية، ماركت أو سكن؟", - "thanks": "العفو 😊 في حاجة تانية أساعدك فيها؟", - "goodbye": "مع السلامة 👋 أي وقت تحتاج مكان في بني سويف أنا موجود.", - "confirm": "تمام 😊 محتاج إيه تاني؟", - "deny": "تمام، قولي قصدك إيه بالظبط وأنا أظبطهولك 😊", - "out_of_scope": "أنا مخصص لمساعدة أهل وزوار بني سويف في الأماكن والخدمات زي المطاعم والكافيهات والصيدليات والماركت والسكن 😊", - "fallback": _dynamic_reply("fallback"), - } - reply = replies[intent] - session.add(text, reply, intent, entities, None, []) - return {"reply": reply, "intent": intent, "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - - if intent == "compare_places": - names = compare_place_names(text) - if len(names) < 2: - reply = "اكتب اسمين عشان أقارن بينهم 😊 مثال: قارن بين أريكا كافيه ولاميرا" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - found, missing = [], [] - for name in names: - hits = name_search(name, top_k=1) - if hits.empty: - missing.append(name) - else: - found.append(row_to_dict(hits.iloc[0])) - if not found: - reply = "مش لاقي الأماكن اللي عايز تقارن بينها حاليًا 😔\nاكتب الاسمين بشكل أوضح." - session.add(text, reply, "no_result", entities, None, []) - return {"reply": reply, "intent": "no_result", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - found = rank_places(pd.DataFrame(found), text, user_lat, user_lon, "best_of").to_dict("records") - if missing: - reply = f"لقيت {', '.join([p.get('name','') for p in found])}، لكن مش لاقي {', '.join(missing)} حاليًا في قاعدة البيانات.\nرتبتلك الموجود حسب التقييم 👇" - else: - reply = _dynamic_reply("best", category=normalize_category(found[0].get("category", "")), best_place=found[0]) - session.add(text, reply, "compare_places", entities, found[0], found) - return {"reply": reply, "intent": "compare_places", "confidence": confidence, "entities": entities, "best_place": found[0], "all_results": found} - - if intent == "show_menu": - menu_cat = infer_category(text, intent, entities) - if menu_cat in {"pharmacy", "supermarket", "housing"}: - reply = "المنيو متاح للمطاعم والكافيهات بس 😊\nلو عايز عنوان أو رقم صيدلية/ماركت اكتب اسمها." - session.add(text, reply, "show_menu", entities, None, []) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": None, "all_results": [], "menu_items": []} - place_name = entities.get("place_name") or extract_menu_place_name(text) - hits = name_search(place_name, category="restaurant", top_k=1) if place_name else pd.DataFrame() - if hits.empty: - hits = name_search(place_name, category="cafe", top_k=1) if place_name else pd.DataFrame() - if hits.empty: - reply = f"مش لاقي مطعم أو كافيه باسم {place_name or 'ده'} عشان أجيب المنيو 😔" - session.add(text, reply, "show_menu", entities, None, []) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": None, "all_results": [], "menu_items": []} - place = row_to_dict(hits.iloc[0]) - items = fetch_menu(place) - reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔" - session.add(text, reply, "show_menu", entities, place, [place]) - return {"reply": reply, "intent": "show_menu", "confidence": confidence, "entities": entities, "best_place": place, "all_results": [place], "menu_items": items} - - if intent == "place_details" and entities.get("place_name"): - hits = name_search(entities["place_name"], category=category, top_k=1) - if not hits.empty: - place = row_to_dict(hits.iloc[0]) - reply = handle_detail(text, place) - session.add(text, reply, intent, entities, place, [place]) - return {"reply": reply, "intent": intent, "confidence": confidence, "entities": entities, "best_place": place, "all_results": [place]} - - merged = session.merge(entities) - if not category and merged.get("category"): - category = merged.get("category") - entities["category"] = category - item_query = entities.get("item_query", "") - if item_query and is_generic_category_item(item_query): - item_query = "" - entities.pop("item_query", None) - place_name = entities.get("place_name", "") - location = entities.get("location") or merged.get("location", "") - price_range = entities.get("price_range", "") - if intent == "search_by_item" and not item_query: - item_query = extract_item_query(text) - if item_query: - entities["item_query"] = item_query - if item_query and not category: - category = intended_item_category(item_query) or "restaurant" - entities["category"] = category - conflict = item_category_conflict(item_query, category) - if conflict: - reply = f"حاسس إن فيه تعارض في الطلب 😊\n{item_query} غالبًا تابع لـ {CAT_AR.get(conflict, conflict)} مش {CAT_AR.get(category, category)}. تقصدي أدورلك فين؟" - session.add(text, reply, "missing_info", entities, None, []) - return {"reply": reply, "intent": "missing_info", "confidence": confidence, "entities": entities, "best_place": None, "all_results": []} - open_now_only = intent in {"open_now", "open_now_extended", "availability_question"} or has_any(text, OPEN_WORDS) - if intent in {"recommendation_by_mood", "recommend_place"} and not category: - category = infer_category(text) or "cafe" - entities["category"] = category - - results_df = search_places(text, 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=12) - soft_reason = "" - open_also_failed = False - if results_df.empty and open_now_only and category: - results_df = search_places(text, category=category, item_query=item_query, location=location, price_range=price_range, open_now_only=False, place_name=place_name, user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - soft_reason = "open" if not results_df.empty else "" - if results_df.empty: - open_also_failed = True - if results_df.empty and location and category: - results_df = search_places(text, category=category, item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name=place_name, user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - if not results_df.empty: - soft_reason = "area" - # If the caller also asked for open_now and that already failed - # before we dropped location, the area-fallback results are not - # guaranteed to be open either — build_response should say so - # rather than presenting them as a plain alternative. - if open_now_only: - open_also_failed = True - if results_df.empty and item_query and is_near_query(text): - results_df = search_places(text, category=category or "restaurant", item_query=item_query, location="", price_range=price_range, open_now_only=False, place_name="", user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - soft_reason = "near_item" if not results_df.empty else soft_reason - related_item_used = "" - if results_df.empty and item_query and not soft_reason: - # Don't just SAY "we found places with حلويات instead" — actually - # search for that related item and return its real cards. Otherwise - # the reply text promises results that never appear for the user - # to tap on, which is worse than saying nothing was found at all. - related = find_related_item_suggestion(item_query, category or "restaurant") - if related: - related_df = search_places(text, category=category or "restaurant", item_query=related, location=location, price_range=price_range, open_now_only=False, place_name="", user_lat=user_lat, user_lon=user_lon, intent=intent, top_k=12) - if not related_df.empty: - results_df = related_df - related_item_used = related - results = [row_to_dict(r) for _, r in results_df.iterrows()] if not results_df.empty else [] - best = results[0] if results else None - result_intent = intent if results else "no_result" - reply = build_response( - results, - intent, - category=category, - item_query=item_query, - place_name=place_name, - location=location, - open_now_only=open_now_only, - soft_reason=soft_reason, - query=text, - open_uncertain=open_also_failed and soft_reason == "area", - user_has_location=(user_lat is not None and user_lon is not None), - related_item_used=related_item_used, - ) - session.add(text, reply, result_intent, entities, best, results) - return {"reply": reply, "intent": result_intent, "confidence": confidence, "entities": entities, "best_place": best, "all_results": results} -@asynccontextmanager -async def lifespan(app: FastAPI): - global intent_pipe, ner_pipe, semantic_model, STARTUP_COMPLETE - log.info("Starting AroundU chatbot backend") - - # Each model loads in its own try block: one model failing to load - # should not block the others from working. STARTUP_COMPLETE is set - # True as long as intent + NER (the core chat path) are usable, even - # if the semantic model or the live places index fails to load. - try: - intent_pipe = pipeline("text-classification", model=INTENT_REPO, tokenizer=INTENT_REPO, return_all_scores=False) - log.info("Intent pipeline loaded from %s", INTENT_REPO) - except Exception as exc: - intent_pipe = None - log.exception("Intent model failed to load: %s", exc) - - try: - ner_pipe = pipeline("ner", model=ENTITY_REPO, tokenizer=ENTITY_REPO, aggregation_strategy="simple") - log.info("Entity pipeline loaded from %s", ENTITY_REPO) - except Exception as exc: - ner_pipe = None - log.exception("Entity model failed to load: %s", exc) - - try: - semantic_model = SentenceTransformer(SEMANTIC_MODEL_NAME) - log.info("Semantic model loaded: %s", SEMANTIC_MODEL_NAME) - except Exception as exc: - semantic_model = None - log.exception("Semantic model failed to load: %s", exc) - - try: - if semantic_model is not None: - rebuild_dynamic_index(force=True) - else: - log.warning("Skipping places index build — semantic model unavailable") - except Exception as exc: - log.exception("Places index build failed: %s", exc) - - STARTUP_COMPLETE = intent_pipe is not None and ner_pipe is not None - if STARTUP_COMPLETE: - log.info("Startup complete (core chat path ready)") - else: - log.error("Startup incomplete — intent/NER unavailable, chat endpoint will return 503") - yield - - -app = FastAPI( - title="Beni Suef Chatbot API", - description="شات بوت ذكي للبحث عن الأماكن في بني سويف 🇪🇬", - version="4.0.0", - lifespan=lifespan, -) -app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) - - -class ChatRequest(BaseModel): - message: str - session_id: str = "default" - lat: Optional[float] = None - lon: Optional[float] = None - user_lat: Optional[float] = None - user_lon: Optional[float] = None - - def resolved_lat(self): - return self.lat if self.lat is not None else self.user_lat - - def resolved_lon(self): - return self.lon if self.lon is not None else self.user_lon - -class ChatData(BaseModel): - reply: str - intent: str - confidence: float - entities: dict = Field(default_factory=dict) - session_id: str - ui_type: str = CFG.UI_TEXT_ONLY - best_place: Optional[dict] = None - place_cards: List[dict] = Field(default_factory=list) - menu_items: List[dict] = Field(default_factory=list) +# ========================= +# QA HARDENING PATCH (V19) +# ========================= +# Last-mile protections for real users: fixed Islamic greetings, stronger +# phonetic place-name matching, and safer generic product/category routing. +ISLAMIC_GREETING_REPLY = "وعليكم السلام ورحمة الله وبركاته 🌹\nأهلاً بيك، محتاج إيه في بني سويف؟ مطعم، كافيه، صيدلية، ماركت أو سكن؟" -class ChatResponse(BaseModel): - data: ChatData +def is_islamic_greeting(text: str) -> bool: + t = norm(text) + return ( + "السلام عليكم" in t + or "سلام عليكم" in t + or "السلم عليكم" in t + or "سلامو عليكم" in t + ) +# Strengthen generic item/product routing. +EXTRA_ITEM_SYNONYMS = { + "ايسكوفي": "ايس كوفي", "ايس كوفى": "ايس كوفي", "ايس كوفي": "ايس كوفي", + "ايس كافي": "ايس كوفي", "ايسكافي": "ايس كوفي", "ايس لاتيه": "ايس لاتيه", + "ايس كريم": "ايس كريم", "ايسكريم": "ايس كريم", + "دوا": "دواء", "دواء": "دواء", "دواء برد": "دواء", "علاج": "دواء", "ادويه": "دواء", "ادوية": "دواء", + "شيبسى": "شيبسي", "شيبصي": "شيبسي", "شيبسي": "شيبسي", + "بيبسى": "بيبسي", "بيبصي": "بيبسي", "بيبسي": "بيبسي", + "شورما": "شاورما", "شاورمه": "شاورما", "بتزا": "بيتزا", "بيتزاا": "بيتزا", + "مكس لحوم": "ميكس لحوم", "ميكس لحوم": "ميكس لحوم", +} +try: + ITEM_SYNONYMS.update(EXTRA_ITEM_SYNONYMS) +except NameError: + ITEM_SYNONYMS = EXTRA_ITEM_SYNONYMS.copy() + +# Generic transliteration tokens, not per-place aliases. These help new DB names +# that contain common English words written in Arabic. +EXTRA_PLACE_WORDS = { + "اند": "and", "ان": "and", "اندد": "and", "اندى": "and", "اندو": "and", + "كافيه": "cafe", "كافي": "cafe", "كافى": "cafe", "كوفي": "coffee", "كوفى": "coffee", + "مطعم": "restaurant", "ريستورانت": "restaurant", "ماركت": "market", "هايبر": "hyper", "مول": "mall", + "بابلك": "public", "بوبلك": "public", "ببلك": "public", "بابليك": "public", + "جراند": "grand", "رويال": "royal", "كينج": "king", "كوين": "queen", "فاميلي": "family", "فاميلى": "family", + "ستار": "star", "ستارز": "stars", "سنتر": "center", "سينتر": "center", "سيتي": "city", "سيتى": "city", + "شوب": "shop", "ستور": "store", "هاوس": "house", "هوم": "home", "كورنر": "corner", + "بيتزا": "pizza", "بايك": "bike", "برجر": "burger", "تشكن": "chicken", "فرايد": "fried", + "بافي": "puffy", "بوفي": "puffy", "فلافي": "fluffy", "فلافى": "fluffy", +} -def _first_value(place: dict, *keys, default=None): - for key in keys: - value = place.get(key) - if value is not None and value != "" and str(value).lower() not in ("nan", "none"): - return value - return default +_old_ar_to_latin_guess_v19 = ar_to_latin_guess +def ar_to_latin_guess(text: Any) -> str: + src = clean_text(text) + if not src: + return "" + # Apply generic word replacements before falling back to character-level transliteration. + words = [EXTRA_PLACE_WORDS.get(w, w) for w in src.split()] + replaced = " ".join(words) + # If replacement produced Latin tokens, keep them and transliterate remaining Arabic chars. + guessed = _old_ar_to_latin_guess_v19(replaced) + return guessed or replaced -def _safe_float(value): - try: - if value is None or value == "": - return None - x = float(value) - if np.isnan(x) or np.isinf(x): - return None - return round(x, 2) - except Exception: - return None +_old_extract_item_query_v19 = extract_item_query +def extract_item_query(text: str) -> str: + t = clean_text(text) + t_no = t.replace(" ", "") + for raw, canonical in ITEM_SYNONYMS.items(): + raw_clean = clean_text(raw) + if raw_clean and (raw_clean in t or raw_clean.replace(" ", "") in t_no): + return canonical + item = _old_extract_item_query_v19(text) + return normalize_item_query(item) if item else "" -def _safe_int(value): - try: - if value is None or value == "": - return 0 - return int(float(value)) - except Exception: - return 0 +_old_intended_item_category_v19 = intended_item_category +def intended_item_category(item_query: str) -> str: + q = normalize_item_query(item_query) + if not q: + return "" + if any(x in q for x in ["دواء", "علاج", "مسكن", "مرهم", "فيتامين"]): + return "pharmacy" + if any(x in q for x in ["شيبسي", "بيبسي", "سناكس", "مياه", "لبن", "عيش", "سكر", "رز", "شوكولاته", "بسكوت"]): + return "supermarket" + if any(x in q for x in ["قهوة", "قهوه", "لاتيه", "كابتشينو", "اسبريسو", "موكا", "نسكافيه", "ايس كوفي", "ايس لاتيه", "شاي", "مشروبات", "ايس كريم", "وافل", "حلويات"]): + return "cafe" + return _old_intended_item_category_v19(q) or "restaurant" -def clean_place(place: dict) -> dict: - if not place: - return {} - lat = _safe_float(_first_value(place, "lat", "latitude")) - lon = _safe_float(_first_value(place, "lon", "lng", "longitude")) - distance = _safe_float(_first_value(place, "distance_km")) - rating = _safe_float(_first_value(place, "rating_norm", "rating", default=0.0)) or 0.0 - open_raw = _first_value(place, "is_open", "open_now") - if isinstance(open_raw, bool): - is_open = open_raw - elif open_raw in (1, "1", "true", "True", "open", "مفتوح"): - is_open = True - elif open_raw in (0, "0", "false", "False", "closed", "مغلق"): - is_open = False - else: - is_open = None - phone_val = _first_value(place, "phone", "mobile", "telephone", default="") - if isinstance(phone_val, (list, tuple)): - phone_val = ", ".join(str(x) for x in phone_val if x) - elif isinstance(phone_val, str) and phone_val.startswith("[") and phone_val.endswith("]"): - phone_val = phone_val.strip("[]").replace("'", "").replace('"', "").strip() - phone_val = (phone_val or "").strip() - has_phone = bool(phone_val) - return { - "id": str(_first_value(place, "id", "place_id", default="")), - "place_id": str(_first_value(place, "place_id", "id", default="")), - "name": _first_value(place, "name", "name_ar", "name_en", default=""), - "category": str(_first_value(place, "category", default="")).lower().strip(), - "sub_category": _first_value(place, "sub_category", "subcategory", default=""), - "rating": rating, - "rating_count": _safe_int(_first_value(place, "rating_count", "review_count", "reviews_count", default=0)), - "address": _first_value(place, "address", "location", default=""), - "description": _first_value(place, "description", default=""), - "is_open": is_open, - "opening_hours": _first_value(place, "opening_hours", "openning_hours", default=""), - "distance_km": distance, - "image": _first_value(place, "image", "image_url", "main_image_url", "photo", "photo_url", default="") or "", - "phone": phone_val if has_phone else None, - "has_phone": has_phone, - "lat": lat, - "lon": lon, - "is_favorited": bool(_first_value(place, "is_favorited", "is_favorite", default=False)), - "final_score": _safe_float(_first_value(place, "final_score")), - } +# Update place aliases conservatively only for common spelling families seen in production tests. +try: + PLACE_NAME_ALIASES.update({ + "انتيكا": ["antika"], "انتكا": ["antika"], "انتيكه": ["antika"], + "بافي اند فلافي": ["puffy fluffy", "puffy and fluffy", "puffy & fluffy"], + "بافي فلافي": ["puffy fluffy", "puffy and fluffy", "puffy & fluffy"], + }) +except NameError: + PLACE_NAME_ALIASES = {} +_old_chat_v19 = chat -def make_chat_response( - *, reply: str, intent: str, confidence: float, entities: dict, session_id: str, - ui_type: str = CFG.UI_TEXT_ONLY, best_place: Optional[dict] = None, - place_cards: Optional[list] = None, menu_items: Optional[list] = None, -) -> ChatResponse: - place_cards = place_cards or [] - menu_items = menu_items or [] - if intent in NO_CARD_INTENTS or ui_type == CFG.UI_TEXT_ONLY: - place_cards = [] - best_place = None - if ui_type != CFG.UI_MENU_LIST: - menu_items = [] - ui_type = CFG.UI_TEXT_ONLY - return ChatResponse(data=ChatData( - reply=reply, - intent=intent, - confidence=confidence, - entities=entities or {}, - session_id=session_id, - ui_type=ui_type, - best_place=best_place, - place_cards=place_cards, - menu_items=menu_items, - )) +def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict: + # Absolute first gate: no model/NER/context should handle Islamic greeting. + if is_islamic_greeting(text): + reply = ISLAMIC_GREETING_REPLY + session.add(text, reply, "greeting", {}, None, []) + return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} + return _old_chat_v19(text, session, user_lat, user_lon) +# ========================= +# QA HARDENING PATCH (V20) +# ========================= +# Fix priority: menu/detail phrases must not be swallowed by bare-name search. -def cleanup_sessions(): - now = time.time() - expired = [sid for sid, sess in SESSIONS.items() if now - getattr(sess, "last_active", now) > SESSION_TTL_SEC] - for sid in expired: - del SESSIONS[sid] +_old_looks_like_bare_place_name_v20 = looks_like_bare_place_name +def looks_like_bare_place_name(text: str) -> bool: + t = norm(text) + if not t: + return False + # Commands/details with a name are not "bare names". Let the correct + # menu/details branch handle them first. + command_words = MENU_WORDS + [ + "وريني", "اعرض", "هات", "ابعت", "قائمة", "منيو", "مينيو", + "مواعيد", "ميعاد", "معاد", "عنوان", "رقم", "تليفون", "لوكيشن", + "بيفتح", "بتفتح", "امتى", "امتي", + ] + if any(norm(w) in t for w in command_words): + return False + return _old_looks_like_bare_place_name_v20(text) -@app.get("/", tags=["General"]) -def root(): - return {"status": "ok", "message": "Beni Suef Chatbot is running 🚀", "version": "4.0.0"} +def _resolve_menu_place(text: str): + place_name = extract_menu_place_name(text) or extract_place_name_from_text(text) + if not place_name: + return None, place_name + # Menu belongs to restaurants/cafes, but fallback to all names for mixed/dirty DB categories. + hits = name_search(place_name, category="restaurant", top_k=1) + if hits.empty: + hits = name_search(place_name, category="cafe", top_k=1) + if hits.empty: + hits = name_search(place_name, category="", top_k=1) + if hits.empty: + return None, place_name + return row_to_dict(hits.iloc[0]), place_name -@app.get("/health", tags=["General"]) -def health(): - return { - "status": "healthy" if STARTUP_COMPLETE else "starting", - "models_loaded": bool(intent_pipe and ner_pipe and semantic_model), - "places_count": len(places_df) if places_df is not None else 0, - "embeddings_ok": corpus_embeddings is not None, - } +_old_chat_v20 = chat +def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict: + text = str(text or "").strip() + if not text: + return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} + if is_islamic_greeting(text): + reply = ISLAMIC_GREETING_REPLY + session.add(text, reply, "greeting", {}, None, []) + return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} + if has_any(text, MENU_WORDS) or has_any(text, ["وريني", "اعرض", "هات المنيو", "قائمة الطعام"]): + place, place_name = _resolve_menu_place(text) + if not place: + reply = f"مش لاقي مطعم أو كافيه باسم {place_name or 'ده'} عشان أجيب المنيو 😔" + session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or "")}, None, []) + return {"reply": reply, "intent": "show_menu", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or "")}, "best_place": None, "all_results": [], "menu_items": []} + items = fetch_menu(place) + reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔" + session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or place.get('name',''))}, place, [place]) + 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} + return _old_chat_v20(text, session, user_lat, user_lon) -@app.post("/chat", response_model=ChatResponse, tags=["Chat"]) -@app.post("/ai/chat", response_model=ChatResponse, tags=["Chat"]) -def chat_endpoint(req: ChatRequest): - cleanup_sessions() - if not STARTUP_COMPLETE: - raise HTTPException(status_code=503, detail="الشات بوت لسه بيتحمل — استنى لحظة وجرب تاني 🔄") - if req.session_id not in SESSIONS: - SESSIONS[req.session_id] = Session(req.session_id) - session = SESSIONS[req.session_id] - try: - result = chat(req.message, session, req.resolved_lat(), req.resolved_lon()) - except Exception as exc: - log.exception("Chat error: %s", exc) - raise HTTPException(status_code=500, detail=str(exc)) - intent = result.get("intent", "fallback") - menu_items = result.get("menu_items", []) or [] - all_results = result.get("all_results", []) or [] - if not all_results and result.get("best_place"): - all_results = [result["best_place"]] - unique_cards = [] - seen = set() - if intent not in NO_CARD_INTENTS: - for place in all_results: - card = clean_place(place) - pid = card.get("id") or card.get("place_id") or card.get("name") - if pid and pid not in seen: - seen.add(pid) - unique_cards.append(card) - ui_type = CFG.UI_MENU_LIST if menu_items else (CFG.UI_PLACES_CARDS if unique_cards else CFG.UI_TEXT_ONLY) - return make_chat_response( - reply=result.get("reply", ""), - intent=intent, - confidence=float(result.get("confidence", 0.0) or 0.0), - entities=result.get("entities", {}) or {}, - session_id=req.session_id, - ui_type=ui_type, - best_place=unique_cards[0] if unique_cards else None, - place_cards=unique_cards[:MAX_CARDS], - menu_items=menu_items, - ) +# ========================= +# QA HARDENING PATCH (V21) +# ========================= +# Follow-up menu requests: "المنيو" after a shown place should use last_place. +_old_extract_menu_place_name_v21 = extract_menu_place_name -@app.post("/reload-data", tags=["Admin"]) -def reload_data(x_secret: Optional[str] = Header(default=None)): - if RELOAD_SECRET and x_secret != RELOAD_SECRET: - raise HTTPException(status_code=403, detail="Forbidden") - try: - count = rebuild_dynamic_index(force=True) - return {"status": "ok", "places_count": count} - except Exception as exc: - log.exception("Reload failed: %s", exc) - raise HTTPException(status_code=500, detail=str(exc)) +def extract_menu_place_name(text: str) -> str: + t = clean_text(text) + for w in ["هات", "ابعت", "وريني", "اعرض", "منيو", "المنيو", "مينيو", "المينيو", "menu", "قائمة", "قائمه", "القائمة", "قائمة الطعام", "بتاع", "بتاعت"]: + t = re.sub(rf"\b{re.escape(clean_text(w))}\b", " ", t) + return re.sub(r"\s+", " ", t).strip() +_old_chat_v21 = chat -@app.delete("/session/{session_id}", tags=["Session"]) -def reset_session(session_id: str): - SESSIONS.pop(session_id, None) - return {"status": "reset", "session_id": session_id} +def chat(text: str, session: Session, user_lat=None, user_lon=None) -> dict: + text = str(text or "").strip() + if not text: + return {"reply": "اكتبلي بتدور على إيه في بني سويف 😊", "intent": "missing_info", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} + if is_islamic_greeting(text): + reply = ISLAMIC_GREETING_REPLY + session.add(text, reply, "greeting", {}, None, []) + return {"reply": reply, "intent": "greeting", "confidence": 1.0, "entities": {}, "best_place": None, "all_results": []} + if has_any(text, MENU_WORDS) or has_any(text, ["وريني", "اعرض", "هات المنيو", "قائمة الطعام", "المنيو", "المينيو"]): + place_name = extract_menu_place_name(text) + place = None + if not place_name and session.last_place: + place = session.last_place + else: + place, _ = _resolve_menu_place(text) + if not place: + reply = f"اكتب اسم المطعم أو الكافيه عشان أجيبلك المنيو 😊" + session.add(text, reply, "missing_info", {"place_name": clean_text(place_name or "")}, None, []) + return {"reply": reply, "intent": "missing_info", "confidence": 1.0, "entities": {"place_name": clean_text(place_name or "")}, "best_place": None, "all_results": [], "menu_items": []} + items = fetch_menu(place) + reply = f"ده منيو {place.get('name')} 👇" if items else f"مفيش منيو متاح حاليًا لـ {place.get('name')} 😔" + session.add(text, reply, "show_menu", {"place_name": clean_text(place_name or place.get('name',''))}, place, [place]) + 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} + return _old_chat_v21(text, session, user_lat, user_lon)