File size: 32,761 Bytes
b4f8279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# -*- coding: utf-8 -*-
"""app.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1iPAjeI3M04kA13lYenlROS96tUeCYakB
"""

import os, re, json, math, random, pickle, joblib
import numpy as np
import pandas as pd
import torch

from datetime import datetime
from zoneinfo import ZoneInfo
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional

from sentence_transformers import SentenceTransformer, util
from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    pipeline,
)
from huggingface_hub import snapshot_download

"""Paths"""

try:
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
except NameError:
    BASE_DIR = os.getcwd()

# HuggingFace Model Repos
INTENT_REPO   = "Youmnaaaa/intent-arabert-ff"
ENTITY_REPO   = "Youmnaaaa/entity-hybrid-ff"
SEMANTIC_REPO = "Youmnaaaa/semantic-search-ff"

# ู…ู„ู ุงู„ุฃู…ุงูƒู† ุฌูˆุง ุงู„ู€ Space
PLACES_FILE  = os.path.join(BASE_DIR, "beni_suef_100_places_v5ff.xlsx")

intent_tokenizer = intent_model = label_encoder = id2intent = None
ner_pipeline = label2id = id2label = None
semantic_model = corpus_df = corpus_embeddings = places_df = None
SESSIONS: dict = {}

def clean_text(text):
    text = str(text).strip().lower()
    text = re.sub(r"ู€+", "", text)
    for old, new in [("[ุฅุฃุขุง]","ุง"),("ู‰","ูŠ"),("ุฉ","ู‡"),("ุค","ูˆ"),("ุฆ","ูŠ")]:
        text = re.sub(old, new, text)
    text = re.sub(r"[^\w\s]", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def norm(text):
    text = str(text).strip().lower()
    text = re.sub(r"ู€+", "", text)
    for old, new in [("[ุฅุฃุขุง]","ุง"),("ู‰","ูŠ"),("ุฉ","ู‡"),("ุค","ูˆ"),("ุฆ","ูŠ")]:
        text = re.sub(old, new, text)
    for old, new in [("ุตุจุงุญู‹ุง","ุต"),("ุตุจุงุญุง","ุต"),("ู…ุณุงุกู‹","ู…"),("ู…ุณุงุกุง","ู…"),
                     ("ู„ูŠู„ู‹ุง","ู…"),("ู„ูŠู„ุง","ู…"),("ุฅู„ู‰","-"),("ุงู„ู‰","-"),("ุญุชู‰","-"),
                     ("โ€“","-"),("โ€”","-")]:
        text = text.replace(old, new)
    return re.sub(r"\s+", " ", text).strip()

#  INTENT MAPS
SEARCH_INTENTS = {"nearest_restaurant","nearest_pharmacy","nearest_cafe",
                  "nearest_supermarket","housing_search","recommend_place",
                  "open_now","place_details"}
STATIC_INTENTS = {"greeting","thanks","goodbye","confirm","deny"}

INTENT_TO_CATEGORY = {
    "nearest_restaurant":"restaurant","nearest_pharmacy":"pharmacy",
    "nearest_cafe":"cafe","nearest_supermarket":"supermarket",
    "housing_search":"housing",
}
INTENT_TEMPLATE_MAP = {
    "nearest_restaurant":"find_restaurant","nearest_pharmacy":"find_pharmacy",
    "nearest_cafe":"find_cafe","nearest_supermarket":"find_supermarket",
    "housing_search":"find_housing","recommend_place":"find_restaurant",
    "open_now":"find_restaurant","place_details":"find_restaurant",
    "greeting":"greeting","thanks":"thanks","goodbye":"goodbye",
    "confirm":"clarification","deny":"clarification","fallback":"fallback",
}
ENTITY_FIELD_MAP = {
    "location":"location","place_type":"category","cuisine_or_item":"sub_category",
    "food_type":"sub_category","price":"price","price_range":"price",
    "category":"category","sub_category":"sub_category","facility_type":"category",
    "housing_type":"category","status":"status","time":"time",
}
KEYWORD_OVERRIDE = {
    "goodbye": ["ู…ุน ุงู„ุณู„ุงู…ุฉ","ู…ุน ุงู„ุณู„ุงู…ู‡","ุจุงูŠ","ูˆุฏุงุนุง","bye","goodbye","ุชุตุจุญ ุนู„ู‰ ุฎูŠุฑ",
                "ููŠ ุงู…ุงู† ุงู„ู„ู‡","ุงู„ู„ู‡ ูŠุณู„ู…ูƒ","ุณู„ุงู…ุชูƒ"],
    "greeting":["ุงู„ุณู„ุงู… ุนู„ูŠูƒู…","ูˆุนู„ูŠูƒู… ุงู„ุณู„ุงู…","ุงู‡ู„ุง","ุฃู‡ู„ุง","ู‡ู„ุง","ู‡ู„ูˆ","ู…ุฑุญุจุง","ู…ุฑุญุจุงู‹",
                "ุตุจุงุญ ุงู„ุฎูŠุฑ","ู…ุณุงุก ุงู„ุฎูŠุฑ","ู‡ุงูŠ","hi","hello","ุตุจุงุญ","ู…ุณุงุก"],
    "thanks":  ["ุดูƒุฑุง","ุดูƒุฑุงู‹","ุชุณู„ู…","ูŠุณู„ู…ูˆ","ู…ู…ู†ูˆู†","ู…ุดูƒูˆุฑ","thanks","thank","ุงู„ู ุดูƒุฑ"],
}
CATEGORY_KEYWORDS = {
    "restaurant":["ู…ุทุนู…","ุงูƒู„","ูˆุฌุจุงุช","ู…ุดูˆูŠุงุช","ูƒุจุงุจ","ุดุงูˆุฑู…ุง","ูƒุฑูŠุจ","ุจุฑุฌุฑ","ุณู…ูƒ","ูุฑุงูŠุฏ"],
    "pharmacy":  ["ุตูŠุฏู„ูŠู‡","ุตูŠุฏู„ูŠุฉ","ุฏูˆุง","ุงุฏูˆูŠู‡","ุฏูˆุงุก"],
    "cafe":      ["ูƒุงููŠู‡","ูƒูˆููŠ","ู‚ู‡ูˆู‡","ู‚ู‡ูˆุฉ","ูƒุงููŠุชูŠุฑูŠุง"],
    "supermarket":["ุณูˆุจุฑู…ุงุฑูƒุช","ู…ุงุฑูƒุช","ุจู‚ุงู„ู‡","ู‡ุงูŠุจุฑ"],
    "housing":   ["ุดู‚ู‡","ุดู‚ุฉ","ุงูŠุฌุงุฑ","ุฅูŠุฌุงุฑ","ูู†ุฏู‚","ู‡ูˆุณุชู„","ุณูƒู†"],
}

_CAT_MAP = {
    "ู…ุทุนู…":"restaurant","ู…ุทุงุนู…":"restaurant","ุทุนุงู…":"restaurant","ุงูƒู„":"restaurant",
    "ุตูŠุฏู„ูŠู‡":"pharmacy","ุตูŠุฏู„ูŠุฉ":"pharmacy","ุตูŠุฏู„ู‡":"pharmacy","ุฏูˆุงุก":"pharmacy","ุฏูˆุง":"pharmacy",
    "ูƒุงููŠู‡":"cafe","ูƒุงููŠุฉ":"cafe","ูƒูˆููŠ":"cafe","ู‚ู‡ูˆู‡":"cafe","ู‚ู‡ูˆุฉ":"cafe","ูƒุงููŠุชูŠุฑูŠุง":"cafe",
    "ุณูˆุจุฑู…ุงุฑูƒุช":"supermarket","ู…ุงุฑูƒุช":"supermarket","ุจู‚ุงู„ู‡":"supermarket","ุจู‚ุงู„ุฉ":"supermarket","ู‡ุงูŠุจุฑ":"supermarket",
    "ุดู‚ู‡":"housing","ุดู‚ุฉ":"housing","ุงูŠุฌุงุฑ":"housing","ุฅูŠุฌุงุฑ":"housing",
    "ูู†ุฏู‚":"housing","ุณูƒู†":"housing","ู‡ูˆุณุชู„":"housing",
}

def normalize_category(cat):
    if not cat: return cat
    cat_s = str(cat).strip()
    if cat_s in ("restaurant","pharmacy","cafe","supermarket","housing"):
        return cat_s
    if cat_s in _CAT_MAP:
        return _CAT_MAP[cat_s]
    for ar, en in _CAT_MAP.items():
        if ar in cat_s or cat_s in ar:
            return en
    return cat_s
CLARIFICATION_Q = {
    "nearest_restaurant":"ุฃูŠ ู†ูˆุน ุฃูƒู„ุŸ ู…ุดูˆูŠุงุชุŒ ุดุงูˆุฑู…ุงุŒ ูƒุฑูŠุจุŒ ุจุฑุฌุฑุŸ",
    "nearest_pharmacy":"ููŠ ุฃูŠ ู…ู†ุทู‚ุฉ ุจุชุฏูˆุฑ ุนู„ู‰ ุตูŠุฏู„ูŠุฉุŸ",
    "nearest_cafe":"ููŠ ุฃูŠ ู…ู†ุทู‚ุฉ ุจุชุฏูˆุฑ ุนู„ู‰ ูƒุงููŠู‡ุŸ",
    "nearest_supermarket":"ููŠ ุฃูŠ ู…ู†ุทู‚ุฉ ุจุชุฏูˆุฑ ุนู„ู‰ ู…ุงุฑูƒุชุŸ",
    "housing_search":"ุจุชุฏูˆุฑ ุนู„ู‰ ุฅูŠู‡ โ€” ุดู‚ุฉ ุฅูŠุฌุงุฑุŒ ูู†ุฏู‚ุŸ ูˆููŠู†ุŸ",
}
OUT_OF_SCOPE_KW = ["ุงู„ุฌูˆ","ุทู‚ุณ","ุฏุฑุฌู‡","ูƒูˆุฑู‡","ูƒุฑุฉ","ุฃู‡ู„ูŠ","ุฒู…ุงู„ูƒ","ู…ุจุงุฑูŠุงุช",
                    "ุณูŠุงุณู‡","ุณูŠุงุณุฉ","ุฃุฎุจุงุฑ","ุฑุตูŠุฏ","ุจู†ูƒ","ุชุญูˆูŠู„","ุงู…ุชุญุงู†","ู…ุฏุฑุณู‡",
                    "ุฌุงู…ุนู‡","ูˆุธูŠูู‡","ุจุฑู…ุฌู‡","ูƒูˆุฏ","python","java","ุฑูŠุงุถูŠุงุช","ุชุฑุฌู…ู‡","translate"]
NEXT_WORDS   = ["ุชุงู†ูŠ","ุบูŠุฑู‡","ุบูŠุฑู‡ุง","ุจุฏูŠู„","ุญุงุฌุฉ ุชุงู†ูŠุฉ","ู…ุด ุนุงุฌุจู†ูŠ","ููŠู‡ ุชุงู†ูŠ","ุนุงูŠุฒ ุบูŠุฑู‡"]
DETAIL_WORDS = ["ุจูŠูุชุญ","ุจุชูุชุญ","ู…ูˆุงุนูŠุฏู‡","ู…ูˆุงุนูŠุฏู‡ุง","ุงู…ุชู‰","ุงู…ุชูŠ","ุนู†ูˆุงู†ู‡","ุนู†ูˆุงู†ู‡ุง",
                "ุชู„ูŠููˆู†ู‡","ุชู„ูŠููˆู†ู‡ุง","ุฑู‚ู…ู‡","ุฑู‚ู…ู‡ุง","ุชู‚ูŠูŠู…ู‡","ุชู‚ูŠูŠู…ู‡ุง","ุณุนุฑู‡","ุณุนุฑู‡ุง"]
REF_WORDS    = ["ู‡ูˆ","ู‡ูŠ","ุฏู‡","ุฏูŠ","ุงู„ู…ูƒุงู† ุฏู‡"]
_LOC_CUES    = ["ุงู„ุญูŠ","ุจู†ูŠ ุณูˆูŠู","ุงู„ุงุจุงุตูŠุฑูŠ","ุงู„ูƒูˆุฑู†ูŠุด","ู…ู‚ุจู„","ุงู„ุฒุฑุงุนูŠูŠู†",
                "ุตู„ุงุญ ุณุงู„ู…","ุดุฑู‚ ุงู„ู†ูŠู„","ุณูŠุชูŠ ุณู†ุชุฑ","ุนุฑุงุจูŠ","ุงู„ุฑูˆุถู‡"]

#  HELPER FUNCTIONS
def apply_keyword_override(text):
    t = norm(text); tw = set(t.split())
    for intent, kws in KEYWORD_OVERRIDE.items():
        for k in sorted(kws, key=len, reverse=True):
            kn = norm(k)
            if (" " in kn and kn in t) or (kn in tw): return intent
    return None

def get_template_key(intent, category=None):
    if category:
        k = {"restaurant":"find_restaurant","pharmacy":"find_pharmacy",
             "cafe":"find_cafe","supermarket":"find_supermarket",
             "housing":"find_housing"}.get(category)
        if k: return k
    return INTENT_TEMPLATE_MAP.get(intent, "fallback")

def infer_category(query):
    q = norm(query)
    for cat, words in CATEGORY_KEYWORDS.items():
        if any(norm(w) in q for w in words): return cat
    return None

def is_out_of_scope(text):
    t = norm(text)
    return any(norm(k) in t for k in OUT_OF_SCOPE_KW)

def detect_ref_type(text):
    t = norm(text); tw = set(t.split())
    if any(norm(w) in t for w in NEXT_WORDS):   return "next"
    if any(norm(w) in t for w in DETAIL_WORDS): return "detail"
    for w in REF_WORDS:
        wn = norm(w)
        if (" " in wn and wn in t) or (wn in tw): return "reference"
    return "new"

def _loc_continuation(text):
    t = norm(text); words = t.split()
    if len(words) <= 4 and any(norm(c) in t for c in _LOC_CUES): return True
    return bool(words and words[0] == "ููŠ")

def normalize_rating(r):
    try:
        r = float(r)
        return round(r/2, 1) if r > 5 else round(r, 1) if r > 0 else 0.0
    except: return 0.0

#  TIME UTILS

def get_cairo_now():
    return datetime.now(ZoneInfo("Africa/Cairo"))

def parse_time(token):
    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):
    if not opening_hours_str or str(opening_hours_str).strip() in ("","nan","none"): return None
    text = norm(str(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

#  SEARCH + FILTER + RANK
def semantic_candidates(query, top_k=20):
    q_emb  = semantic_model.encode(clean_text(query), convert_to_tensor=True)
    scores = util.cos_sim(q_emb, corpus_embeddings)[0]
    top_k  = min(top_k, len(corpus_df))
    top_r  = torch.topk(scores, k=top_k)
    res    = corpus_df.iloc[top_r.indices.cpu().numpy()].copy()
    res["semantic_score"] = top_r.values.cpu().numpy()
    keep = [c for c in ["place_id","doc_id","name","category","sub_category","location",
                         "address","price_range","opening_hours","description","semantic_score"]
            if c in res.columns]
    return res[keep].reset_index(drop=True)

def merge_places(df):
    extra = [c for c in ["lat","lon","rating","phone","social_media","status",
                          "category_clean","sub_category_clean","location_clean",
                          "address_clean","price_range_clean","search_text_clean"]
             if c in places_df.columns]
    slim = places_df[["place_id"] + extra].copy()
    return df.merge(slim, on="place_id", how="left")

def apply_filters(df, query, category=None, sub_category=None, location=None,
                   price_range=None, open_now_only=False, min_rating=None):
    f = df.copy()
    if category:     f = f[f["category_clean"].astype(str).str.contains(re.escape(clean_text(category)), na=False)]
    if sub_category: f = f[f["sub_category_clean"].astype(str).str.contains(re.escape(clean_text(sub_category)), na=False)]
    if location:     f = f[f["location_clean"].astype(str).str.contains(re.escape(clean_text(location)), na=False)]
    if price_range:  f = f[f["price_range_clean"].astype(str).str.contains(re.escape(clean_text(price_range)), na=False)]
    f["open_now"]     = f["opening_hours"].apply(check_open_now)
    f["rating_num"]   = pd.to_numeric(f.get("rating", pd.Series()), errors="coerce").fillna(0)
    f["rating_norm"]  = f["rating_num"].apply(normalize_rating)
    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.0))
    if open_now_only: f = f[f["open_now"] == 1]
    if min_rating:    f = f[f["rating_norm"] >= min_rating]
    return f

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 rank(df, query, user_lat=None, user_lon=None):
    df = df.copy()
    if user_lat and user_lon and "lat" in df.columns:
        def dist(row):
            try: return haversine(float(user_lat), float(user_lon), float(row["lat"]), float(row["lon"]))
            except: return 999
        df["distance_km"]    = df.apply(dist, axis=1)
        mx                   = df["distance_km"].replace(999, np.nan).max() or 1
        df["distance_score"] = 1 - (df["distance_km"] / (mx + 1))
    else:
        df["distance_km"] = 999; df["distance_score"] = 0.0
    q_clean = clean_text(query)
    df["name_match_score"] = df["name"].apply(
        lambda n: 1.0 if clean_text(str(n)) in q_clean or q_clean in clean_text(str(n)) else 0.0)
    w = dict(semantic=0.40, rating=0.25, open=0.15, distance=0.10, name=0.10)
    df["final_score"] = (
        w["semantic"]*df.get("semantic_score", pd.Series(0,index=df.index)).fillna(0) +
        w["rating"]  *df.get("rating_score",   pd.Series(0,index=df.index)).fillna(0) +
        w["open"]    *df.get("open_score",      pd.Series(0,index=df.index)).fillna(0) +
        w["distance"]*df["distance_score"] + w["name"]*df["name_match_score"]
    )
    return df.sort_values("final_score", ascending=False).reset_index(drop=True)

