Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -22,6 +22,12 @@ from transformers import (
|
|
| 22 |
)
|
| 23 |
from huggingface_hub import snapshot_download, hf_hub_download
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
"""LOGGING"""
|
| 26 |
|
| 27 |
logging.basicConfig(
|
|
@@ -48,6 +54,13 @@ SEMANTIC_REPO = "Youmnaaaa/Semantic-model"
|
|
| 48 |
AROUNDU_BASE = "https://aroundubackend-production.up.railway.app/api/v1/ai/data"
|
| 49 |
AROUNDU_KEY = os.getenv("AROUNDU_API_KEY", "") # ← حطيه في HuggingFace Secrets
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
"""Embeddings cache"""
|
| 52 |
|
| 53 |
CACHE_PATH = os.path.join(BASE_DIR, "embeddings_cache.pkl")
|
|
@@ -3355,7 +3368,7 @@ def search_places(query, top_k_final=5, category=None, sub_category=None,
|
|
| 3355 |
|
| 3356 |
|
| 3357 |
# ═══════════════════════════════════════════════════════════════════════
|
| 3358 |
-
#
|
| 3359 |
# ═══════════════════════════════════════════════════════════════════════
|
| 3360 |
|
| 3361 |
_CAT_SYNONYMS_V2 = {
|
|
@@ -3383,7 +3396,7 @@ _LOCATIONS_V2 = [
|
|
| 3383 |
|
| 3384 |
_STOP_FOR_NAME_V2 = set(clean_text(x) for x in (
|
| 3385 |
list(sum(_CAT_SYNONYMS_V2.values(), [])) + _ITEM_CONTEXT_V2 + _MENU_WORDS_V2 + _RANK_WORDS_V2 + _NEAR_WORDS_V2 + _OPEN_WORDS_V2 +
|
| 3386 |
-
["عايز", "عايزة", "عايزه", "عاوز", "عاوزه", "محتاج", "محتاجة", "محتاجه", "بدور", "دور", "هات", "هاتي", "فين", "مكان", "اماكن", "في", "من", "على", "عن", "لي", "ليا", "لو سمحت", "ممكن"
|
| 3387 |
))
|
| 3388 |
|
| 3389 |
|
|
@@ -3444,7 +3457,7 @@ def _item_candidate_v2(text: str) -> str:
|
|
| 3444 |
loc = _extract_location_v2(text)
|
| 3445 |
cand = _strip_known_parts_v2(text, cat, loc)
|
| 3446 |
# remove generic verbs that are not item names
|
| 3447 |
-
bad_phrases = ["اقدر", "اقدر اذاكر", "اقدر اشتغل", "اقعد", "اشتغل", "اذاكر", "مفروشه", "مفروشة", "اتعشى", "امشي", "كتير", "حاجه", "حاجة"
|
| 3448 |
toks = [w for w in cand.split() if w not in set(clean_text(x) for x in bad_phrases)]
|
| 3449 |
return " ".join(toks).strip()
|
| 3450 |
|
|
@@ -3548,20 +3561,12 @@ def handle_detail(text, place): # noqa: F811
|
|
| 3548 |
|
| 3549 |
|
| 3550 |
def _extract_place_name_v2(text: str, category: str | None, location: str | None) -> str | None:
|
| 3551 |
-
# only for explicit place lookup, not item/mood/open/ranking
|
| 3552 |
if _is_real_item_query_v2(text) or _has_v2(text, _RANK_WORDS_V2) or _has_v2(text, _NEAR_WORDS_V2) or _has_v2(text, _OPEN_WORDS_V2):
|
| 3553 |
return None
|
| 3554 |
cand = _strip_known_parts_v2(text, category, location)
|
| 3555 |
-
generic_verbs = {"اشرب", "اشربه", "اشربي", "اجيب", "جيب", "جيبي", "شرب", "اروح", "اقعد"}
|
| 3556 |
if not cand or len(cand) < 2:
|
| 3557 |
return None
|
| 3558 |
-
if all(w in generic_verbs for w in cand.split()):
|
| 3559 |
-
return None
|
| 3560 |
-
if category in ("cafe", "restaurant", "pharmacy", "supermarket", "housing") and cand in generic_verbs:
|
| 3561 |
-
return None
|
| 3562 |
-
# لو الجملة طلب عام زي "عايزة اشرب كوفي" ماينفعش اشرب تبقى اسم كافيه
|
| 3563 |
-
if category == "cafe" and _has_v2(text, ["اشرب", "اجيب", "كوفي", "قهوة", "قهوه", "coffee"]):
|
| 3564 |
-
return None
|
| 3565 |
# if candidate is a known food/drink, it is not a place name
|
| 3566 |
if _has_v2(cand, _FOOD_HINTS_V2 | _DRINK_HINTS_V2):
|
| 3567 |
return None
|
|
@@ -3929,6 +3934,247 @@ def _final_is_open_followup(text: str) -> bool:
|
|
| 3929 |
and _has_v2(text, ["فاتح", "فاتحة", "فاتحه", "مفتوح", "مفتوحة", "مفتوحه", "شغال"])
|
| 3930 |
)
|
| 3931 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3932 |
_old_chat_before_open_hotfix = chat
|
| 3933 |
|
| 3934 |
def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
|
|
@@ -3936,7 +4182,15 @@ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
|
|
| 3936 |
Final wrapper:
|
| 3937 |
- "ايه اللي فاتح؟" filters last_results, not only last_place.
|
| 3938 |
- open status/card dots use robust opening_hours parser.
|
|
|
|
| 3939 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3940 |
if text and _final_is_open_followup(text) and getattr(session, "last_results", None):
|
| 3941 |
rows = []
|
| 3942 |
for p in list(session.last_results):
|
|
@@ -3984,4 +4238,9 @@ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
|
|
| 3984 |
if fixed_rows:
|
| 3985 |
res["all_results"] = fixed_rows
|
| 3986 |
res["best_place"] = fixed_rows[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3987 |
return res
|
|
|
|
| 22 |
)
|
| 23 |
from huggingface_hub import snapshot_download, hf_hub_download
|
| 24 |
|
| 25 |
+
# Optional Gemini integration (safe fallback if the package/key is missing)
|
| 26 |
+
try:
|
| 27 |
+
from google import genai
|
| 28 |
+
except Exception:
|
| 29 |
+
genai = None
|
| 30 |
+
|
| 31 |
"""LOGGING"""
|
| 32 |
|
| 33 |
logging.basicConfig(
|
|
|
|
| 54 |
AROUNDU_BASE = "https://aroundubackend-production.up.railway.app/api/v1/ai/data"
|
| 55 |
AROUNDU_KEY = os.getenv("AROUNDU_API_KEY", "") # ← حطيه في HuggingFace Secrets
|
| 56 |
|
| 57 |
+
# ── Gemini API ─────────────────────────────────────────────
|
| 58 |
+
# حطي GEMINI_API_KEY في HuggingFace Secrets. لو مش موجود، الكود القديم هيشتغل عادي.
|
| 59 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
|
| 60 |
+
gemini_client = genai.Client(api_key=GEMINI_API_KEY) if (genai is not None and GEMINI_API_KEY) else None
|
| 61 |
+
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-1.5-flash")
|
| 62 |
+
GEMINI_ENABLED = bool(gemini_client)
|
| 63 |
+
|
| 64 |
"""Embeddings cache"""
|
| 65 |
|
| 66 |
CACHE_PATH = os.path.join(BASE_DIR, "embeddings_cache.pkl")
|
|
|
|
| 3368 |
|
| 3369 |
|
| 3370 |
# ═══════════════════════════════════════════════════════════════════════
|
| 3371 |
+
# FINAL_DOCTOR_DEMO_PATCH_V2 — single routing layer to stop case-by-case bugs
|
| 3372 |
# ═══════════════════════════════════════════════════════════════════════
|
| 3373 |
|
| 3374 |
_CAT_SYNONYMS_V2 = {
|
|
|
|
| 3396 |
|
| 3397 |
_STOP_FOR_NAME_V2 = set(clean_text(x) for x in (
|
| 3398 |
list(sum(_CAT_SYNONYMS_V2.values(), [])) + _ITEM_CONTEXT_V2 + _MENU_WORDS_V2 + _RANK_WORDS_V2 + _NEAR_WORDS_V2 + _OPEN_WORDS_V2 +
|
| 3399 |
+
["عايز", "عايزة", "عايزه", "عاوز", "عاوزه", "محتاج", "محتاجة", "محتاجه", "بدور", "دور", "هات", "هاتي", "فين", "مكان", "اماكن", "في", "من", "على", "عن", "لي", "ليا", "لو سمحت", "ممكن"]
|
| 3400 |
))
|
| 3401 |
|
| 3402 |
|
|
|
|
| 3457 |
loc = _extract_location_v2(text)
|
| 3458 |
cand = _strip_known_parts_v2(text, cat, loc)
|
| 3459 |
# remove generic verbs that are not item names
|
| 3460 |
+
bad_phrases = ["اقدر", "اقدر اذاكر", "اقدر اشتغل", "اقعد", "اشتغل", "اذاكر", "مفروشه", "مفروشة", "اتعشى", "امشي", "كتير", "حاجه", "حاجة"]
|
| 3461 |
toks = [w for w in cand.split() if w not in set(clean_text(x) for x in bad_phrases)]
|
| 3462 |
return " ".join(toks).strip()
|
| 3463 |
|
|
|
|
| 3561 |
|
| 3562 |
|
| 3563 |
def _extract_place_name_v2(text: str, category: str | None, location: str | None) -> str | None:
|
| 3564 |
+
# only for explicit place lookup, not item/mood/open/ranking queries
|
| 3565 |
if _is_real_item_query_v2(text) or _has_v2(text, _RANK_WORDS_V2) or _has_v2(text, _NEAR_WORDS_V2) or _has_v2(text, _OPEN_WORDS_V2):
|
| 3566 |
return None
|
| 3567 |
cand = _strip_known_parts_v2(text, category, location)
|
|
|
|
| 3568 |
if not cand or len(cand) < 2:
|
| 3569 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3570 |
# if candidate is a known food/drink, it is not a place name
|
| 3571 |
if _has_v2(cand, _FOOD_HINTS_V2 | _DRINK_HINTS_V2):
|
| 3572 |
return None
|
|
|
|
| 3934 |
and _has_v2(text, ["فاتح", "فاتحة", "فاتحه", "مفتوح", "مفتوحة", "مفتوحه", "شغال"])
|
| 3935 |
)
|
| 3936 |
|
| 3937 |
+
|
| 3938 |
+
|
| 3939 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 3940 |
+
# GEMINI SAFE LAYER — NLU + Reply polish
|
| 3941 |
+
# ═══════════════════════════════════════════════════════════════════════
|
| 3942 |
+
|
| 3943 |
+
_GEMINI_NLU_CACHE = {}
|
| 3944 |
+
|
| 3945 |
+
_ALLOWED_GEMINI_INTENTS = [
|
| 3946 |
+
"nearest_restaurant", "nearest_pharmacy", "nearest_cafe", "nearest_supermarket",
|
| 3947 |
+
"housing_search", "recommend_place", "recommendation_by_mood", "open_now",
|
| 3948 |
+
"place_details", "search_by_item", "show_menu", "menu_query", "compare_places",
|
| 3949 |
+
"show_more", "phone_followup", "greeting", "thanks", "goodbye", "fallback",
|
| 3950 |
+
"missing_info", "out_of_scope", "no_result",
|
| 3951 |
+
]
|
| 3952 |
+
|
| 3953 |
+
_GEMINI_INTENT_ALIASES = {
|
| 3954 |
+
"menu_query": "show_menu",
|
| 3955 |
+
"nearest_place": "recommend_place",
|
| 3956 |
+
"best_of": "recommend_place",
|
| 3957 |
+
"phone": "phone_followup",
|
| 3958 |
+
"details": "place_details",
|
| 3959 |
+
}
|
| 3960 |
+
|
| 3961 |
+
_GEMINI_ENTITY_ALIASES = {
|
| 3962 |
+
"PLACE_TYPE": "category", "place_type": "category", "type": "category",
|
| 3963 |
+
"CATEGORY": "category", "category": "category",
|
| 3964 |
+
"PLACE_NAME": "place_name", "placeName": "place_name", "name": "place_name",
|
| 3965 |
+
"LOCATION": "location", "area": "location", "ADDRESS": "location",
|
| 3966 |
+
"ITEM_QUERY": "item_query", "CUISINE_OR_ITEM": "item_query", "FOOD_TYPE": "item_query",
|
| 3967 |
+
"MENU_REQUEST": "menu_request", "PRICE_RANGE": "price_range", "PRICE": "price_range",
|
| 3968 |
+
"TIME_CONTEXT": "time_context", "COMPARISON_CRITERIA": "comparison_criteria",
|
| 3969 |
+
"RESULT_REFERENCE": "result_reference", "PLACE_MOOD": "place_mood",
|
| 3970 |
+
}
|
| 3971 |
+
|
| 3972 |
+
_GEMINI_CATEGORY_ALIASES = {
|
| 3973 |
+
"مطعم": "restaurant", "مطاعم": "restaurant", "restaurant": "restaurant", "food": "restaurant",
|
| 3974 |
+
"كافيه": "cafe", "كافيهات": "cafe", "cafe": "cafe", "coffee": "cafe",
|
| 3975 |
+
"صيدلية": "pharmacy", "صيدليه": "pharmacy", "pharmacy": "pharmacy",
|
| 3976 |
+
"ماركت": "supermarket", "سوبرماركت": "supermarket", "سوبر ماركت": "supermarket", "market": "supermarket", "supermarket": "supermarket",
|
| 3977 |
+
"سكن": "housing", "شقة": "housing", "شقه": "housing", "فندق": "housing", "housing": "housing", "hotel": "housing",
|
| 3978 |
+
}
|
| 3979 |
+
|
| 3980 |
+
def _extract_json_object(text: str) -> dict:
|
| 3981 |
+
"""Extract first JSON object from Gemini text safely."""
|
| 3982 |
+
if not text:
|
| 3983 |
+
return {}
|
| 3984 |
+
s = str(text).strip().replace("```json", "").replace("```", "").strip()
|
| 3985 |
+
try:
|
| 3986 |
+
return json.loads(s)
|
| 3987 |
+
except Exception:
|
| 3988 |
+
pass
|
| 3989 |
+
m = re.search(r"\{.*\}", s, flags=re.S)
|
| 3990 |
+
if not m:
|
| 3991 |
+
return {}
|
| 3992 |
+
try:
|
| 3993 |
+
return json.loads(m.group(0))
|
| 3994 |
+
except Exception:
|
| 3995 |
+
return {}
|
| 3996 |
+
|
| 3997 |
+
def _normalize_gemini_entities(raw_entities: dict) -> dict:
|
| 3998 |
+
ents = {}
|
| 3999 |
+
if not isinstance(raw_entities, dict):
|
| 4000 |
+
return ents
|
| 4001 |
+
for k, v in raw_entities.items():
|
| 4002 |
+
if v is None:
|
| 4003 |
+
continue
|
| 4004 |
+
if isinstance(v, (list, tuple)):
|
| 4005 |
+
v = " ".join(str(x) for x in v if x)
|
| 4006 |
+
v = str(v).strip()
|
| 4007 |
+
if not v or v.lower() in ("null", "none", "nan"):
|
| 4008 |
+
continue
|
| 4009 |
+
key = _GEMINI_ENTITY_ALIASES.get(k, _GEMINI_ENTITY_ALIASES.get(str(k).upper(), str(k).lower()))
|
| 4010 |
+
if key == "category":
|
| 4011 |
+
vv = clean_text(v)
|
| 4012 |
+
v = _GEMINI_CATEGORY_ALIASES.get(vv, normalize_category(vv))
|
| 4013 |
+
elif key in ("item_query", "place_name", "location", "price_range"):
|
| 4014 |
+
v = clean_item_query(v) if key == "item_query" else clean_text(v)
|
| 4015 |
+
ents[key] = v
|
| 4016 |
+
|
| 4017 |
+
# أكل زي شاورما/برجر/بيتزا => restaurant إجباري
|
| 4018 |
+
if ents.get("item_query") and not ents.get("category"):
|
| 4019 |
+
ents["category"] = "restaurant"
|
| 4020 |
+
return ents
|
| 4021 |
+
|
| 4022 |
+
def gemini_nlu(text: str, session=None) -> dict:
|
| 4023 |
+
"""
|
| 4024 |
+
Gemini يفهم intent/entities فقط. لو مش متاح أو رجع غلط، يرجع {} والكود القديم يكمل.
|
| 4025 |
+
"""
|
| 4026 |
+
if not gemini_client or not text:
|
| 4027 |
+
return {}
|
| 4028 |
+
|
| 4029 |
+
cache_key = clean_text(text)
|
| 4030 |
+
if cache_key in _GEMINI_NLU_CACHE:
|
| 4031 |
+
return _GEMINI_NLU_CACHE[cache_key]
|
| 4032 |
+
|
| 4033 |
+
last_place_name = ""
|
| 4034 |
+
try:
|
| 4035 |
+
lp = getattr(session, "last_place", None) or {}
|
| 4036 |
+
if isinstance(lp, dict):
|
| 4037 |
+
last_place_name = str(lp.get("name", ""))
|
| 4038 |
+
except Exception:
|
| 4039 |
+
pass
|
| 4040 |
+
|
| 4041 |
+
prompt = f"""
|
| 4042 |
+
You are an Arabic NLU engine for a Beni Suef places chatbot.
|
| 4043 |
+
Return ONLY one valid JSON object. No markdown.
|
| 4044 |
+
|
| 4045 |
+
Allowed intents:
|
| 4046 |
+
{_ALLOWED_GEMINI_INTENTS}
|
| 4047 |
+
|
| 4048 |
+
Entity keys allowed:
|
| 4049 |
+
category, place_name, location, item_query, price_range, time_context,
|
| 4050 |
+
menu_request, comparison_criteria, result_reference, place_mood.
|
| 4051 |
+
|
| 4052 |
+
Rules:
|
| 4053 |
+
- Do NOT invent any place.
|
| 4054 |
+
- If the user asks about food item like شاورما / برجر / بيتزا / كريب / فراخ, intent must be search_by_item and category must be restaurant.
|
| 4055 |
+
- If the user asks منيو / menu, intent must be show_menu.
|
| 4056 |
+
- If the user asks رقم / تليفون / phone after previous place, intent must be phone_followup.
|
| 4057 |
+
- If the user asks أقرب / قريب مني and a category exists, use nearest_* intent.
|
| 4058 |
+
- If the user asks مفتوح دلوقتي / فاتح, use open_now.
|
| 4059 |
+
- If the user greets, thanks, or says goodbye, use greeting/thanks/goodbye.
|
| 4060 |
+
- Keep Egyptian Arabic values as written, but normalize category to restaurant/cafe/pharmacy/supermarket/housing.
|
| 4061 |
+
|
| 4062 |
+
Previous place name: {last_place_name}
|
| 4063 |
+
User text: {text}
|
| 4064 |
+
|
| 4065 |
+
JSON schema:
|
| 4066 |
+
{{"intent":"...","confidence":0.0,"entities":{{}},"follow_up_type":"none|phone|details|show_more|open_now"}}
|
| 4067 |
+
""".strip()
|
| 4068 |
+
|
| 4069 |
+
try:
|
| 4070 |
+
response = gemini_client.models.generate_content(model=GEMINI_MODEL, contents=prompt)
|
| 4071 |
+
data = _extract_json_object(getattr(response, "text", ""))
|
| 4072 |
+
if not isinstance(data, dict):
|
| 4073 |
+
return {}
|
| 4074 |
+
intent = str(data.get("intent", "fallback")).strip()
|
| 4075 |
+
intent = _GEMINI_INTENT_ALIASES.get(intent, intent)
|
| 4076 |
+
if intent not in _ALLOWED_GEMINI_INTENTS:
|
| 4077 |
+
intent = "fallback"
|
| 4078 |
+
conf = float(data.get("confidence", 0.85) or 0.85)
|
| 4079 |
+
conf = max(0.0, min(conf, 1.0))
|
| 4080 |
+
ents = _normalize_gemini_entities(data.get("entities", {}))
|
| 4081 |
+
out = {"intent": intent, "confidence": conf, "entities": ents, "follow_up_type": data.get("follow_up_type", "none")}
|
| 4082 |
+
_GEMINI_NLU_CACHE[cache_key] = out
|
| 4083 |
+
return out
|
| 4084 |
+
except Exception as e:
|
| 4085 |
+
log.warning(f"Gemini NLU skipped: {e}")
|
| 4086 |
+
return {}
|
| 4087 |
+
|
| 4088 |
+
def _shorten_places_for_gemini(rows, limit=5):
|
| 4089 |
+
safe = []
|
| 4090 |
+
for p in list(rows or [])[:limit]:
|
| 4091 |
+
if not isinstance(p, dict):
|
| 4092 |
+
continue
|
| 4093 |
+
safe.append({
|
| 4094 |
+
"name": p.get("name", ""),
|
| 4095 |
+
"category": p.get("category", ""),
|
| 4096 |
+
"sub_category": p.get("sub_category", ""),
|
| 4097 |
+
"address": p.get("address", ""),
|
| 4098 |
+
"location": p.get("location", ""),
|
| 4099 |
+
"rating": p.get("rating_norm", p.get("rating", "")),
|
| 4100 |
+
"opening_hours": p.get("opening_hours", ""),
|
| 4101 |
+
"open_now": p.get("open_now", None),
|
| 4102 |
+
"distance_km": p.get("distance_km", None),
|
| 4103 |
+
"phone": p.get("phone", ""),
|
| 4104 |
+
"price_range": p.get("price_range", ""),
|
| 4105 |
+
"description": p.get("description", ""),
|
| 4106 |
+
})
|
| 4107 |
+
return safe
|
| 4108 |
+
|
| 4109 |
+
def gemini_rewrite_reply(user_text: str, result: dict) -> str | None:
|
| 4110 |
+
"""
|
| 4111 |
+
Gemini يحسن صياغة reply فقط، بدون ما يغير place_cards/best_place/all_results.
|
| 4112 |
+
"""
|
| 4113 |
+
if not gemini_client or not isinstance(result, dict):
|
| 4114 |
+
return None
|
| 4115 |
+
intent = result.get("intent", "")
|
| 4116 |
+
if intent in ("out_of_scope",):
|
| 4117 |
+
return None
|
| 4118 |
+
|
| 4119 |
+
real_places = _shorten_places_for_gemini(result.get("all_results") or ([result.get("best_place")] if result.get("best_place") else []))
|
| 4120 |
+
current_reply = str(result.get("reply", "")).strip()
|
| 4121 |
+
|
| 4122 |
+
prompt = f"""
|
| 4123 |
+
You are the response writer for a Beni Suef places chatbot.
|
| 4124 |
+
Write ONE short, natural Egyptian Arabic reply.
|
| 4125 |
+
|
| 4126 |
+
Critical rules:
|
| 4127 |
+
- Use ONLY the real_places data below.
|
| 4128 |
+
- Never invent places, phones, addresses, menu items, ratings, opening hours, or distances.
|
| 4129 |
+
- Do not mention a phone unless the user asked for phone/number.
|
| 4130 |
+
- If real_places is empty, politely say no suitable result is available now.
|
| 4131 |
+
- If intent is search_by_item, never suggest cafes unless real_places contains cafes only because the data says so.
|
| 4132 |
+
- Keep it friendly, not robotic, and concise.
|
| 4133 |
+
- Return plain text only.
|
| 4134 |
+
|
| 4135 |
+
User text: {user_text}
|
| 4136 |
+
Intent: {intent}
|
| 4137 |
+
Entities: {json.dumps(result.get('entities', {}), ensure_ascii=False)}
|
| 4138 |
+
Current reply: {current_reply}
|
| 4139 |
+
real_places: {json.dumps(real_places, ensure_ascii=False, default=str)}
|
| 4140 |
+
""".strip()
|
| 4141 |
+
try:
|
| 4142 |
+
response = gemini_client.models.generate_content(model=GEMINI_MODEL, contents=prompt)
|
| 4143 |
+
reply = str(getattr(response, "text", "")).strip()
|
| 4144 |
+
reply = reply.replace("```", "").strip()
|
| 4145 |
+
if not reply or len(reply) > 700:
|
| 4146 |
+
return None
|
| 4147 |
+
return reply
|
| 4148 |
+
except Exception as e:
|
| 4149 |
+
log.warning(f"Gemini reply rewrite skipped: {e}")
|
| 4150 |
+
return None
|
| 4151 |
+
|
| 4152 |
+
# حفظ النسخ القديمة، ثم override لـ predict/extract بحيث Gemini يساعد والكود القديم يفضل fallback.
|
| 4153 |
+
_base_predict_intent_before_gemini = predict_intent
|
| 4154 |
+
_base_extract_entities_before_gemini = extract_entities
|
| 4155 |
+
|
| 4156 |
+
def predict_intent(text: str, threshold=0.45) -> dict: # noqa: F811
|
| 4157 |
+
g = gemini_nlu(text)
|
| 4158 |
+
if g and g.get("intent") and g.get("confidence", 0) >= 0.60:
|
| 4159 |
+
return {"intent": g.get("intent", "fallback"), "confidence": round(float(g.get("confidence", 0.85)), 4)}
|
| 4160 |
+
return _base_predict_intent_before_gemini(text, threshold=threshold)
|
| 4161 |
+
|
| 4162 |
+
def extract_entities(text, min_score=0.40): # noqa: F811
|
| 4163 |
+
base = {}
|
| 4164 |
+
try:
|
| 4165 |
+
base = _base_extract_entities_before_gemini(text, min_score=min_score)
|
| 4166 |
+
except Exception:
|
| 4167 |
+
base = {}
|
| 4168 |
+
g = gemini_nlu(text)
|
| 4169 |
+
if g and isinstance(g.get("entities"), dict):
|
| 4170 |
+
merged = dict(base)
|
| 4171 |
+
# Gemini يكمل الناقص ويصحح category/item_query/place_name لما واضحين
|
| 4172 |
+
for k, v in g["entities"].items():
|
| 4173 |
+
if v and str(v).strip():
|
| 4174 |
+
merged[k] = v
|
| 4175 |
+
return merged
|
| 4176 |
+
return base
|
| 4177 |
+
|
| 4178 |
_old_chat_before_open_hotfix = chat
|
| 4179 |
|
| 4180 |
def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
|
|
|
|
| 4182 |
Final wrapper:
|
| 4183 |
- "ايه اللي فاتح؟" filters last_results, not only last_place.
|
| 4184 |
- open status/card dots use robust opening_hours parser.
|
| 4185 |
+
- Gemini adds safer NLU + nicer reply, while real data still comes from AroundU/search/ranking.
|
| 4186 |
"""
|
| 4187 |
+
# Refresh Gemini cache with session context for follow-up questions like "رقمه".
|
| 4188 |
+
if text and gemini_client:
|
| 4189 |
+
try:
|
| 4190 |
+
_GEMINI_NLU_CACHE[clean_text(text)] = gemini_nlu(text, session=session) or _GEMINI_NLU_CACHE.get(clean_text(text), {})
|
| 4191 |
+
except Exception:
|
| 4192 |
+
pass
|
| 4193 |
+
|
| 4194 |
if text and _final_is_open_followup(text) and getattr(session, "last_results", None):
|
| 4195 |
rows = []
|
| 4196 |
for p in list(session.last_results):
|
|
|
|
| 4238 |
if fixed_rows:
|
| 4239 |
res["all_results"] = fixed_rows
|
| 4240 |
res["best_place"] = fixed_rows[0]
|
| 4241 |
+
|
| 4242 |
+
# Gemini يحسن الرد فقط، من غير ما يلمس النتائج أو الكروت.
|
| 4243 |
+
better_reply = gemini_rewrite_reply(text, res)
|
| 4244 |
+
if better_reply:
|
| 4245 |
+
res["reply"] = better_reply
|
| 4246 |
return res
|