File size: 27,777 Bytes
59e06b1
 
 
 
 
 
 
 
 
17c6f13
59e06b1
17c6f13
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3566be
59e06b1
 
e3566be
59e06b1
 
17c6f13
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
e3566be
59e06b1
 
17c6f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59e06b1
 
 
 
 
 
 
 
 
 
17c6f13
59e06b1
 
17c6f13
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3566be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3566be
59e06b1
 
e3566be
 
 
59e06b1
 
 
 
e3566be
59e06b1
 
 
 
e3566be
59e06b1
 
 
 
17c6f13
59e06b1
 
 
17c6f13
59e06b1
 
 
 
17c6f13
59e06b1
 
 
 
17c6f13
59e06b1
 
 
17c6f13
 
59e06b1
 
 
 
 
 
 
 
 
17c6f13
59e06b1
 
 
 
17c6f13
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3566be
 
 
59e06b1
e3566be
 
 
 
 
 
 
 
 
 
 
 
 
 
59e06b1
 
e3566be
 
 
 
 
 
 
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
"""
Two-stage DistilBERT inference for Explorer Consultant Bot.

Stage 1: Predict the objection TYPE (8 classes β€” Competitor Comparison,
Documentation, Lack of Understanding, Location, Price, Processing Time,
Risk / Guarantee Concerns, Trust).

Stage 2: For each type that has its own fine-tuned cluster model, predict the
specific CLUSTER. Types without a Stage 2 model fall back to a deterministic
mapping (Location -> General, Trust -> Trust Issue).

After we have the cluster, we look up the database-backed Browse responses
to retrieve severity,
the perfect response, the recommended solution, the follow-up question,
and the training video id.
"""

from __future__ import annotations

import os
import pickle
import re
import tempfile
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Dict, List, Optional, Tuple

# HF Spaces and the local sandbox may expose a read-only user cache. Keep model
# library cache writes in a temp folder unless deployment explicitly overrides.
_HF_CACHE_DIR = Path(tempfile.gettempdir()) / "explorer_hf_cache"
os.environ.setdefault("HF_HOME", str(_HF_CACHE_DIR))
os.environ.setdefault("TORCH_HOME", str(_HF_CACHE_DIR / "torch"))

import numpy as np
import pandas as pd
import torch
from sklearn.base import BaseEstimator, ClassifierMixin
from transformers import AutoTokenizer, AutoModelForSequenceClassification

from core import database as db


# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------

# Webapp/core/predictor.py  ->  Webapp/  ->  Final Project/
PROJECT_ROOT = Path(__file__).resolve().parents[2]

# On Railway: set ARTIFACTS_DIR env var to point to a persistent volume
# e.g. ARTIFACTS_DIR=/app_data/artifacts
ARTIFACTS_DIR = Path(os.environ.get("ARTIFACTS_DIR", str(PROJECT_ROOT / "artifacts")))
RESPONSES_CSV = PROJECT_ROOT / "data" / "responses.csv"

FINAL_MODEL_PATH = ARTIFACTS_DIR / "final_model.pkl"
STAGE1_DIR = ARTIFACTS_DIR / "distilbert_stage1"

RESPONSE_COLUMNS = (
    "service",
    "customer_group",
    "destination",
    "cluster",
    "objection_type",
    "severity",
    "video_id",
    "perfect_response",
    "perfect_response_km",
    "solution",
    "solution_km",
    "follow_up_question",
    "follow_up_question_km",
)


def _load_response_rows_df() -> pd.DataFrame:
    """Load response rows from the database, falling back to CSV for bootstraps."""
    try:
        rows = db.get_browse_responses()
        if rows:
            return pd.DataFrame(rows)
    except Exception:
        pass
    if RESPONSES_CSV.exists():
        return pd.read_csv(RESPONSES_CSV)
    return pd.DataFrame()