def search_places(query, top_k_final=5, category=None, sub_category=None,
                   location=None, price_range=None, open_now_only=False,
                   min_rating=None, user_lat=None, user_lon=None):
    cands  = semantic_candidates(query, top_k=20)
    merged = merge_places(cands)
    for attempt in [
        dict(category=category, sub_category=sub_category, location=location,
             price_range=price_range, open_now_only=open_now_only, min_rating=min_rating),
        dict(category=category, sub_category=None, location=location,
             price_range=price_range, open_now_only=open_now_only, min_rating=min_rating),
        dict(category=category, sub_category=None, location=location,
             price_range=None, open_now_only=False, min_rating=min_rating),
        dict(category=category, sub_category=None, location=None,
             price_range=None, open_now_only=False, min_rating=None),
    ]:
        filtered = apply_filters(merged, query, **attempt)
        if not filtered.empty: break
    if filtered.empty: return pd.DataFrame()
    ranked = rank(filtered, query, user_lat, user_lon)
    keep = [c for c in ["place_id","name","category","sub_category","location","address",
                         "price_range","rating","rating_norm","opening_hours","description",
                         "phone","lat","lon","semantic_score","final_score","open_now"]
            if c in ranked.columns]
    return ranked[keep].head(top_k_final).reset_index(drop=True)

