Sakda101's picture
Deploy FastAPI app to Hugging Face Space
59e06b1
Raw History Blame Contribute Delete
7.33 kB
"""
Correction store — lets staff fix wrong predictions so the system learns.
Two matching strategies (applied in order):
1. Exact match on normalised quote text (instant, zero-cost)
2. TF-IDF cosine similarity >= SIMILARITY_THRESHOLD (catches paraphrases)
When a match is found the corrected objection type and cluster replace the
neural model's output, and the response copy is re-looked up from
responses.csv so it stays consistent.
"""
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
import pandas as pd
from core import database as db
from core.model_config import read_config as _read_model_config
if TYPE_CHECKING:
from core.predictor import ObjectionPredictor, PredictionResult
# Default kept for backwards-compat; runtime value comes from model_config.json
SIMILARITY_THRESHOLD = 0.80
def _get_threshold() -> float:
"""Return the active similarity threshold from config, falling back to default."""
try:
return float(_read_model_config().get("similarity_threshold", SIMILARITY_THRESHOLD))
except Exception:
return SIMILARITY_THRESHOLD
# ---------------------------------------------------------------------------
# Text normalisation
# ---------------------------------------------------------------------------
def _normalize(text: str) -> str:
"""Lower-case + collapse whitespace."""
return " ".join(text.lower().split())
# ---------------------------------------------------------------------------
# Correction store
# ---------------------------------------------------------------------------
class CorrectionStore:
"""In-memory store built from the corrections table.
Call CorrectionStore.from_db() to load fresh data each time.
The TF-IDF index is only built when there are >= 2 corrections
(1 correction can't produce a meaningful similarity matrix).
"""
def __init__(self, corrections: list[dict]):
self.corrections = corrections
self._vectorizer = None
self._matrix = None
if len(corrections) >= 2:
self._build_tfidf()
@classmethod
def from_db(cls) -> "CorrectionStore":
return cls(db.get_all_corrections_raw())
# ----- index build -------------------------------------------------------
def _build_tfidf(self) -> None:
try:
from sklearn.feature_extraction.text import TfidfVectorizer
texts = [c["quote_normalized"] for c in self.corrections]
vec = TfidfVectorizer(ngram_range=(1, 2), analyzer="word", min_df=1)
self._matrix = vec.fit_transform(texts)
self._vectorizer = vec
except Exception:
pass
# ----- lookup ------------------------------------------------------------
def find(self, quote: str) -> Optional[dict]:
"""Return the best-matching correction row, or None."""
if not self.corrections:
return None
norm = _normalize(quote)
# 1. Exact match
for c in self.corrections:
if c["quote_normalized"] == norm:
return c
# 2. TF-IDF similarity
if self._vectorizer is None or self._matrix is None:
return None
try:
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
q_vec = self._vectorizer.transform([norm])
sims = cosine_similarity(q_vec, self._matrix)[0]
best = int(np.argmax(sims))
if float(sims[best]) >= _get_threshold():
return self.corrections[best]
except Exception:
pass
return None
# ---------------------------------------------------------------------------
# Apply corrections to a PredictionResult
# ---------------------------------------------------------------------------
def apply_corrections_to_result(
quote: str,
result: "PredictionResult",
predictor: Optional["ObjectionPredictor"] = None,
customer_group: str = "",
destination: str = "",
) -> "PredictionResult":
"""Check the corrections DB. If a matching correction is found, override
the objection type and cluster, re-look up the response copy, and set
from_correction=True on the returned PredictionResult.
Returns the original result unchanged when no correction matches.
"""
# Import here to avoid circular import at module load time
from core.predictor import PredictionResult
store = CorrectionStore.from_db()
match = store.find(quote)
if match is None:
return result
corrected_type = match["corrected_type"]
corrected_cluster = match["corrected_cluster"]
# Increment usage counter (best-effort; never crash the main flow)
try:
db.increment_correction_applied(match["id"])
except Exception:
pass
# Re-look up response copy so type + cluster + response are consistent
row: Optional[dict] = None
if predictor is not None:
row = predictor._lookup_response(corrected_cluster, customer_group, destination)
if row is None:
row = predictor._lookup_response_by_type(corrected_type)
def _field(key: str) -> Optional[str]:
if row is None:
return None
val = row.get(key)
return str(val) if val is not None and pd.notna(val) and str(val).strip() else None
if row is not None:
return PredictionResult(
quote=result.quote,
objection_type=str(row.get("objection_type", corrected_type)),
objection_type_confidence=result.objection_type_confidence,
cluster=corrected_cluster,
cluster_confidence=result.cluster_confidence,
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=result.stage2_used,
from_correction=True,
correction_id=match["id"],
)
else:
# No response row found — keep response content from original result,
# only override the type + cluster labels.
return PredictionResult(
quote=result.quote,
objection_type=corrected_type,
objection_type_confidence=result.objection_type_confidence,
cluster=corrected_cluster,
cluster_confidence=result.cluster_confidence,
severity=result.severity,
perfect_response=result.perfect_response,
solution=result.solution,
follow_up_question=result.follow_up_question,
video_id=result.video_id,
perfect_response_km=result.perfect_response_km,
solution_km=result.solution_km,
follow_up_question_km=result.follow_up_question_km,
response_lookup_succeeded=result.response_lookup_succeeded,
stage2_used=result.stage2_used,
from_correction=True,
correction_id=match["id"],
)