Youmnaaaa commited on
Commit
3661337
ยท
verified ยท
1 Parent(s): 0f2c736

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -0
app.py CHANGED
@@ -3721,3 +3721,259 @@ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
3721
  result.update(reply=reply, intent=intent, confidence=1.0, entities={k:v for k,v in ents.items() if v}, best_place=best, all_results=rows)
3722
  session.add(text, reply, intent, result["entities"], best, rows)
3723
  return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3721
  result.update(reply=reply, intent=intent, confidence=1.0, entities={k:v for k,v in ents.items() if v}, best_place=best, all_results=rows)
3722
  session.add(text, reply, intent, result["entities"], best, rows)
3723
  return result
3724
+
3725
+
3726
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
3727
+ # FINAL HOTFIX PATCH โ€” open_now/cards/follow-up stability
3728
+ # This block intentionally overrides earlier functions because the file
3729
+ # contains multiple older patches. Keep this block at the very end.
3730
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
3731
+
3732
+ _DAY_ALIASES_FINAL = {
3733
+ 0: ["monday", "mon", "ุงู„ุงุซู†ูŠู†", "ุงู„ุฅุซู†ูŠู†"],
3734
+ 1: ["tuesday", "tue", "ุงู„ุซู„ุงุซุงุก"],
3735
+ 2: ["wednesday", "wed", "ุงู„ุงุฑุจุนุงุก", "ุงู„ุฃุฑุจุนุงุก"],
3736
+ 3: ["thursday", "thu", "ุงู„ุฎู…ูŠุณ"],
3737
+ 4: ["friday", "fri", "ุงู„ุฌู…ุนุฉ"],
3738
+ 5: ["saturday", "sat", "ุงู„ุณุจุช"],
3739
+ 6: ["sunday", "sun", "ุงู„ุงุญุฏ", "ุงู„ุฃุญุฏ"],
3740
+ }
3741
+
3742
+ def _final_to_minutes(hour: str, minute: str = "0", ampm: str | None = None):
3743
+ try:
3744
+ h = int(hour)
3745
+ m = int(minute or 0)
3746
+ if not (0 <= m <= 59):
3747
+ return None
3748
+ suf = (ampm or "").strip().lower()
3749
+ if suf in ("am", "a.m", "a.m.", "ุต"):
3750
+ if h == 12:
3751
+ h = 0
3752
+ elif suf in ("pm", "p.m", "p.m.", "ู…"):
3753
+ if h != 12:
3754
+ h += 12
3755
+ elif not (0 <= h <= 23):
3756
+ return None
3757
+ return h * 60 + m
3758
+ except Exception:
3759
+ return None
3760
+
3761
+ def _final_extract_ranges(hours_text: str):
3762
+ """
3763
+ Extract time ranges from Arabic/English opening_hours strings.
3764
+ Supports:
3765
+ - 9:00 AM - 10:00 PM
3766
+ - 9ุต-11ู…
3767
+ - Saturday: 12:00 AM - 12:00 AM | Sunday: ...
3768
+ """
3769
+ if not hours_text or str(hours_text).strip().lower() in ("", "nan", "none", "null"):
3770
+ return []
3771
+ raw = str(hours_text)
3772
+ txt = raw.replace("โ€“", "-").replace("โ€”", "-").replace("ุฅู„ู‰", "-").replace("ุงู„ู‰", "-").replace("ุญุชู‰", "-")
3773
+ # common 24h patterns
3774
+ if re.search(r"\b(24/7|24\s*ุณุงุนุฉ|ุทูˆู„\s*ุงู„ูŠูˆู…|always)\b", txt, flags=re.I):
3775
+ return [(0, 24 * 60)]
3776
+
3777
+ # Prefer today's segment if weekly schedule exists.
3778
+ today = get_cairo_now().weekday()
3779
+ lower = txt.lower()
3780
+ selected = None
3781
+ for alias in _DAY_ALIASES_FINAL.get(today, []):
3782
+ idx = lower.find(alias.lower())
3783
+ if idx >= 0:
3784
+ part = txt[idx:]
3785
+ # cut at next separator before another day
3786
+ cuts = []
3787
+ for aliases in _DAY_ALIASES_FINAL.values():
3788
+ for a in aliases:
3789
+ j = part.lower().find(a.lower(), max(1, len(alias)))
3790
+ if j > 0:
3791
+ cuts.append(j)
3792
+ pipe = part.find("|")
3793
+ if pipe > 0:
3794
+ cuts.append(pipe)
3795
+ selected = part[:min(cuts)] if cuts else part
3796
+ break
3797
+ if selected:
3798
+ txt = selected
3799
+
3800
+ ranges = []
3801
+ # English AM/PM ranges
3802
+ pattern_en = re.compile(
3803
+ r"(\d{1,2})(?::(\d{2}))?\s*(AM|PM|A\.M\.|P\.M\.)?\s*-\s*"
3804
+ r"(\d{1,2})(?::(\d{2}))?\s*(AM|PM|A\.M\.|P\.M\.)?",
3805
+ flags=re.I,
3806
+ )
3807
+ for m in pattern_en.finditer(txt):
3808
+ s = _final_to_minutes(m.group(1), m.group(2) or "0", m.group(3))
3809
+ e = _final_to_minutes(m.group(4), m.group(5) or "0", m.group(6))
3810
+ if s is not None and e is not None:
3811
+ # 12:00 AM - 12:00 AM usually means 24 hours in business schedules.
3812
+ if s == e:
3813
+ ranges.append((0, 24 * 60))
3814
+ else:
3815
+ ranges.append((s, e))
3816
+
3817
+ # Arabic ุต/ู… ranges
3818
+ pattern_ar = re.compile(
3819
+ r"(\d{1,2})(?::(\d{2}))?\s*(ุต|ู…)?\s*-\s*"
3820
+ r"(\d{1,2})(?::(\d{2}))?\s*(ุต|ู…)?"
3821
+ )
3822
+ for m in pattern_ar.finditer(txt):
3823
+ s = _final_to_minutes(m.group(1), m.group(2) or "0", m.group(3))
3824
+ e = _final_to_minutes(m.group(4), m.group(5) or "0", m.group(6))
3825
+ if s is not None and e is not None:
3826
+ if s == e:
3827
+ ranges.append((0, 24 * 60))
3828
+ else:
3829
+ ranges.append((s, e))
3830
+
3831
+ return ranges
3832
+
3833
+ def check_open_now(opening_hours_str): # noqa: F811
3834
+ """Robust open-now parser. Returns 1 open, 0 closed, None unknown."""
3835
+ ranges = _final_extract_ranges(opening_hours_str)
3836
+ if not ranges:
3837
+ return None
3838
+ now = get_cairo_now()
3839
+ now_min = now.hour * 60 + now.minute
3840
+ for start, end in ranges:
3841
+ if start == 0 and end == 24 * 60:
3842
+ return 1
3843
+ if start < end:
3844
+ if start <= now_min <= end:
3845
+ return 1
3846
+ else:
3847
+ # overnight range e.g. 10 PM - 2 AM
3848
+ if now_min >= start or now_min <= end:
3849
+ return 1
3850
+ return 0
3851
+
3852
+ def _final_open_bool(place: dict):
3853
+ raw = _first_value(place, "is_open", "open_now")
3854
+ if isinstance(raw, bool):
3855
+ return raw
3856
+ if raw in (1, "1", "true", "True", "open", "ู…ูุชูˆุญ"):
3857
+ return True
3858
+ if raw in (0, "0", "false", "False", "closed", "ู…ุบู„ู‚"):
3859
+ return False
3860
+ calc = check_open_now(_first_value(place, "opening_hours", "openning_hours", default=""))
3861
+ if calc == 1:
3862
+ return True
3863
+ if calc == 0:
3864
+ return False
3865
+ return None
3866
+
3867
+ def clean_place(place: dict) -> dict: # noqa: F811
3868
+ """Return Flutter card with reliable is_open computed from opening_hours too."""
3869
+ if not place:
3870
+ return {}
3871
+
3872
+ lat = _safe_float(_first_value(place, "lat", "latitude"))
3873
+ lon = _safe_float(_first_value(place, "lon", "lng", "longitude"))
3874
+ distance = _safe_float(_first_value(place, "distance_km"))
3875
+ rating = _safe_float(_first_value(place, "rating_norm", "rating", default=0.0)) or 0.0
3876
+ is_open = _final_open_bool(place)
3877
+
3878
+ image = _first_value(place, "image", "image_url", "main_image_url", "photo", "photo_url", default="")
3879
+ favorite_raw = _first_value(place, "is_favorited", "is_favorite", default=False)
3880
+ phone_val = _first_value(place, "phone", "mobile", "telephone", default="")
3881
+ if isinstance(phone_val, (list, tuple)):
3882
+ phone_val = ", ".join(str(x) for x in phone_val if x)
3883
+ elif isinstance(phone_val, str) and phone_val.startswith("[") and phone_val.endswith("]"):
3884
+ phone_val = phone_val.strip("[]").replace("'", "").replace('"', "").strip()
3885
+
3886
+ return {
3887
+ "id": str(_first_value(place, "id", "place_id", default="")),
3888
+ "place_id": str(_first_value(place, "place_id", "id", default="")),
3889
+ "name": _first_value(place, "name", "name_ar", "name_en", default=""),
3890
+ "category": str(_first_value(place, "category", default="")).lower().strip(),
3891
+ "sub_category": _first_value(place, "sub_category", "subcategory", default=""),
3892
+ "rating": rating,
3893
+ "rating_count": _safe_int(_first_value(place, "rating_count", "review_count", "reviews_count", default=0)),
3894
+ "address": _first_value(place, "address", "location", default=""),
3895
+ "description": _first_value(place, "description", default=""),
3896
+ "is_open": is_open,
3897
+ "open_now": 1 if is_open is True else (0 if is_open is False else None),
3898
+ "opening_hours": _first_value(place, "opening_hours", "openning_hours", default=""),
3899
+ "distance_km": distance,
3900
+ "image": image or "",
3901
+ "phone": phone_val,
3902
+ "lat": lat,
3903
+ "lon": lon,
3904
+ "is_favorited": bool(favorite_raw),
3905
+ "final_score": _safe_float(_first_value(place, "final_score")),
3906
+ }
3907
+
3908
+ def _format_open_status_v2(place: dict) -> str: # noqa: F811
3909
+ name = place.get("name", "ุงู„ู…ูƒุงู†")
3910
+ is_open = _final_open_bool(place)
3911
+ if is_open is True:
3912
+ return f"๐ŸŸข *{name}* ู…ูุชูˆุญ ุฏู„ูˆู‚ุชูŠ."
3913
+ if is_open is False:
3914
+ return f"๐Ÿ”ด *{name}* ู…ุบู„ู‚ ุฏู„ูˆู‚ุชูŠ."
3915
+ return f"ู…ูˆุงุนูŠุฏ *{name}* ุบูŠุฑ ูˆุงุถุญุฉ ุนู†ุฏู†ุง ุญุงู„ูŠู‹ุง."
3916
+
3917
+ def _final_is_open_followup(text: str) -> bool:
3918
+ t = norm(text)
3919
+ return (
3920
+ ("ุงูŠู‡" in t or "ุงูŠ" in t or "ู…ูŠู†" in t or "ุงู†ู‡ูŠ" in t or "ุงู„ู„ูŠ" in t)
3921
+ and _has_v2(text, ["ูุงุชุญ", "ูุงุชุญุฉ", "ูุงุชุญู‡", "ู…ูุชูˆุญ", "ู…ูุชูˆุญุฉ", "ู…ูุชูˆุญู‡", "ุดุบุงู„"])
3922
+ )
3923
+
3924
+ _old_chat_before_open_hotfix = chat
3925
+
3926
+ def chat(text: str, session, user_lat=None, user_lon=None): # noqa: F811
3927
+ """
3928
+ Final wrapper:
3929
+ - "ุงูŠู‡ ุงู„ู„ูŠ ูุงุชุญุŸ" filters last_results, not only last_place.
3930
+ - open status/card dots use robust opening_hours parser.
3931
+ """
3932
+ if text and _final_is_open_followup(text) and getattr(session, "last_results", None):
3933
+ rows = []
3934
+ for p in list(session.last_results):
3935
+ q = dict(p)
3936
+ q["open_now"] = check_open_now(q.get("opening_hours", ""))
3937
+ rows.append(q)
3938
+
3939
+ opened = [p for p in rows if p.get("open_now") == 1]
3940
+ if opened:
3941
+ opened = _rank_postprocess_v2(opened, text)
3942
+ names = "ุŒ ".join(f"*{p.get('name','')}*" for p in opened[:3])
3943
+ reply = f"๐ŸŸข ุงู„ู…ูุชูˆุญ ุฏู„ูˆู‚ุชูŠ ู…ู† ุขุฎุฑ ุงู„ู†ุชุงุฆุฌ: {names}"
3944
+ result = dict(
3945
+ reply=reply,
3946
+ intent="open_now",
3947
+ confidence=1.0,
3948
+ entities={"open_now": True},
3949
+ best_place=opened[0],
3950
+ all_results=opened[:5],
3951
+ )
3952
+ session.add(text, reply, "open_now", result["entities"], opened[0], opened[:5])
3953
+ return result
3954
+
3955
+ reply = "ู…ุด ู„ุงู‚ูŠ ุฃู…ุงูƒู† ู…ูุชูˆุญุฉ ุฏู„ูˆู‚ุชูŠ ู…ู† ุขุฎุฑ ุงู„ู†ุชุงุฆุฌ ๐Ÿ˜”"
3956
+ result = dict(
3957
+ reply=reply,
3958
+ intent="no_result",
3959
+ confidence=1.0,
3960
+ entities={"open_now": True},
3961
+ best_place=None,
3962
+ all_results=[],
3963
+ )
3964
+ session.add(text, reply, "no_result", result["entities"], None, [])
3965
+ return result
3966
+
3967
+ res = _old_chat_before_open_hotfix(text, session, user_lat, user_lon)
3968
+
3969
+ # Ensure returned results carry open_now for cards.
3970
+ fixed_rows = []
3971
+ for p in (res.get("all_results") or []):
3972
+ q = dict(p)
3973
+ if q.get("open_now") is None:
3974
+ q["open_now"] = check_open_now(q.get("opening_hours", ""))
3975
+ fixed_rows.append(q)
3976
+ if fixed_rows:
3977
+ res["all_results"] = fixed_rows
3978
+ res["best_place"] = fixed_rows[0]
3979
+ return res