#  RESPONSE TEMPLATES + FORMATTERS
RESPONSE_TEMPLATES = {
    "find_restaurant":[
        "๐Ÿฝ๏ธ ู„ู‚ูŠุชู„ูƒ {name} ููŠ {location}. {price_info}{rating_info}{hours_info}",
        "ุฃู†ุตุญูƒ ุจู€ {name} โ€” ู‡ุชู„ุงู‚ูŠู‡ ููŠ {location}. {price_info}{rating_info}{hours_info}",
        "ููŠ {location} ููŠู‡ {name}. {description_short}{price_info}{hours_info}",
    ],
    "find_pharmacy":[
        "๐Ÿ’Š {name} ููŠ {location}.{hours_info}{rating_info}",
        "ุฃู‚ุฑุจ ุตูŠุฏู„ูŠุฉ ู„ูŠูƒ: {name} โ€” {address_info}{hours_info}",
    ],
    "find_cafe":[
        "โ˜• {name} ููŠ {location}. {price_info}{rating_info}{hours_info}",
        "ุฌุฑุจ {name} โ€” ููŠ {location}. {description_short}{hours_info}",
    ],
    "find_supermarket":[
        "๐Ÿ›’ {name} ููŠ {location}.{hours_info}{rating_info}",
        "ุฃู‚ุฑุจ ู…ุงุฑูƒุช: {name} โ€” {address_info}{hours_info}",
    ],
    "find_housing":[
        "๐Ÿ  {name} ููŠ {location}. {price_info}{description_short}",
        "ููŠู‡ {name} ููŠ {location}. {price_info}{rating_info}",
    ],
    "greeting":     ["ุฃู‡ู„ุงู‹! ๐Ÿ˜Š ุฃู†ุง ุจุณุงุนุฏูƒ ุชู„ุงู‚ูŠ ุฃูŠ ู…ูƒุงู† ููŠ ุจู†ูŠ ุณูˆูŠู. ุนุงูŠุฒ ุฅูŠู‡ุŸ",
                     "ูˆุนู„ูŠูƒู… ุงู„ุณู„ุงู…! ู‚ูˆู„ูŠ ู…ุญุชุงุฌ ุฅูŠู‡ โ€” ู…ุทุนู…ุŒ ุตูŠุฏู„ูŠุฉุŒ ูƒุงููŠู‡ุŸ",
                     "ู‡ู„ุง ุจูŠูƒ! ู…ุญุชุงุฌ ุฅูŠู‡ ููŠ ุจู†ูŠ ุณูˆูŠูุŸ ๐Ÿ˜Š"],
    "thanks":       ["ุงู„ุนููˆ! ๐Ÿ˜Š ููŠ ุญุงุฌุฉ ุชุงู†ูŠุฉ ุฃุณุงุนุฏูƒ ููŠู‡ุงุŸ","ุฃูŠ ุฎุฏู…ุฉ! ๐Ÿ˜Š","ุจูƒู„ ุณุฑูˆุฑ! ๐Ÿ˜Š"],
    "goodbye":      ["ู…ุน ุงู„ุณู„ุงู…ุฉ! ๐Ÿ‘‹","ุณู„ุงู…ุชูƒ! ุฃูŠ ูˆู‚ุช ู…ุญุชุงุฌ ู…ุณุงุนุฏุฉ ุฃู†ุง ู‡ู†ุง.","ุจุงูŠ! ุฑุจู†ุง ูŠูˆูู‚ูƒ ๐Ÿ˜Š"],
    "clarification":["๐Ÿ˜Š ู‚ุตุฏูƒ ุฅูŠู‡ ุจุงู„ุธุจุทุŸ","ู…ู…ูƒู† ุชูˆุถุญ ุฃูƒุชุฑุŸ","ุชู…ุงู…! ุจุชุฏูˆุฑ ุนู„ู‰ ุฅูŠู‡ ุจุงู„ุธุจุทุŸ"],
    "no_result":    ["๐Ÿ˜” ู…ุด ู„ุงู‚ูŠ ุญุงุฌุฉ ู…ู†ุงุณุจุฉ. ุฌุฑุจ ุชุบูŠุฑ ุงู„ู…ู†ุทู‚ุฉ ุฃูˆ ุชุณุฃู„ ุจุทุฑูŠู‚ุฉ ุชุงู†ูŠุฉ.",
                     "ู…ุนู„ุดุŒ ู…ููŠุด ู†ุชุงูŠุฌ. ู…ู…ูƒู† ุชุญุฏุฏ ุงู„ู…ู†ุทู‚ุฉ ุฃูˆ ุงู„ู†ูˆุน ุฃูƒุชุฑุŸ"],
    "fallback":     ["ุขุณูุŒ ู…ุด ูุงู‡ู… ู‚ุตุฏูƒ. ๐Ÿ˜Š ู‚ูˆู„ูŠ ู…ุญุชุงุฌ ุฅูŠู‡ โ€” ู…ุทุนู…ุŒ ุตูŠุฏู„ูŠุฉุŒ ูƒุงููŠู‡ุŸ",
                     "ู…ู…ูƒู† ุชุณุฃู„ู†ูŠ ุนู† ุฃูŠ ู…ูƒุงู† ููŠ ุจู†ูŠ ุณูˆูŠู ูˆุฃู†ุง ู‡ุณุงุนุฏูƒ! ๐Ÿ˜Š"],
}

