Download FastAPI/core/predictor.py from Sakda101/explorer-consultant-bot: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/core/predictor.py
- Command line
-
hf download hf://spaces/Sakda101/explorer-consultant-bot/FastAPI/core/predictor.py
-
curl -L -o predictor.py https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/FastAPI/core/predictor.py
27.8 kB
| """ | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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_) | |
| 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 | |
| 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)) | |