def _normalise_response_rows_df(df: pd.DataFrame) -> pd.DataFrame:
    """Return a lookup-safe response dataframe with all expected columns."""
    df = df.copy()
    for col in RESPONSE_COLUMNS:
        if col not in df.columns:
            df[col] = ""
        df[col] = df[col].fillna("").astype(str).str.strip()
    df["destination"] = df["destination"].str.upper()
    return df

# Folder names use underscores in place of spaces / slashes
STAGE2_DIRS: Dict[str, Path] = {
    "Competitor Comparison": ARTIFACTS_DIR / "distilbert_stage2_Competitor_Comparison",
    "Documentation": ARTIFACTS_DIR / "distilbert_stage2_Documentation",
    "Lack of Understanding": ARTIFACTS_DIR / "distilbert_stage2_Lack_of_Understanding",
    "Price": ARTIFACTS_DIR / "distilbert_stage2_Price",
    "Processing Time": ARTIFACTS_DIR / "distilbert_stage2_Processing_Time",
    "Risk / Guarantee Concerns": ARTIFACTS_DIR / "distilbert_stage2_Risk_Guarantee_Concerns",
}

# For types without a Stage 2 model, fall back to the canonical cluster.
TYPE_FALLBACK_CLUSTER: Dict[str, str] = {
    "Location": "General",
    "Trust": "Trust Issue",
}

# ---------------------------------------------------------------------------
# Cluster alias + per-type override maps
# ---------------------------------------------------------------------------
# Stage 2 models were trained on cluster labels that differ from (or are absent
# in) responses.csv. These maps translate the model's predicted cluster to the
# canonical cluster name used in responses.csv β€” without requiring a retrain.
#
# Priority: per-type overrides take precedence over global aliases.

# Global renames: model uses a different name for the same concept
_CLUSTER_ALIASES: Dict[str, str] = {
    "Discount Issue":   "Pricing Issue",   # Price Stage 2
    "Time Constraints": "Processing Time", # Processing Time Stage 2
}

# Per-type overrides: cluster predicted by Stage 2 that doesn't exist under
# that objection_type in responses.csv β€” mapped to the closest valid cluster.
_CLUSTER_OVERRIDE: Dict[str, Dict[str, str]] = {
    # Competitor Comparison Stage 2 was trained on mixed cluster labels;
    # only "Customer Service" exists in responses.csv for this type.
    "Competitor Comparison": {
        "Document Forgery":  "Customer Service",
        "Price":             "Customer Service",
        "Processing Time":   "Customer Service",
        "Refund":            "Customer Service",
        "Visa Guarantee":    "Customer Service",
    },
    # Documentation Stage 2 occasionally predicts Document Forgery
    # (belongs to Risk / Guarantee Concerns). Fall back to Work Permit.
    "Documentation": {
        "Document Forgery": "Work Permit",
    },
    # Lack of Understanding Stage 2 can predict Previous Rejection
    # (belongs to Trust). Map to the nearest LoU cluster.
    "Lack of Understanding": {
        "Previous Rejection": "Visa Terms",
    },
    # Processing Time Stage 2 outputs General when confidence is low
    "Processing Time": {
        "General": "Processing Time",
    },
    # Risk / Guarantee Concerns Stage 2 outputs clusters not in responses.csv.
    # Map each to the closest valid cluster.
    "Risk / Guarantee Concerns": {
        "Approval Issue":    "Visa Guarantee",
        "Previous Rejection":"Visa Guarantee",
        "Refund":            "Visa Guarantee",
        "Travel History":    "Document Forgery",
    },
}


# ---------------------------------------------------------------------------
# Result container
# ---------------------------------------------------------------------------