def fmt_price(x):
    p = str(x).strip().lower()
    if not p or p in ("","nan","none"): return ""
    m = {"cheap":"ุงู„ุฃุณุนุงุฑ ุฑุฎูŠุตุฉ","ุฑุฎูŠุต":"ุงู„ุฃุณุนุงุฑ ุฑุฎูŠุตุฉ","ุงู‚ุชุตุงุฏูŠ":"ุงู„ุฃุณุนุงุฑ ุงู‚ุชุตุงุฏูŠุฉ",
         "medium":"ุงู„ุฃุณุนุงุฑ ู…ุชูˆุณุทุฉ","ู…ุชูˆุณุท":"ุงู„ุฃุณุนุงุฑ ู…ุชูˆุณุทุฉ",
         "expensive":"ุงู„ุฃุณุนุงุฑ ุบุงู„ูŠุฉ","ุบุงู„ูŠ":"ุงู„ุฃุณุนุงุฑ ุบุงู„ูŠุฉ"}
    for k,v in m.items():
        if k in p: return v+". "
    return f"ุงู„ุณุนุฑ: {x}. "

def fmt_rating(x):
    try:
        r = normalize_rating(float(x)); stars = min(round(r), 5)
        return f"ุชู‚ูŠูŠู…ู‡ {r} {'โญ'*stars}. " if r > 0 else ""
    except: return ""

