Spaces:
Running

File size: 5,096 Bytes
0776bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic classification of a customer's answer to a COD confirmation (Phase 8).



Order of precedence (untrusted text can only ever select one value of :data:`Decision`):



1. a WhatsApp quick-reply button payload we set ourselves: ``CONFIRM:ORD-1021`` /

   ``CANCEL:ORD-1021`` (the order number comes from the payload);

2. keyword rules over short typed replies in English, Roman Urdu and Urdu

   ("haan bhej do", "ji theek hai", "nahi chahiye", "cancel kar do", "ہاں", "نہیں");

   an address-change request ("address change kar do", "pata badal gaya") wins over yes/no,

   because it needs a human; both yes and no words -> ``UNCLEAR``;

3. only if the reply is correlated with a confirmation and the rules say ``UNCLEAR``: the

   quarantine extractor with :class:`ConfirmationReply` (a closed enum, no free fields).

"""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Literal

from pydantic import BaseModel, Field

from core.i18n.normalize import normalize_for_rules

Decision = Literal["CONFIRM", "CANCEL", "ADDRESS_CHANGE", "UNCLEAR"]
MAX_RULE_CHARS = 160

_BUTTON = re.compile(r"^\s*(CONFIRM|CANCEL)\s*:\s*(ORD-\d{3,10})\s*$", re.I)
# Urdu letters (incl. diacritics and digits) but not Arabic punctuation: "ہاں،" (with the
# Urdu comma) must still read as "ہاں" (U+060C-U+061F and U+06D4 are punctuation).
_TOKEN = re.compile(r"[a-z]+|[ء-٩ٮ-ۓە-ۿ]+|[✅❌👍👎]")

YES_WORDS = {
    "haan",
    "han",
    "haa",
    "haanji",
    "ha",
    "ji",
    "jee",
    "jii",
    "g",
    "yes",
    "yess",
    "yep",
    "yeah",
    "ok",
    "okay",
    "okk",
    "confirm",
    "confirmed",
    "theek",
    "thik",
    "theak",
    "bilkul",
    "zaroor",
    "zarur",
    "done",
    "sure",
    "bhejo",
    "bhejdo",
    "send",
    "✅",
    "👍",
    "ہاں",
    "جی",
    "ٹھیک",
    "بالکل",
    "ضرور",
}
YES_PHRASES = ("bhej do", "bhej dein", "bhej den", "kar do confirm", "theek hai", "thik hai")
NO_WORDS = {
    "nahi",
    "nahin",
    "nai",
    "nhi",
    "nahe",
    "na",
    "no",
    "nope",
    "cancel",
    "cancelled",
    "mat",
    "reject",
    "❌",
    "👎",
    "نہیں",
    "نہ",
    "کینسل",
    "منسوخ",
    "مت",
}
NO_PHRASES = (
    "nahi chahiye",
    "nahi chahye",
    "mat bhejo",
    "mat bhejna",
    "cancel kar",
    "don't send",
    "do not send",
    "not needed",
)
ADDRESS_WORDS = {"address", "adress", "addres", "pata", "location", "پتہ", "ایڈریس"}
ADDRESS_CHANGE_HINTS = (
    "change",
    "badal",
    "badla",
    "new",
    "naya",
    "nayi",
    "different",
    "dusra",
    "doosra",
    "update",
    "shift",
    "galat",
    "wrong",
    "تبدیل",
    "نیا",
)


@dataclass(frozen=True)
class RuleResult:
    decision: Decision
    order_number: str | None = None  # from a button payload only
    source: Literal["button", "keyword", "none"] = "none"


def classify(text: str | None, button_payload: str | None = None) -> RuleResult:
    if button_payload:
        m = _BUTTON.match(button_payload)
        if m:
            decision: Decision = "CONFIRM" if m.group(1).upper() == "CONFIRM" else "CANCEL"
            return RuleResult(decision, m.group(2).upper(), "button")
    # Phase 13: Roman Urdu spelling variants ("thk h", "nhi chahye") and Urdu digits.
    t = normalize_for_rules(text).strip()
    if not t or len(t) > MAX_RULE_CHARS:
        return RuleResult("UNCLEAR")
    tokens = set(_TOKEN.findall(t))
    if tokens & ADDRESS_WORDS and any(h in t for h in ADDRESS_CHANGE_HINTS):
        return RuleResult("ADDRESS_CHANGE", source="keyword")
    no_phrase = any(p in t for p in NO_PHRASES)
    rest = t
    for p in NO_PHRASES:  # "mat bhejo" must not also count "bhejo" as a yes
        rest = rest.replace(p, " ")
    no = no_phrase or bool(tokens & NO_WORDS)
    yes = bool(set(_TOKEN.findall(rest)) & YES_WORDS) or any(p in rest for p in YES_PHRASES)
    if no and yes:
        # "nahi, theek hai bhej do"? "confirm nahi"? Ambiguous: let the extractor decide.
        return RuleResult("UNCLEAR")
    if yes:
        return RuleResult("CONFIRM", source="keyword")
    if no:
        return RuleResult("CANCEL", source="keyword")
    return RuleResult("UNCLEAR")


class ConfirmationReply(BaseModel):
    """The only thing the quarantine extractor may return for a confirmation reply."""

    decision: Decision = Field(
        default="UNCLEAR",
        description="CONFIRM = the customer wants the order delivered; CANCEL = they do not "
        "want it; ADDRESS_CHANGE = they ask to deliver somewhere else; UNCLEAR = anything else",
    )


class AddressChangeFields(BaseModel):
    """What the extractor may return for an address-change request (values stay tainted)."""

    new_address: str | None = Field(default=None, max_length=400)
    city: str | None = Field(default=None, max_length=80)