@dataclass
class PredictionResult:
    quote: str
    objection_type: str
    objection_type_confidence: float
    cluster: str
    cluster_confidence: Optional[float]  # None if fallback was used
    severity: Optional[str]
    perfect_response: Optional[str]
    solution: Optional[str]
    follow_up_question: Optional[str]
    video_id: Optional[str]
    perfect_response_km: Optional[str]
    solution_km: Optional[str]
    follow_up_question_km: Optional[str]
    response_lookup_succeeded: bool
    stage2_used: bool
    from_correction: bool = False
    correction_id: Optional[int] = None

    def to_dict(self) -> dict:
        return asdict(self)


# ---------------------------------------------------------------------------
# Stage models
# ---------------------------------------------------------------------------

class _StageModel:
    """Wraps one DistilBERT classifier + its label encoder.

    Loads from a local path if it exists, otherwise falls back to
    downloading directly from Hugging Face Hub using HF_REPO_ID env var.
    """

    def __init__(self, model_dir: Path, device: torch.device):
        self.model_dir = model_dir
        self.device = device

        hf_repo  = os.environ.get("HF_REPO_ID", "")
        hf_token = os.environ.get("HF_TOKEN", "") or None

        if model_dir.exists():
            # Load from local disk (local dev or after snapshot_download)
            # Do NOT pass subfolder=None β€” some transformers versions crash on it
            self.tokenizer = AutoTokenizer.from_pretrained(
                str(model_dir),
                token=hf_token,
            )
            self.model = AutoModelForSequenceClassification.from_pretrained(
                str(model_dir),
                token=hf_token,
            )
            self.model.to(device)
            self.model.eval()

            with open(model_dir / "label_encoder.pkl", "rb") as f:
                self.label_encoder = pickle.load(f)

        elif hf_repo:
            # Load directly from HF Hub β€” no local download needed
            try:
                subfolder = str(model_dir.relative_to(ARTIFACTS_DIR.parent))
            except ValueError:
                subfolder = model_dir.name

            self.tokenizer = AutoTokenizer.from_pretrained(
                hf_repo,
                subfolder=subfolder,
                token=hf_token,
            )
            self.model = AutoModelForSequenceClassification.from_pretrained(
                hf_repo,
                subfolder=subfolder,
                token=hf_token,
            )
            self.model.to(device)
            self.model.eval()

            from huggingface_hub import hf_hub_download
            pkl_path = hf_hub_download(
                repo_id=hf_repo,
                filename=f"{subfolder}/label_encoder.pkl",
                token=hf_token,
            )
            with open(pkl_path, "rb") as f:
                self.label_encoder = pickle.load(f)

        else:
            raise FileNotFoundError(
                f"Model not found at {model_dir} and HF_REPO_ID is not set."
            )

        self.classes_ = list(self.label_encoder.classes_)

    @torch.no_grad()
    def predict(self, text: str, max_length: int = 256) -> Tuple[str, float, List[Tuple[str, float]]]:
        enc = self.tokenizer(
            text,
            return_tensors="pt",
            truncation=True,
            padding=True,
            max_length=max_length,
        )
        # DistilBERT has no token_type_ids β€” remove it if the tokenizer added it
        enc = {k: v.to(self.device) for k, v in enc.items() if k != "token_type_ids"}
        logits = self.model(**enc).logits[0]
        probs = torch.softmax(logits, dim=-1).cpu().numpy()
        idx = int(probs.argmax())
        label = str(self.classes_[idx])
        conf = float(probs[idx])
        ranked = sorted(
            zip(self.classes_, probs.tolist()),
            key=lambda x: x[1],
            reverse=True,
        )
        return label, conf, [(str(c), float(p)) for c, p in ranked]


# ---------------------------------------------------------------------------
# Keyword-based override rules
# ---------------------------------------------------------------------------
# The Stage 1 model has known misclassification cases (e.g., processing-time
# questions being labelled as "Location"). These regex rules act as a guard:
# if the quote strongly signals a particular type, we force that type
# regardless of what the neural model predicted. Add new entries here
# whenever a recurring misclassification pattern is identified.