def fmt_hours(x):
    h = str(x).strip()
    if not h or h in ("","nan","none"): return ""
    if any(k in h.lower() for k in ["24","always","ุทูˆู„ ุงู„ูŠูˆู…"]): return "ู…ูุชูˆุญ 24 ุณุงุนุฉ. "
    return f"ุจูŠูุชุญ: {h}. "

def fmt_addr(address, location):
    a=str(address).strip(); l=str(location).strip()
    if a and a not in ("","nan","none"): return f"ุนู†ูˆุงู†ู‡: {a}. "
    if l and l not in ("","nan","none"): return f"ููŠ {l}. "
    return ""

def fmt_desc(x, max_words=12):
    d = str(x).strip()
    if not d or d in ("","nan","none"): return ""
    words = d.split()
    return (" ".join(words[:max_words])+"...") if len(words)>max_words else d+" "

def build_response(place, intent, category=None):
    if not place: return random.choice(RESPONSE_TEMPLATES["no_result"])
    tk = get_template_key(intent, category)
    reply = random.choice(RESPONSE_TEMPLATES[tk]).format(
        name             = str(place.get("name","")).strip(),
        location         = str(place.get("location","")).strip() or "ุจู†ูŠ ุณูˆูŠู",
        price_info       = fmt_price(place.get("price_range","")),
        rating_info      = fmt_rating(place.get("rating_norm", place.get("rating", 0))),
        hours_info       = fmt_hours(place.get("opening_hours","")),
        address_info     = fmt_addr(place.get("address",""), place.get("location","")),
        description_short= fmt_desc(place.get("description","")),
    )
    on = place.get("open_now")
    if on == 1:   reply += "\n๐ŸŸข ู…ูุชูˆุญ ุฏู„ูˆู‚ุชูŠ."
    elif on == 0: reply += "\n๐Ÿ”ด ู…ุบู„ู‚ ุฏู„ูˆู‚ุชูŠ."
    return reply

