File size: 2,391 Bytes
e4d2e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

from __future__ import annotations

import argparse
import json
import os
import re

from common import HERE, OUT, read_jsonl, write_jsonl

LEXICON = {
    "SMS": ("es-em-es", "acronym"), "IT": ("ay-ti", "acronym"), "AI": ("ey-ay", "acronym"),
    "SMM": ("es-em-em", "acronym"), "HR": ("eych-ar", "acronym"), "CRM": ("si-ar-em", "acronym"),
    "ID": ("ay-di", "acronym"), "VIP": ("vip", "acronym"), "IELTS": ("ayelts", "acronym"),
    "TOEFL": ("tofl", "acronym"), "PDF": ("pe-de-ef", "acronym"), "QR": ("kyu-ar", "acronym"),
    "Wi-Fi": ("vay-fay", "acronym"), "MRT": ("em-er-te", "acronym_ru"), "UZI": ("uzi", "acronym_ru"),
    "EKG": ("e-ka-ge", "acronym_ru"), "MSKT": ("em-es-ka-te", "acronym_ru"), "NDS": ("en-de-es", "acronym_ru"),
    "YouTube": ("Yutub", "brand"), "iPhone": ("Ayfon", "brand"), "WhatsApp": ("Vatsap", "brand"),
    "Google": ("Gugl", "brand"), "Zoom": ("Zum", "brand"), "Click": ("Klik", "brand"),
    "Payme": ("Peymi", "brand"), "Uzcard": ("Uzkard", "brand"), "BYD": ("bi-vay-di", "brand"),
    "Chevrolet": ("Shevrole", "brand"), "Excel": ("Eksel", "brand"), "Gmail": ("Jimeyl", "brand"),
}
SEND_WRITTEN = {"MSKT"}
_TERM_RE = re.compile(r"(?<![\w'-])(" + "|".join(sorted(map(re.escape, LEXICON), key=len, reverse=True))
                      + r")(?![\w'-])")


def find_terms(text: str) -> list[str]:
    return _TERM_RE.findall(text)


def swap_out(text: str) -> tuple[str, list[str]]:
    found = []

    def sub(m):
        found.append(m[1])
        return f"zqterm{'abcdefghij'[len(found) - 1]}qz"
    return _TERM_RE.sub(sub, text), found


def swap_in(text: str, found: list[str], form: str) -> str:
    for k, term in enumerate(found):
        written = form == "written" or (form == "tts" and term in SEND_WRITTEN)
        value = term if written else LEXICON[term][0]
        text = re.sub(f"zqterm{'abcdefghij'[k]}qz", value, text, flags=re.IGNORECASE)
    return text


def canonical(normalized: str) -> str:
    for written, (spoken, _) in LEXICON.items():
        token = re.sub(r"\W", "", written.lower())
        forms = {re.sub(r"[-\s]+", " ", written.lower()), re.sub(r"[-\s]+", " ", spoken.lower()),
                 re.sub(r"[-\s]+", "", spoken.lower()), token}
        for form in sorted(forms, key=len, reverse=True):
            normalized = re.sub(rf"(?<![\w']){re.escape(form)}(?![\w'])", token, normalized)
    return normalized