_KEYWORD_OVERRIDES: List[Tuple[re.Pattern, str]] = [
    (
        re.compile(
            r"(too long|taking (so |too )?long|how long (does|will|is|do)|"
            r"processing time|when will (my |the )?visa|still (waiting|processing)|"
            r"visa (delay|delayed|slow)|how many (days|weeks)|"
            r"wait(ing)? (for )?(my |the )?visa|visa.*tak(e|ing)|"
            r"tak(e|ing).*long|tak(e|ing).*(process|visa)|"
            r"(process|visa).*(slow|fast|quick|speed)|long.*process)",
            re.IGNORECASE,
        ),
        "Processing Time",
    ),
]


def _keyword_override(quote: str) -> Optional[str]:
    """Return a forced objection type if the quote matches a known keyword
    pattern. Returns None to let the neural model decide otherwise."""
    for pattern, forced_type in _KEYWORD_OVERRIDES:
        if pattern.search(quote):
            return forced_type
    return None


class HierarchicalTextClassifier(BaseEstimator, ClassifierMixin):
    """Notebook-compatible class used when unpickling final_model.pkl."""

    def __init__(self, base_estimator_factory):
        self.base_estimator_factory = base_estimator_factory

    def fit(self, X, y_type, y_cluster):
        X = np.asarray(X, dtype=object)
        y_type = np.asarray(y_type)
        y_cluster = np.asarray(y_cluster)
        self.stage1_ = self.base_estimator_factory()
        self.stage1_.fit(X, y_type)
        self.stage2_ = {}
        self.type_to_clusters_ = {}
        for t in sorted(np.unique(y_type)):
            mask = y_type == t
            clusters_in_type = np.unique(y_cluster[mask])
            self.type_to_clusters_[t] = list(clusters_in_type)
            if len(clusters_in_type) == 1:
                self.stage2_[t] = None
            else:
                clf = self.base_estimator_factory()
                clf.fit(X[mask], y_cluster[mask])
                self.stage2_[t] = clf
        return self

    def predict_type(self, X):
        return self.stage1_.predict(np.asarray(X, dtype=object))

    def predict_cluster(self, X, predicted_types=None):
        X = np.asarray(X, dtype=object)
        if predicted_types is None:
            predicted_types = self.predict_type(X)
        clusters = np.empty(len(X), dtype=object)
        for t in np.unique(predicted_types):
            mask = predicted_types == t
            if self.stage2_.get(t) is None:
                clusters[mask] = self.type_to_clusters_[t][0]
            else:
                clusters[mask] = self.stage2_[t].predict(X[mask])
        return clusters

    def predict(self, X):
        y_type_pred = self.predict_type(X)
        y_cluster_pred = self.predict_cluster(X, y_type_pred)
        return np.column_stack([y_type_pred, y_cluster_pred])

    def predict_type_proba(self, X):
        return self.stage1_.predict_proba(np.asarray(X, dtype=object))


class _NotebookBundleUnpickler(pickle.Unpickler):
    def find_class(self, module: str, name: str):
        if module == "__main__" and name == "HierarchicalTextClassifier":
            return HierarchicalTextClassifier
        if module == "__main__" and name.startswith("make_") and name.endswith("_pipeline"):
            return _unused_notebook_pipeline_factory
        return super().find_class(module, name)


def _unused_notebook_pipeline_factory():
    raise RuntimeError("Notebook pipeline factories are only kept for pickle compatibility.")


def _preprocess_text(text: str) -> str:
    text = str(text).lower()
    text = re.sub(r"http\S+|www\S+", " ", text)
    text = re.sub(r"[^a-z0-9\s']", " ", text)
    text = re.sub(r"\s+", " ", text).strip()
    return text