def handle_detail(text, place):
    if not place: return "ู…ุด ูุงูƒุฑ ุฅุญู†ุง ุงุชูƒู„ู…ู†ุง ุนู† ู…ูƒุงู†. ู…ู…ูƒู† ุชุณุฃู„ู†ูŠ ู…ู† ุงู„ุฃูˆู„ุŸ"
    t = norm(text); name = str(place.get("name","")).strip()
    if any(w in t for w in ["ุงู…ุชูŠ","ุงู…ุชู‰","ู…ูˆุงุนูŠุฏ","ูŠูุชุญ","ุชูุชุญ","ูŠู‚ูู„"]):
        st = "๐ŸŸข ู…ูุชูˆุญ" if place.get("open_now")==1 else "๐Ÿ”ด ู…ุบู„ู‚"
        return f"โฐ {name} โ€” {fmt_hours(place.get('opening_hours',''))}\n{st} ุฏู„ูˆู‚ุชูŠ."
    if any(w in t for w in ["ุนู†ูˆุงู†","ููŠู†","ูˆุตูˆู„","ุงูˆุตู„"]):
        return f"๐Ÿ“ {name} ููŠ {place.get('location','')}.\\nุงู„ุนู†ูˆุงู†: {place.get('address','')}"
    if any(w in t for w in ["ุณุนุฑ","ุจูƒุงู…","ุชูƒู„ู","ุบุงู„ูŠ","ุฑุฎูŠุต"]):
        return f"๐Ÿ’ฐ {name} โ€” {fmt_price(place.get('price_range',''))}"
    if any(w in t for w in ["ุชู‚ูŠูŠู…","ู†ุฌูˆู…"]):
        return f"โญ {name} โ€” {fmt_rating(place.get('rating_norm', place.get('rating',0)))}"
    if any(w in t for w in ["ุฑู‚ู…","ุชู„ูŠููˆู†"]):
        phone = str(place.get("phone","")).strip()
        return f"๐Ÿ“ž {name} โ€” {phone}" if phone else f"ู…ุนู†ุฏูŠุด ุฑู‚ู… {name}."
    return f"๐Ÿ“‹ {name}:\n{fmt_desc(place.get('description',''), 20)}\n{fmt_hours(place.get('opening_hours',''))}{fmt_rating(place.get('rating_norm',0))}"

#  PREDICT FUNCTIONS

def predict_intent(text, threshold=0.5):
    override = apply_keyword_override(text)
    if override: return {"intent": override, "confidence": 1.0}
    inputs = intent_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=128)
    with torch.no_grad():
        outputs = intent_model(**inputs)
    probs = torch.softmax(outputs.logits, dim=1)
    pid   = torch.argmax(probs, dim=1).item()
    conf  = probs[0][pid].item()
    return {"intent": id2intent[pid] if conf >= threshold else "fallback", "confidence": round(conf, 4)}

def extract_entities(text, min_score=0.40):
    raw = ner_pipeline([text])[0]; entities = {}
    for item in raw:
        rtype = item["entity_group"].lower().strip()
        val   = re.sub(r"##", "", item["word"].strip()).strip()
        val   = re.sub(r"\s+", " ", val).strip()
        score = float(item["score"])
        if len(val) < 2 or score < min_score: continue
        mapped = ENTITY_FIELD_MAP.get(rtype, rtype)
        val_c  = clean_text(val)
        if mapped not in entities or len(val_c) > len(clean_text(entities[mapped])):
            entities[mapped] = val_c
    return entities

