mlbench123 commited on
Commit
aaa22f8
·
verified ·
1 Parent(s): fec0153

Upload rag_treatment_app.py

Browse files
Files changed (1) hide show
  1. rag_treatment_app.py +874 -0
rag_treatment_app.py ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """RAGTreatmentSearchApp.
3
+
4
+ Structured RAG AI Search over database.xlsx with strict filtering.
5
+
6
+ UPDATED:
7
+ - Adds mismatch detection for worst-case scenario:
8
+ If user-selected Region/Sub-Zone is inconsistent with the issue text,
9
+ return a warning message + recommended Region/Sub-Zone suggestions (exact DB names),
10
+ instead of producing irrelevant treatments.
11
+
12
+ This prevents cases like:
13
+ Hair -> Scalp + "dark circles under eyes"
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import pickle
21
+ import re
22
+ import time
23
+ from dataclasses import dataclass
24
+ from typing import Dict, List, Optional, Tuple
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+ import torch
29
+ from sentence_transformers import SentenceTransformer
30
+ from sklearn.metrics.pairwise import cosine_similarity
31
+
32
+ from llm_client import LocalLLMClient
33
+ from web_retriever import WebRetriever, WebDoc
34
+
35
+
36
+ # Keep everything CPU-only
37
+ if torch.backends.mps.is_available():
38
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
39
+ torch.set_default_device("cpu")
40
+
41
+
42
+ DEFAULT_EMBEDDING_MODEL = "sentence-transformers/static-similarity-mrl-multilingual-v1"
43
+
44
+
45
+ @dataclass
46
+ class RetrievedCandidate:
47
+ row_index: int
48
+ similarity: float
49
+ procedure: str
50
+ region: str
51
+ sub_zone: str
52
+ type: str
53
+ technique: str
54
+ concerns: str
55
+ verbatims: str
56
+
57
+
58
+ def _norm_text(x: str) -> str:
59
+ return " ".join(str(x or "").strip().lower().split())
60
+
61
+
62
+ def _subzone_mask(df: pd.DataFrame, sub_zone: str) -> pd.Series:
63
+ """Robust sub-zone matching.
64
+
65
+ 1) Try strict equality on normalized values.
66
+ 2) If strict match yields 0 rows, broaden to a fuzzy match:
67
+ - match if DB sub-zone contains the selected sub-zone (e.g., "under-eyes" contains "eyes"), OR
68
+ - match if selected sub-zone contains the DB sub-zone.
69
+
70
+ This specifically fixes cases like:
71
+ selected: "Eyes" -> DB rows: "Under-Eyes", "Tear Troughs", "Eyes / crow's feet"
72
+ """
73
+ sz = _norm_text(sub_zone)
74
+ if not sz:
75
+ return pd.Series([True] * len(df), index=df.index)
76
+
77
+ strict = df["_subzone_norm"].eq(sz)
78
+ if int(strict.sum()) > 0:
79
+ return strict
80
+
81
+ key_tokens = [t for t in re.split(r"[^a-z0-9]+", sz) if t]
82
+ if not key_tokens:
83
+ return strict
84
+
85
+ def _fuzzy(cell: str) -> bool:
86
+ c = _norm_text(cell)
87
+ if not c:
88
+ return False
89
+ if sz in c or c in sz:
90
+ return True
91
+ return any(tok in c for tok in key_tokens)
92
+
93
+ return df["_subzone_norm"].apply(_fuzzy)
94
+
95
+
96
+ def _norm_type_value(x: str) -> str:
97
+ """Normalize Excel 'Type' values to either 'surgical' or 'non-surgical'."""
98
+ t = _norm_text(x)
99
+ t = t.replace("_", "-").replace("–", "-").replace("—", "-")
100
+ if "non" in t and "surg" in t:
101
+ return "non-surgical"
102
+ if "surg" in t:
103
+ return "surgical"
104
+ return ""
105
+
106
+
107
+ def _norm_type_choice(choice: str) -> str:
108
+ """Normalize UI choice to 'surgical' / 'non-surgical' / 'both'."""
109
+ c = _norm_text(choice)
110
+ if not c:
111
+ return "both"
112
+ if "both" in c:
113
+ return "both"
114
+ if "non" in c and "surg" in c:
115
+ return "non-surgical"
116
+ if "surg" in c:
117
+ return "surgical"
118
+ return "both"
119
+
120
+
121
+ class RAGTreatmentSearchApp:
122
+ """Core engine: loads database.xlsx, creates/loads embeddings, and performs filtered retrieval + synthesis."""
123
+
124
+ def __init__(
125
+ self,
126
+ excel_path: str = "database.xlsx",
127
+ sheet_name: str = "All_Procedures",
128
+ embeddings_cache_path: str = "treatment_embeddings.pkl",
129
+ embedding_model_name: str = DEFAULT_EMBEDDING_MODEL,
130
+ llm: Optional[LocalLLMClient] = None,
131
+ web: Optional[WebRetriever] = None,
132
+ ):
133
+ self.excel_path = excel_path
134
+ self.sheet_name = sheet_name
135
+ self.embeddings_cache_path = embeddings_cache_path
136
+
137
+ self.df = self._load_database()
138
+ self._normalize_columns()
139
+
140
+ self.model = SentenceTransformer(embedding_model_name, device="cpu")
141
+ self.embeddings, self.texts = self._load_or_create_embeddings()
142
+
143
+ self.llm = llm or LocalLLMClient()
144
+ self.web = web or WebRetriever()
145
+
146
+ # ------------------------------------------------------------------
147
+ # Data loading / normalization
148
+ # ------------------------------------------------------------------
149
+ def _load_database(self) -> pd.DataFrame:
150
+ xl = pd.ExcelFile(self.excel_path)
151
+ if self.sheet_name not in xl.sheet_names:
152
+ raise ValueError(
153
+ f"Sheet '{self.sheet_name}' not found in {self.excel_path}. Found: {xl.sheet_names}"
154
+ )
155
+ return pd.read_excel(self.excel_path, sheet_name=self.sheet_name)
156
+
157
+ def _normalize_columns(self) -> None:
158
+ required = [
159
+ "Type",
160
+ "Region",
161
+ "Sub-Zone",
162
+ "Procedure",
163
+ "Technique / Technology / Brand",
164
+ "Signature technique, brands, technology",
165
+ "Aesthetic Concerns",
166
+ "Verbatims",
167
+ ]
168
+ missing = [c for c in required if c not in self.df.columns]
169
+ if missing:
170
+ raise ValueError(
171
+ f"database.xlsx is missing required columns: {missing}. Found: {list(self.df.columns)}"
172
+ )
173
+
174
+ for col in ["Type", "Region", "Sub-Zone", "Procedure"]:
175
+ self.df[col] = self.df[col].astype(str).fillna("").str.strip()
176
+
177
+ self.df["_region_norm"] = self.df["Region"].astype(str).apply(_norm_text)
178
+ self.df["_subzone_norm"] = self.df["Sub-Zone"].astype(str).apply(_norm_text)
179
+ self.df["_type_norm"] = self.df["Type"].astype(str).apply(_norm_type_value)
180
+
181
+ def get_regions(self) -> List[str]:
182
+ regions = [r for r in self.df["Region"].dropna().unique().tolist() if str(r).strip()]
183
+ return sorted(regions)
184
+
185
+ def get_sub_zones(self, region: str) -> List[str]:
186
+ r = _norm_text(region)
187
+ sub = self.df[self.df["_region_norm"].eq(r)]["Sub-Zone"].dropna().unique().tolist()
188
+ return sorted([s for s in sub if str(s).strip()])
189
+
190
+ # ------------------------------------------------------------------
191
+ # Embedding text creation
192
+ # ------------------------------------------------------------------
193
+ def _row_to_text(self, row: pd.Series) -> str:
194
+ def safe(col: str) -> str:
195
+ v = row.get(col, "")
196
+ if pd.isna(v):
197
+ return ""
198
+ return str(v).strip()
199
+
200
+ parts = [
201
+ f"Type: {safe('Type')}",
202
+ f"Region: {safe('Region')}",
203
+ f"Sub-Zone: {safe('Sub-Zone')}",
204
+ f"Procedure: {safe('Procedure')}",
205
+ ]
206
+
207
+ tech = safe("Technique / Technology / Brand")
208
+ if tech:
209
+ parts.append(f"Technique/Technology/Brand: {tech}")
210
+
211
+ sig = safe("Signature technique, brands, technology")
212
+ if sig:
213
+ parts.append(f"Signature techniques/brands/technology: {sig}")
214
+
215
+ concerns = safe("Aesthetic Concerns")
216
+ if concerns:
217
+ parts.append(f"Aesthetic concerns: {concerns}")
218
+
219
+ verb = safe("Verbatims")
220
+ if verb:
221
+ parts.append(f"Patient verbatims: {verb}")
222
+
223
+ return " | ".join([p for p in parts if p.strip()])
224
+
225
+ # ------------------------------------------------------------------
226
+ # Embedding cache
227
+ # ------------------------------------------------------------------
228
+ def _load_or_create_embeddings(self) -> Tuple[np.ndarray, List[str]]:
229
+ if os.path.exists(self.embeddings_cache_path):
230
+ try:
231
+ with open(self.embeddings_cache_path, "rb") as f:
232
+ data = pickle.load(f)
233
+
234
+ if (
235
+ data.get("excel_path") == os.path.abspath(self.excel_path)
236
+ and data.get("sheet_name") == self.sheet_name
237
+ ):
238
+ emb = np.array(data["embeddings"], dtype=np.float32)
239
+ txt = list(data["texts"])
240
+ if len(txt) == len(self.df) and emb.shape[0] == len(self.df):
241
+ return emb, txt
242
+ except Exception:
243
+ pass
244
+
245
+ return self._create_embeddings()
246
+
247
+ def _create_embeddings(self) -> Tuple[np.ndarray, List[str]]:
248
+ texts = [self._row_to_text(self.df.iloc[i]) for i in range(len(self.df))]
249
+ embeddings = self.model.encode(texts, convert_to_numpy=True, show_progress_bar=True).astype(np.float32)
250
+
251
+ payload = {
252
+ "excel_path": os.path.abspath(self.excel_path),
253
+ "sheet_name": self.sheet_name,
254
+ "created_at": time.time(),
255
+ "model": getattr(self.model, "name_or_path", "unknown"),
256
+ "texts": texts,
257
+ "embeddings": embeddings.tolist(),
258
+ }
259
+ with open(self.embeddings_cache_path, "wb") as f:
260
+ pickle.dump(payload, f)
261
+
262
+ return embeddings, texts
263
+
264
+ def refresh_embeddings(self) -> None:
265
+ if os.path.exists(self.embeddings_cache_path):
266
+ os.remove(self.embeddings_cache_path)
267
+ self.embeddings, self.texts = self._create_embeddings()
268
+
269
+ # ------------------------------------------------------------------
270
+ # Retrieval: strict filter + semantic search
271
+ # ------------------------------------------------------------------
272
+ def _candidate_indices(
273
+ self,
274
+ region: str,
275
+ sub_zone: str,
276
+ type_choice_norm: str,
277
+ ) -> np.ndarray:
278
+ r = _norm_text(region)
279
+ df = self.df
280
+ base = df["_region_norm"].eq(r)
281
+
282
+ sz_norm = _norm_text(sub_zone)
283
+ if sz_norm:
284
+ strict_sz = df["_subzone_norm"].eq(sz_norm)
285
+ else:
286
+ strict_sz = pd.Series([True] * len(df), index=df.index)
287
+
288
+ def _apply(base_mask: pd.Series, sz_mask: pd.Series) -> np.ndarray:
289
+ m = base_mask & sz_mask
290
+ if type_choice_norm in {"surgical", "non-surgical"}:
291
+ m = m & df["_type_norm"].eq(type_choice_norm)
292
+ return np.where(m.values)[0]
293
+
294
+ # 1) strict sub-zone
295
+ idxs = _apply(base, strict_sz)
296
+ if idxs.size > 0 or not sz_norm:
297
+ return idxs
298
+
299
+ # 2) fuzzy sub-zone
300
+ fuzzy_sz = _subzone_mask(df, sub_zone)
301
+ idxs = _apply(base, fuzzy_sz)
302
+ return idxs
303
+
304
+ def _semantic_search_over_indices(
305
+ self,
306
+ idxs: np.ndarray,
307
+ query: str,
308
+ top_k: int,
309
+ min_similarity: float,
310
+ ) -> List[RetrievedCandidate]:
311
+ if idxs.size == 0:
312
+ return []
313
+
314
+ q_emb = self.model.encode([query], convert_to_numpy=True).astype(np.float32)
315
+ sub_emb = self.embeddings[idxs]
316
+ sims = cosine_similarity(q_emb, sub_emb)[0]
317
+ order = sims.argsort()[::-1]
318
+
319
+ results: List[RetrievedCandidate] = []
320
+ for rank_pos in order[: max(top_k, 1) * 3]:
321
+ sim = float(sims[rank_pos])
322
+ if sim < min_similarity:
323
+ continue
324
+ row_index = int(idxs[rank_pos])
325
+ row = self.df.iloc[row_index]
326
+ results.append(
327
+ RetrievedCandidate(
328
+ row_index=row_index,
329
+ similarity=sim,
330
+ procedure=str(row.get("Procedure", "")).strip(),
331
+ region=str(row.get("Region", "")).strip(),
332
+ sub_zone=str(row.get("Sub-Zone", "")).strip(),
333
+ type=str(row.get("Type", "")).strip(),
334
+ technique=str(row.get("Technique / Technology / Brand", "")).strip(),
335
+ concerns=str(row.get("Aesthetic Concerns", "")).strip(),
336
+ verbatims=str(row.get("Verbatims", "")).strip(),
337
+ )
338
+ )
339
+ if len(results) >= top_k:
340
+ break
341
+ return results
342
+
343
+ def semantic_search(
344
+ self,
345
+ region: str,
346
+ sub_zone: str,
347
+ type_choice: str,
348
+ issue_text: str,
349
+ top_k: int = 12,
350
+ min_similarity: float = 0.18,
351
+ both_type_balanced: bool = True,
352
+ ) -> List[RetrievedCandidate]:
353
+ issue_text = (issue_text or "").strip()
354
+ if not issue_text:
355
+ return []
356
+
357
+ type_choice_norm = _norm_type_choice(type_choice)
358
+
359
+ query = f"Region: {region} | Sub-Zone: {sub_zone} | Type: {type_choice} | Issue: {issue_text}"
360
+
361
+ if type_choice_norm == "both" and both_type_balanced:
362
+ per_bucket = max(2, top_k // 2)
363
+ idx_s = self._candidate_indices(region, sub_zone, "surgical")
364
+ idx_n = self._candidate_indices(region, sub_zone, "non-surgical")
365
+
366
+ if idx_s.size == 0:
367
+ idx_s = self._candidate_indices(region, "", "surgical")
368
+ if idx_n.size == 0:
369
+ idx_n = self._candidate_indices(region, "", "non-surgical")
370
+
371
+ res_s = self._semantic_search_over_indices(idx_s, query, per_bucket, min_similarity)
372
+ res_n = self._semantic_search_over_indices(idx_n, query, per_bucket, min_similarity)
373
+
374
+ merged = res_s + res_n
375
+ by_idx: Dict[int, RetrievedCandidate] = {}
376
+ for c in merged:
377
+ prev = by_idx.get(c.row_index)
378
+ if prev is None or c.similarity > prev.similarity:
379
+ by_idx[c.row_index] = c
380
+
381
+ out = list(by_idx.values())
382
+ out.sort(key=lambda x: x.similarity, reverse=True)
383
+ return out[:top_k]
384
+
385
+ idxs = self._candidate_indices(region, sub_zone, type_choice_norm if type_choice_norm != "both" else "")
386
+ if idxs.size == 0:
387
+ idxs = self._candidate_indices(region, "", type_choice_norm if type_choice_norm != "both" else "")
388
+ if idxs.size == 0:
389
+ r = _norm_text(region)
390
+ idxs = np.where(self.df["_region_norm"].eq(r).values)[0]
391
+
392
+ return self._semantic_search_over_indices(idxs, query, top_k, min_similarity)
393
+
394
+ # ------------------------------------------------------------------
395
+ # NEW: Global semantic search + mismatch detection
396
+ # ------------------------------------------------------------------
397
+ def _global_semantic_search(
398
+ self,
399
+ issue_text: str,
400
+ top_k: int = 20,
401
+ min_similarity: float = 0.18,
402
+ ) -> List[RetrievedCandidate]:
403
+ """Search across the ENTIRE database to infer likely region/sub-zones for the issue."""
404
+ issue_text = (issue_text or "").strip()
405
+ if not issue_text:
406
+ return []
407
+
408
+ q_emb = self.model.encode([issue_text], convert_to_numpy=True).astype(np.float32)
409
+ sims = cosine_similarity(q_emb, self.embeddings)[0]
410
+ order = sims.argsort()[::-1]
411
+
412
+ results: List[RetrievedCandidate] = []
413
+ for idx in order[: max(top_k, 1) * 4]:
414
+ sim = float(sims[idx])
415
+ if sim < min_similarity:
416
+ continue
417
+ row = self.df.iloc[int(idx)]
418
+ results.append(
419
+ RetrievedCandidate(
420
+ row_index=int(idx),
421
+ similarity=sim,
422
+ procedure=str(row.get("Procedure", "")).strip(),
423
+ region=str(row.get("Region", "")).strip(),
424
+ sub_zone=str(row.get("Sub-Zone", "")).strip(),
425
+ type=str(row.get("Type", "")).strip(),
426
+ technique=str(row.get("Technique / Technology / Brand", "")).strip(),
427
+ concerns=str(row.get("Aesthetic Concerns", "")).strip(),
428
+ verbatims=str(row.get("Verbatims", "")).strip(),
429
+ )
430
+ )
431
+ if len(results) >= top_k:
432
+ break
433
+ return results
434
+
435
+ def _detect_mismatch(
436
+ self,
437
+ selected_region: str,
438
+ selected_sub_zone: str,
439
+ local_candidates: List[RetrievedCandidate],
440
+ global_candidates: List[RetrievedCandidate],
441
+ ) -> Tuple[bool, str, List[Tuple[str, str, float]]]:
442
+ """Decide whether the issue text appears inconsistent with selected region/sub-zone.
443
+
444
+ Returns:
445
+ mismatch: bool
446
+ reason: short string
447
+ suggestions: list of (Region, Sub-Zone, score) from global candidates
448
+ """
449
+ sr = _norm_text(selected_region)
450
+ ssz = _norm_text(selected_sub_zone)
451
+
452
+ local_best = local_candidates[0].similarity if local_candidates else 0.0
453
+ global_best = global_candidates[0].similarity if global_candidates else 0.0
454
+
455
+ # Dedup suggested (Region, Sub-Zone) from global
456
+ seen = set()
457
+ suggestions: List[Tuple[str, str, float]] = []
458
+ for c in global_candidates:
459
+ key = (c.region, c.sub_zone)
460
+ if key in seen:
461
+ continue
462
+ seen.add(key)
463
+ suggestions.append((c.region, c.sub_zone, float(c.similarity)))
464
+ if len(suggestions) >= 8:
465
+ break
466
+
467
+ # If no global signal, do not block
468
+ if global_best <= 0.0:
469
+ return False, "no_global_signal", suggestions
470
+
471
+ # If local candidates are empty, and global is strong -> mismatch
472
+ if not local_candidates and global_best >= 0.45:
473
+ return True, "no_local_candidates_but_global_strong", suggestions
474
+
475
+ # Check whether selected region/sub-zone appears in global top results
476
+ def _same_selected(c: RetrievedCandidate) -> bool:
477
+ if _norm_text(c.region) != sr:
478
+ return False
479
+ # allow fuzzy containment between selected sub-zone and global sub-zone
480
+ cz = _norm_text(c.sub_zone)
481
+ if not ssz:
482
+ return True
483
+ if cz == ssz:
484
+ return True
485
+ if ssz in cz or cz in ssz:
486
+ return True
487
+ return False
488
+
489
+ selected_in_global = any(_same_selected(c) for c in global_candidates[:10])
490
+
491
+ # Mismatch rule (tuned for stability on small models):
492
+ # - global is meaningfully strong
493
+ # - local best is weak relative to global
494
+ # - and the selected region/sub-zone does NOT appear among global top signals
495
+ gap = global_best - local_best
496
+ if (global_best >= 0.50 and gap >= 0.10 and not selected_in_global):
497
+ return True, f"global_much_stronger_than_selected (gap={gap:.2f})", suggestions
498
+
499
+ # Another conservative rule: local best is very low but global is decent
500
+ if (global_best >= 0.48 and local_best <= 0.35 and not selected_in_global):
501
+ return True, "selected_signal_weak_vs_global", suggestions
502
+
503
+ return False, "no_mismatch", suggestions
504
+
505
+ def _build_mismatch_message(
506
+ self,
507
+ selected_region: str,
508
+ selected_sub_zone: str,
509
+ issue_text: str,
510
+ suggestions: List[Tuple[str, str, float]],
511
+ ) -> str:
512
+ """Use LLM to write a friendly mismatch notice, but force exact DB names."""
513
+ sug_lines = []
514
+ for i, (r, sz, sc) in enumerate(suggestions, start=1):
515
+ sug_lines.append(f"{i}. Region: {r} | Sub-Zone: {sz}")
516
+
517
+ allowed_block = "\n".join(sug_lines) if sug_lines else "(No suggestions available)"
518
+
519
+ prompt = f"""
520
+ You are an assistant in an Aesthetic treatment search app.
521
+
522
+ The user selected:
523
+ - Region: {selected_region}
524
+ - Sub-Zone: {selected_sub_zone}
525
+
526
+ But the user's described problem is:
527
+ "{issue_text}"
528
+
529
+ Task:
530
+ Write a short, polite warning that the selected Region/Sub-Zone do not seem appropriate for the problem,
531
+ and suggest the most appropriate Region/Sub-Zone choices from the database list below.
532
+
533
+ IMPORTANT RULES:
534
+ - You MUST use the Region/Sub-Zone names EXACTLY as provided (do not invent new names).
535
+ - Do NOT recommend procedures now; only guide the user to select correct Region/Sub-Zone.
536
+ - Output MUST be Markdown.
537
+
538
+ Database-based suggestions (use these exact strings):
539
+ {allowed_block}
540
+
541
+ Markdown output format:
542
+ ## Notice
543
+ <1-2 sentence apology + mismatch explanation>
544
+
545
+ ## Suggested Region/Sub-Zones
546
+ - Region → Sub-Zone
547
+ - Region → Sub-Zone
548
+
549
+ ## Next step
550
+ <one sentence instruction to re-run search with suggested categories>
551
+ """.strip()
552
+
553
+ try:
554
+ msg = self.llm.generate(prompt, temperature=0.2, max_tokens=450)
555
+ msg = (msg or "").strip()
556
+ if msg:
557
+ return msg
558
+ except Exception:
559
+ pass
560
+
561
+ # Fallback deterministic message (no LLM)
562
+ lines = [
563
+ "## Notice",
564
+ "Sorry for inconvenience. Your selected body region/sub-zone does not seem appropriate for your described problem.",
565
+ "",
566
+ "## Suggested Region/Sub-Zones",
567
+ ]
568
+ if suggestions:
569
+ for (r, sz, _) in suggestions[:8]:
570
+ lines.append(f"- {r} → {sz}")
571
+ else:
572
+ lines.append("- (No suggestions found in database)")
573
+ lines += [
574
+ "",
575
+ "## Next step",
576
+ "Please select one of the suggested Region/Sub-Zones above and run the search again.",
577
+ ]
578
+ return "\n".join(lines).strip()
579
+
580
+ # ------------------------------------------------------------------
581
+ # LLM rerank + web-enriched final answer
582
+ # ------------------------------------------------------------------
583
+ def _llm_rerank(
584
+ self,
585
+ issue_text: str,
586
+ region: str,
587
+ sub_zone: str,
588
+ type_choice: str,
589
+ candidates: List[RetrievedCandidate],
590
+ top_k: int = 5,
591
+ ) -> List[RetrievedCandidate]:
592
+ if not candidates:
593
+ return []
594
+
595
+ cand_lines = []
596
+ for i, c in enumerate(candidates, start=1):
597
+ cand_lines.append(
598
+ f"{i}. {c.procedure} (Type: {c.type}; Region/Sub-Zone: {c.region}/{c.sub_zone})\n"
599
+ f" Technique: {c.technique}\n"
600
+ f" Concerns: {c.concerns}\n"
601
+ )
602
+ cand_block = "\n".join(cand_lines)
603
+
604
+ prompt = f"""
605
+ You are a medical-aesthetics assistant helping select the best matching procedures from a structured database.
606
+
607
+ User selections:
608
+ - Region (body part): {region}
609
+ - Sub-Zone: {sub_zone}
610
+ - Treatment preference: {type_choice}
611
+ - Issue/problem (free text): {issue_text}
612
+
613
+ Candidate procedures (already filtered and semantically matched):
614
+ {cand_block}
615
+
616
+ Task:
617
+ Pick the best {top_k} procedures that match the user's issue and selections.
618
+
619
+ Output format (STRICT):
620
+ Return ONLY a numbered list of procedure names, one per line, exactly as written in the candidates.
621
+ Example:
622
+ 1) Procedure Name A
623
+ 2) Procedure Name B
624
+ """.strip()
625
+
626
+ try:
627
+ raw = self.llm.generate(prompt, temperature=0.2, max_tokens=350)
628
+ except Exception:
629
+ return candidates[:top_k]
630
+
631
+ ranked_names: List[str] = []
632
+ for line in (raw or "").splitlines():
633
+ m = re.match(r"^\s*\d+\s*[\)\.-]\s*(.+?)\s*$", line)
634
+ if m:
635
+ ranked_names.append(m.group(1).strip())
636
+
637
+ if not ranked_names:
638
+ data = self.llm.safe_json_loads(raw)
639
+ for item in (data.get("ranked") or [])[:top_k]:
640
+ name = str(item.get("procedure", "")).strip()
641
+ if name:
642
+ ranked_names.append(name)
643
+
644
+ if not ranked_names:
645
+ return candidates[:top_k]
646
+
647
+ name_to_candidate = {c.procedure.lower(): c for c in candidates}
648
+ out: List[RetrievedCandidate] = []
649
+ for nm in ranked_names:
650
+ c = name_to_candidate.get(nm.lower())
651
+ if c and c not in out:
652
+ out.append(c)
653
+ if len(out) >= top_k:
654
+ break
655
+
656
+ for c in candidates:
657
+ if len(out) >= top_k:
658
+ break
659
+ if c not in out:
660
+ out.append(c)
661
+
662
+ return out
663
+
664
+ def _web_enrich(self, procedure_name: str) -> List[WebDoc]:
665
+ queries = [
666
+ f"{procedure_name} downtime recovery time",
667
+ f"{procedure_name} how long does it last results longevity",
668
+ f"{procedure_name} session duration minutes",
669
+ f"{procedure_name} risks side effects complications",
670
+ f"{procedure_name} candidacy who is it for",
671
+ ]
672
+ return self.web.search_and_fetch(queries, max_results_per_query=3, max_docs=8)
673
+
674
+ @staticmethod
675
+ def _format_web_evidence(docs: List[WebDoc], max_sources: int = 6) -> Tuple[str, List[str]]:
676
+ blocks = []
677
+ urls: List[str] = []
678
+ for i, d in enumerate(docs[:max_sources], start=1):
679
+ if d.url:
680
+ urls.append(d.url)
681
+ snippet = (d.snippet or "").strip()
682
+ blocks.append(
683
+ f"[Source {i}] {d.title}\nURL: {d.url}\nSnippet: {snippet}\n"
684
+ )
685
+ return "\n".join(blocks).strip(), urls
686
+
687
+ def answer(
688
+ self,
689
+ region: str,
690
+ sub_zone: str,
691
+ type_choice: str,
692
+ issue_text: str,
693
+ retrieval_k: int = 12,
694
+ final_k: int = 5,
695
+ ) -> Dict[str, object]:
696
+ """Full pipeline: retrieval -> mismatch check -> rerank -> web evidence -> synthesis."""
697
+ issue_text = (issue_text or "").strip()
698
+
699
+ candidates = self.semantic_search(
700
+ region=region,
701
+ sub_zone=sub_zone,
702
+ type_choice=type_choice,
703
+ issue_text=issue_text,
704
+ top_k=int(retrieval_k),
705
+ )
706
+
707
+ # NEW: mismatch detection against global semantic signal
708
+ global_cands = self._global_semantic_search(issue_text=issue_text, top_k=20, min_similarity=0.18)
709
+ mismatch, mismatch_reason, suggestions = self._detect_mismatch(
710
+ selected_region=region,
711
+ selected_sub_zone=sub_zone,
712
+ local_candidates=candidates,
713
+ global_candidates=global_cands,
714
+ )
715
+
716
+ if mismatch:
717
+ answer_md = self._build_mismatch_message(
718
+ selected_region=region,
719
+ selected_sub_zone=sub_zone,
720
+ issue_text=issue_text,
721
+ suggestions=suggestions,
722
+ )
723
+ return {
724
+ "answer_md": answer_md,
725
+ "sources": [],
726
+ "_debug": {
727
+ "mismatch": True,
728
+ "mismatch_reason": mismatch_reason,
729
+ "candidate_count": len(candidates),
730
+ "candidates": [
731
+ {
732
+ "procedure": c.procedure,
733
+ "similarity": round(float(c.similarity), 4),
734
+ "type": c.type,
735
+ "region": c.region,
736
+ "sub_zone": c.sub_zone,
737
+ }
738
+ for c in candidates[: min(len(candidates), 25)]
739
+ ],
740
+ "global_top": [
741
+ {
742
+ "procedure": c.procedure,
743
+ "similarity": round(float(c.similarity), 4),
744
+ "type": c.type,
745
+ "region": c.region,
746
+ "sub_zone": c.sub_zone,
747
+ }
748
+ for c in global_cands[:10]
749
+ ],
750
+ "suggested_region_subzones": [
751
+ {"region": r, "sub_zone": sz, "score": round(float(sc), 4)}
752
+ for (r, sz, sc) in suggestions
753
+ ],
754
+ },
755
+ }
756
+
757
+ # Continue normal pipeline if no mismatch
758
+ best = self._llm_rerank(
759
+ issue_text=issue_text,
760
+ region=region,
761
+ sub_zone=sub_zone,
762
+ type_choice=type_choice,
763
+ candidates=candidates,
764
+ top_k=int(final_k),
765
+ )
766
+
767
+ web_bundle: Dict[str, List[WebDoc]] = {}
768
+ all_urls: List[str] = []
769
+ for c in best:
770
+ docs = self._web_enrich(c.procedure)
771
+ web_bundle[c.procedure] = docs
772
+ for d in docs:
773
+ if d.url:
774
+ all_urls.append(d.url)
775
+
776
+ proc_blocks = []
777
+ for c in best:
778
+ evidence, _ = self._format_web_evidence(web_bundle.get(c.procedure, []))
779
+ proc_blocks.append(
780
+ f"PROCEDURE: {c.procedure}\n"
781
+ f"TYPE (from DB): {c.type}\n"
782
+ f"REGION/SUB-ZONE: {c.region} / {c.sub_zone}\n"
783
+ f"TECHNIQUE/TECHNOLOGY/BRAND (from DB): {c.technique}\n"
784
+ f"AESTHETIC CONCERNS (from DB): {c.concerns}\n"
785
+ f"WEB EVIDENCE:\n{evidence if evidence else '(No web evidence retrieved)'}\n"
786
+ )
787
+
788
+ synthesis_prompt = f"""
789
+ You are a medical-aesthetics research assistant.
790
+
791
+ User:
792
+ - Region: {region}
793
+ - Sub-Zone: {sub_zone}
794
+ - Preference: {type_choice}
795
+ - Issue: {issue_text}
796
+
797
+ Selected procedures (database + web evidence):
798
+ {chr(10).join(proc_blocks)}
799
+
800
+ Task:
801
+ Create a concise, high-signal comparison for the user. For EACH procedure, provide:
802
+ - What it is (1-2 sentences)
803
+ - Invasiveness (Non-invasive / Minimally invasive / Surgical)
804
+ - Typical session duration
805
+ - Downtime / recovery (typical range)
806
+ - When results appear + longevity
807
+ - Key risks / side effects
808
+ - Best suited for (bullet points)
809
+
810
+ Rules:
811
+ - Base factual claims on the WEB EVIDENCE. If something is not supported, write "Not found in evidence".
812
+ - Cite sources as [Source #] next to claims.
813
+ - Output MUST be Markdown.
814
+ - Include a short safety disclaimer at the end.
815
+ """.strip()
816
+
817
+ try:
818
+ answer_md = self.llm.generate(synthesis_prompt, temperature=0.3, max_tokens=900)
819
+ answer_md = (answer_md or "").strip()
820
+ except Exception as e:
821
+ lines = [
822
+ "## Recommended treatments",
823
+ "(LLM generation failed; showing database + web evidence only.)",
824
+ "",
825
+ ]
826
+ for i, c in enumerate(best, start=1):
827
+ lines.append(f"### {i}) {c.procedure} ({c.type})")
828
+ lines.append(f"- Technique: {c.technique}")
829
+ lines.append(f"- Concerns: {c.concerns}")
830
+ docs = web_bundle.get(c.procedure, [])
831
+ if docs:
832
+ lines.append("- Sources:")
833
+ for d in docs[:6]:
834
+ lines.append(f" - {d.url}")
835
+ lines.append("")
836
+ lines.append("**Disclaimer:** This is general information and not medical advice. Consult a licensed clinician.")
837
+ answer_md = "\n".join(lines).strip() + f"\n\n(Reason: {repr(e)})"
838
+
839
+ seen = set()
840
+ dedup_urls: List[str] = []
841
+ for u in all_urls:
842
+ if u and u not in seen:
843
+ seen.add(u)
844
+ dedup_urls.append(u)
845
+
846
+ out: Dict[str, object] = {
847
+ "answer_md": answer_md,
848
+ "sources": dedup_urls,
849
+ "_debug": {
850
+ "mismatch": False,
851
+ "candidate_count": len(candidates),
852
+ "candidates": [
853
+ {
854
+ "procedure": c.procedure,
855
+ "similarity": round(float(c.similarity), 4),
856
+ "type": c.type,
857
+ "region": c.region,
858
+ "sub_zone": c.sub_zone,
859
+ }
860
+ for c in candidates[: min(len(candidates), 25)]
861
+ ],
862
+ "global_top": [
863
+ {
864
+ "procedure": c.procedure,
865
+ "similarity": round(float(c.similarity), 4),
866
+ "type": c.type,
867
+ "region": c.region,
868
+ "sub_zone": c.sub_zone,
869
+ }
870
+ for c in global_cands[:10]
871
+ ],
872
+ },
873
+ }
874
+ return out