class _FinalModelBundle:
    """Adapter for the retrained notebook bundle saved as final_model.pkl."""

    def __init__(self, model_path: Path):
        with model_path.open("rb") as f:
            self.bundle = _NotebookBundleUnpickler(f).load()
        self.model = self.bundle.get("classical_model") or self.bundle["hierarchical_svm"]
        self.stage2_used = True
        self.name = self.bundle.get("classical_model_name") or self.bundle.get("best_model_name") or "final_model.pkl"

    def predict(self, quote: str) -> Tuple[str, float, str, Optional[float]]:
        X = np.asarray([_preprocess_text(quote)], dtype=object)
        stage1 = self.model.stage1_
        probs = stage1.predict_proba(X)[0]
        classes = list(stage1.classes_)
        idx = int(np.argmax(probs))
        obj_type = str(classes[idx])
        type_conf = float(probs[idx])

        if self.model.stage2_.get(obj_type) is None:
            cluster = str(self.model.type_to_clusters_[obj_type][0])
            cluster_conf: Optional[float] = 1.0
        else:
            stage2 = self.model.stage2_[obj_type]
            cluster_probs = stage2.predict_proba(X)[0]
            cluster_classes = list(stage2.classes_)
            cluster_idx = int(np.argmax(cluster_probs))
            cluster = str(cluster_classes[cluster_idx])
            cluster_conf = float(cluster_probs[cluster_idx])

        return obj_type, type_conf, cluster, cluster_conf


# ---------------------------------------------------------------------------
# Top-level predictor
# ---------------------------------------------------------------------------