#  SESSION
class Session:
    def __init__(self, sid="default"):
        self.sid = sid; 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.history.append({"turn":self.turns,"user":user,"bot":bot,
                              "intent":intent,"entities":entities})
        if intent and intent not in ("fallback","no_result","out_of_scope"):
            self.last_intent = intent
            if intent in SEARCH_INTENTS:
                self.last_entities = entities
                if place is not None: self.last_place = place
                if results: self.last_results=results; self.result_pointer=0
                self._slots(entities)
        self.turns += 1

    def _slots(self, ents):
        for s in ["location","category","sub_category","price"]:
            v = ents.get(s)
            if v and str(v).strip(): self.context_slots[s] = str(v).strip()

    def merge(self, new_ents):
        merged = dict(self.context_slots)
        for k,v in new_ents.items():
            if v and str(v).strip(): merged[k]=str(v).strip()
        self._slots(new_ents)
        return merged

#  MAIN CHAT

def chat(text: str, session: Session, user_lat=None, user_lon=None):
    result = dict(reply="", intent="", confidence=0.0, entities={}, best_place=None, all_results=[])

    if not text or not text.strip():
        result.update(reply="ุงู„ุฑุฌุงุก ุฅุฏุฎุงู„ ุณุคุงู„ ๐Ÿ˜Š", intent="fallback")
        session.add("", result["reply"], "fallback", {}, None, [])
        return result

    if is_out_of_scope(text):
        reply = "ุฃู†ุง ู…ุชุฎุตุต ููŠ ุฅูŠุฌุงุฏ ุงู„ุฃู…ุงูƒู† ููŠ ุจู†ูŠ ุณูˆูŠู ูู‚ุท. ๐Ÿ˜Š\nู…ู…ูƒู† ุฃุณุงุนุฏูƒ ุชู„ุงู‚ูŠ ู…ุทุนู…ุŒ ุตูŠุฏู„ูŠุฉุŒ ูƒุงููŠู‡ุŒ ู…ุงุฑูƒุชุŒ ุฃูˆ ุณูƒู†."
        result.update(reply=reply, intent="out_of_scope")
        session.add(text, reply, "out_of_scope", {}, None, [])
        return result

    ref = detect_ref_type(text)
    if ref == "detail" and session.last_place:
        reply = handle_detail(text, session.last_place)
        result.update(reply=reply, intent=session.last_intent or "detail", best_place=session.last_place)
        session.add(text, reply, result["intent"], {}, session.last_place, [])
        return result

    if ref == "next" and session.last_results:
        ptr = session.result_pointer + 1
        if ptr < len(session.last_results):
            session.result_pointer = ptr; nxt = session.last_results[ptr]; session.last_place = nxt
            reply = build_response(nxt, session.last_intent, category=nxt.get("category"))
            result.update(reply=reply, intent=session.last_intent, best_place=nxt)
        else:
            result.update(reply="๐Ÿ˜” ู…ููŠุด ู†ุชุงูŠุฌ ุชุงู†ูŠุฉ. ุนุงูŠุฒ ุฃุฏูˆุฑ ู…ู† ุงู„ุฃูˆู„ุŸ", intent="no_result")
        session.add(text, result["reply"], result["intent"], {}, result["best_place"], [])
        return result

    ir = predict_intent(text); intent = ir["intent"]; conf = ir["confidence"]
    result["intent"] = intent; result["confidence"] = conf

    if intent in STATIC_INTENTS:
        result["reply"] = random.choice(RESPONSE_TEMPLATES[get_template_key(intent)])
        session.add(text, result["reply"], intent, {}, None, [])
        return result

    if intent == "fallback":
        if session.last_intent in SEARCH_INTENTS and _loc_continuation(text):
            intent = session.last_intent; result["intent"] = intent
        else:
            result["reply"] = random.choice(RESPONSE_TEMPLATES["fallback"])
            session.add(text, result["reply"], "fallback", {}, None, [])
            return result

    if intent not in SEARCH_INTENTS:
        result["reply"] = random.choice(RESPONSE_TEMPLATES.get(get_template_key(intent), RESPONSE_TEMPLATES["fallback"]))
        session.add(text, result["reply"], intent, {}, None, [])
        return result

    ents   = extract_entities(text); result["entities"] = ents
    merged = session.merge(ents)

    category    = normalize_category(merged.get("category") or INTENT_TO_CATEGORY.get(intent) or infer_category(text))
    sub_cat     = merged.get("sub_category")
    location    = merged.get("location")
    price_range = merged.get("price")
    open_only   = ("open_now" in intent or "place_details" in intent)

    df = search_places(text, top_k_final=5, category=category, sub_category=sub_cat,
                        location=location, price_range=price_range, open_now_only=open_only,
                        user_lat=user_lat, user_lon=user_lon)

    if df.empty:
        cl = CLARIFICATION_Q.get(intent, "")
        reply = random.choice(RESPONSE_TEMPLATES["no_result"]) + (f"\n\n๐Ÿ’ฌ {cl}" if cl else "")
        result.update(reply=reply, intent="no_result")
        session.add(text, reply, "no_result", ents, None, [])
        return result

    all_res = df.to_dict(orient="records"); best = all_res[0]
    reply   = build_response(best, intent, category=category)
    if len(all_res) > 1: reply += f"\n\n๐Ÿ’ฌ ููŠู‡ {len(all_res)} ู†ุชูŠุฌุฉ โ€” ู‚ูˆู„ูŠ 'ุชุงู†ูŠ' ู„ูˆ ุนุงูŠุฒ ุบูŠุฑู‡."

    result.update(reply=reply, best_place=best, all_results=all_res)
    session.add(text, reply, intent, ents, best, all_res)
    return result

