File size: 7,326 Bytes
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
"""
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"],
        )