class ObjectionPredictor:
    """Lazy two-stage objection -> cluster -> response predictor.

    Stage 2 models are loaded the first time their type is needed so we do
    not pay the full ~2GB RAM cost up front.
    """

    def __init__(
        self,
        device: Optional[str] = None,
        stage1_name: str = "distilbert_stage1",
        pipeline: str = "two_stage",
    ):
        if device is None:
            device = "cuda" if torch.cuda.is_available() else "cpu"
        self.device = torch.device(device)
        self.pipeline = pipeline  # "two_stage" | "flat_cluster"
        self.final_model: Optional[_FinalModelBundle] = None

        stage1_dir = ARTIFACTS_DIR / stage1_name
        if FINAL_MODEL_PATH.exists():
            self.final_model = _FinalModelBundle(FINAL_MODEL_PATH)
        elif not stage1_dir.exists() and not os.environ.get("HF_REPO_ID", ""):
            raise FileNotFoundError(
                f"Stage 1 model not found at {stage1_dir}. "
                f"Make sure the 'artifacts/' folder is alongside the Webapp."
            )
        self.stage1 = None if self.final_model else _StageModel(stage1_dir, self.device)
        self._stage2_cache: Dict[str, _StageModel] = {}

        # Flat-cluster pipeline: load the shared distilbert_cluster model
        self._flat_cluster_model: Optional[_StageModel] = None
        if self.final_model is None and pipeline == "flat_cluster":
            flat_dir = ARTIFACTS_DIR / "distilbert_cluster"
            if flat_dir.exists():
                self._flat_cluster_model = _StageModel(flat_dir, self.device)

        self.responses_df = pd.DataFrame()
        self._responses_by_key: Dict[tuple, dict] = {}
        self._responses_by_cluster: Dict[str, dict] = {}
        self._responses_by_type: Dict[str, List[dict]] = {}
        self.reload_responses()

    # ----- Reload responses from disk ------------------------------------------

    def reload_responses(self) -> None:
        """Re-read database-backed Browse responses and rebuild lookup indices.

        Call this after the Browse page saves an edit so the predictor picks up
        the new content without reloading the (expensive) ML models.
        """
        self.responses_df = _normalise_response_rows_df(_load_response_rows_df())

        self._responses_by_key = {}
        for _, row in self.responses_df.iterrows():
            if not str(row.get("cluster", "")).strip():
                continue
            key = (
                str(row.get("customer_group", "")).strip(),
                str(row.get("destination", "")).strip(),
                str(row["cluster"]).strip().lower(),
            )
            self._responses_by_key[key] = row.to_dict()

        self._responses_by_cluster = {}
        for _, row in self.responses_df.iterrows():
            if str(row.get("customer_group", "")).strip() == "" and str(row.get("cluster", "")).strip():
                self._responses_by_cluster[str(row["cluster"]).strip().lower()] = row.to_dict()

        self._responses_by_type = {}
        for _, row in self.responses_df.iterrows():
            if str(row.get("customer_group", "")).strip() == "" and str(row.get("objection_type", "")).strip():
                t_key = str(row["objection_type"]).strip().lower()
                self._responses_by_type.setdefault(t_key, []).append(row.to_dict())

    # ----- Stage 2 lazy loader -------------------------------------------------

    def _get_stage2(self, objection_type: str) -> Optional[_StageModel]:
        if objection_type not in STAGE2_DIRS:
            return None
        if objection_type in self._stage2_cache:
            return self._stage2_cache[objection_type]
        d = STAGE2_DIRS[objection_type]
        if not d.exists():
            return None
        m = _StageModel(d, self.device)
        self._stage2_cache[objection_type] = m
        return m

    # ----- Response lookup -----------------------------------------------------

    def _lookup_response(
        self,
        cluster: str,
        customer_group: str = "",
        destination: str = "",
    ) -> Optional[dict]:
        """Tiered lookup:
        1. (customer_group, destination, cluster) β€” most specific
        2. (customer_group, "",          cluster) β€” group-level fallback
        3. ("",             "",          cluster) β€” original generic row
        """
        cl = cluster.strip().lower()
        cg = (customer_group or "").strip()
        dest = (destination or "").strip()

        if cg:
            if dest:
                row = self._responses_by_key.get((cg, dest, cl))
                if row:
                    return row
            row = self._responses_by_key.get((cg, "", cl))
            if row:
                return row
        return self._responses_by_cluster.get(cl)

    def _lookup_response_by_type(self, objection_type: str) -> Optional[dict]:
        rows = self._responses_by_type.get(objection_type.strip().lower())
        if not rows:
            return None
        # If multiple rows share this type, pick the alphabetically first
        # cluster for determinism.
        return sorted(rows, key=lambda r: str(r.get("cluster", "")))[0]

    # ----- Public API ----------------------------------------------------------

    def predict(
        self,
        quote: str,
        customer_group: str = "",
        destination: str = "",
    ) -> PredictionResult:
        quote = (quote or "").strip()
        if not quote:
            raise ValueError("quote cannot be empty")

        if self.final_model is not None:
            obj_type, type_conf, cluster, cluster_conf = self.final_model.predict(quote)
            stage2_used = self.final_model.stage2_used
        else:
            # Stage 1: objection type
            obj_type, type_conf, _ = self.stage1.predict(quote)

            # Keyword override β€” corrects known Stage 1 misclassifications
            # (e.g., processing-time questions labelled as "Location").
            forced_type = _keyword_override(quote)
            if forced_type is not None and forced_type != obj_type:
                obj_type = forced_type
                type_conf = 1.0  # rule-based; treat as certain

            # Stage 2: cluster (or deterministic fallback)
            if self.pipeline == "flat_cluster" and self._flat_cluster_model is not None:
                # Use the shared flat cluster model regardless of objection type
                cluster, cluster_conf, _ = self._flat_cluster_model.predict(quote)
                stage2_used = True
            else:
                stage2 = self._get_stage2(obj_type)
                if stage2 is not None:
                    cluster, cluster_conf, _ = stage2.predict(quote)
                    stage2_used = True
                else:
                    cluster = TYPE_FALLBACK_CLUSTER.get(obj_type, "General")
                    cluster_conf = None
                    stage2_used = False

        # Normalise cluster name:
        # 1. Apply global aliases (e.g. "Discount Issue" -> "Pricing Issue")
        cluster = _CLUSTER_ALIASES.get(cluster, cluster)
        # 2. Apply per-type overrides for clusters that don't exist under this
        #    objection_type in responses.csv (e.g. CC predicting "Refund")
        type_overrides = _CLUSTER_OVERRIDE.get(obj_type, {})
        if cluster in type_overrides:
            cluster = type_overrides[cluster]

        # Look up response metadata: try by cluster first, then by type
        row = self._lookup_response(cluster, customer_group, destination)
        used_type_fallback = False
        if row is None:
            # The Stage 2 model can output finer-grained cluster names than
            # responses.csv stores (e.g., Price -> "Pricing Issue" /
            # "Discount Issue", Processing Time -> "Time Constraints", Risk /
            # Guarantee Concerns -> "Approval Issue"). When that happens, fall
            # back to any response row whose objection_type matches Stage 1.
            row = self._lookup_response_by_type(obj_type)
            used_type_fallback = row is not None

        if row is None:
            return PredictionResult(
                quote=quote,
                objection_type=obj_type,
                objection_type_confidence=type_conf,
                cluster=cluster,
                cluster_confidence=cluster_conf,
                severity=None,
                perfect_response=None,
                solution=None,
                follow_up_question=None,
                video_id=None,
                perfect_response_km=None,
                solution_km=None,
                follow_up_question_km=None,
                response_lookup_succeeded=False,
                stage2_used=stage2_used,
            )

        # The canonical objection_type in responses.csv is the source of truth
        # for display (it ensures cluster + type pair is consistent)
        canonical_type = str(row.get("objection_type", obj_type))
        # If we used the type fallback, keep the model's predicted (finer)
        # cluster label visible to the user, but pull the response copy
        # from the parent row.
        display_cluster = cluster if used_type_fallback else str(row.get("cluster", cluster))

        def _field(key: str) -> Optional[str]:
            val = row.get(key)
            return str(val) if val is not None and pd.notna(val) and str(val).strip() else None

        return PredictionResult(
            quote=quote,
            objection_type=canonical_type,
            objection_type_confidence=type_conf,
            cluster=display_cluster,
            cluster_confidence=cluster_conf,
            severity=_field("severity"),
            perfect_response=_field("perfect_response"),
            solution=_field("solution"),
            follow_up_question=_field("follow_up_question"),
            video_id=_field("video_id"),
            perfect_response_km=_field("perfect_response_km"),
            solution_km=_field("solution_km"),
            follow_up_question_km=_field("follow_up_question_km"),
            response_lookup_succeeded=True,
            stage2_used=stage2_used,
        )