@asynccontextmanager
async def lifespan(app: FastAPI):
    global intent_tokenizer, intent_model, label_encoder, id2intent
    global ner_pipeline, label2id, id2label
    global semantic_model, corpus_df, corpus_embeddings, places_df

    print("โณ Downloading models from HuggingFace โ€ฆ")

    # ุชุญู…ูŠู„ ุงู„ู…ูˆุฏูŠู„ุฒ ู…ู† HuggingFace Model Hub
    intent_local   = snapshot_download(INTENT_REPO)
    entity_local   = snapshot_download(ENTITY_REPO)
    semantic_local = snapshot_download(SEMANTIC_REPO)

    print("โณ Loading Intent model โ€ฆ")
    intent_tokenizer = AutoTokenizer.from_pretrained(intent_local)
    intent_model     = AutoModelForSequenceClassification.from_pretrained(intent_local)
    label_encoder    = joblib.load(os.path.join(intent_local, "label_encoder.pkl"))
    id2intent        = {i: lbl for i, lbl in enumerate(label_encoder.classes_)}
    intent_model.eval()

    print("โณ Loading Entity model โ€ฆ")
    with open(os.path.join(entity_local, "label2id.json"), encoding="utf-8") as f: label2id = json.load(f)
    with open(os.path.join(entity_local, "id2label.json"), encoding="utf-8") as f: id2label = json.load(f)
    etok = AutoTokenizer.from_pretrained(entity_local)
    emod = AutoModelForTokenClassification.from_pretrained(entity_local)
    ner_pipeline = pipeline("token-classification", model=emod, tokenizer=etok, aggregation_strategy="first")

    print("โณ Loading Semantic model โ€ฆ")
    semantic_model = SentenceTransformer("Youmnaaaa/semantic-search-ff")
    from huggingface_hub import hf_hub_download
    pkl_path = hf_hub_download(
        repo_id="Youmnaaaa/semantic-search-ff",
        filename="semantic_data.pkl"
    )
    with open(pkl_path, "rb") as f:
        sd = pickle.load(f)
    corpus_df = sd["corpus_df"]
    corpus_embeddings = sd["corpus_embeddings"]

    places_df = pd.read_excel(PLACES_FILE)
    for col in ["place_id","name","category","sub_category","location","address",
                "price_range","rating","opening_hours","description","lat","lon"]:
        if col not in places_df.columns: places_df[col] = ""
    places_df = places_df.fillna("")
    places_df["category_clean"]     = places_df["category"].apply(clean_text)
    places_df["sub_category_clean"] = places_df["sub_category"].apply(clean_text)
    places_df["location_clean"]     = places_df["location"].apply(clean_text)
    places_df["address_clean"]      = places_df["address"].apply(clean_text)
    places_df["price_range_clean"]  = places_df["price_range"].apply(clean_text)
    places_df["description_clean"]  = places_df["description"].apply(clean_text)
    places_df["search_text_clean"]  = (
        places_df["name"].astype(str)+" "+places_df["category"].astype(str)+" "+
        places_df["sub_category"].astype(str)+" "+places_df["location"].astype(str)+" "+
        places_df["description"].astype(str)
    ).apply(clean_text)

    print("โœ… All models loaded!")
    yield
    print("Shutting down.")

#  FASTAPI
app = FastAPI(title="Beni Suef Chatbot API", version="1.0.0", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])


class ChatRequest(BaseModel):
    message: str
    session_id: str = "default"
    user_lat: Optional[float] = None
    user_lon: Optional[float] = None

class ChatResponse(BaseModel):
    reply: str
    intent: str
    confidence: float
    entities: dict
    session_id: str
    best_place: Optional[dict] = None


@app.get("/")
def root():
    return {"status": "ok", "message": "Beni Suef Chatbot is running ๐Ÿš€"}

@app.get("/health")
def health():
    return {"status": "healthy",
            "models_loaded": all([intent_model, ner_pipeline, semantic_model, places_df is not None])}

@app.post("/chat", response_model=ChatResponse)
def chat_endpoint(req: ChatRequest):
    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.user_lat, req.user_lon)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

    best = result.get("best_place")
    if best:
        best = {k: (float(v) if isinstance(v, (np.floating, np.integer)) else
                    (None if (isinstance(v, float) and np.isnan(v)) else v))
                for k, v in best.items()
                if k in ["place_id","name","category","sub_category","location","address",
                          "price_range","rating","opening_hours","description","phone",
                          "lat","lon","open_now","final_score"]}

    return ChatResponse(reply=result["reply"], intent=result["intent"],
                        confidence=result["confidence"], entities=result["entities"],
                        session_id=req.session_id, best_place=best)

@app.delete("/session/{session_id}")
def reset_session(session_id: str):
    SESSIONS.pop(session_id, None)
    return {"status": "reset", "session_id": session_id}