# ---------------------------------------------------------------------------
# Streamlit cache helper
# ---------------------------------------------------------------------------

def get_predictor(stage1_name: str = "distilbert_stage1", pipeline: str = "two_stage") -> ObjectionPredictor:
    """Lazy-loaded singleton for use inside Streamlit (cached per config combo)."""
    try:
        import streamlit as st

        @st.cache_resource(show_spinner="Loading DistilBERT models (this happens once)...")
        def _load(s1: str, pl: str) -> ObjectionPredictor:
            return ObjectionPredictor(stage1_name=s1, pipeline=pl)

        return _load(stage1_name, pipeline)
    except ImportError:
        # CLI / test usage β€” ignore config, use defaults
        global _CLI_PREDICTOR
        try:
            return _CLI_PREDICTOR  # type: ignore[name-defined]
        except NameError:
            _CLI_PREDICTOR = ObjectionPredictor()  # type: ignore[name-defined]
            return _CLI_PREDICTOR  # type: ignore[name-defined]


if __name__ == "__main__":
    # Quick CLI smoke test:  python -m core.predictor "your quote here"
    import sys
    import json

    quote = " ".join(sys.argv[1:]) or "Why is your service so expensive compared to others?"
    p = get_predictor()
    result = p.predict(quote)
    print(json.dumps(result.to_dict(), indent=2, ensure_ascii=False))