File size: 6,232 Bytes
f4ac846
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Domain vocabulary correction for the voice coach's speech-to-text.



The bundled offline Whisper model (``sherpa-onnx-whisper-base``) is a general

multilingual model: it repeatedly mis-hears Indonesian finance/crypto terms

("Bitcoin" -> "betoin", "Ethereum" -> "ekterum", "Bank Mandiri" -> "bang

mandiri", "bullish" -> "prem bulis"). Adding a bigger model costs a lot of RAM

and load time for only a marginal accuracy gain, so we keep the small model and

repair the handful of domain terms on the transcript before it reaches the

LLM/caption/persistence layers.



Kept free of LiveKit/sherpa imports so the rules can be unit-tested without the

agent SDK installed.

"""

from __future__ import annotations

import difflib
import re

# Canonical spelling -> forms the model is known/likely to emit. Variants are
# matched case-insensitively on word boundaries; spaces/hyphens are treated as
# equivalent so "b-coin" and "b coin" both match. Keep variants specific enough
# to avoid clobbering ordinary Indonesian words (e.g. never map bare "bank").
_DOMAIN_TERMS: tuple[tuple[str, tuple[str, ...]], ...] = (
    (
        "Bitcoin",
        (
            "bitcoin",
            "bit coin",
            "b coin",
            "bcoin",
            "betoin",
            "becoin",
            "bitkon",
            "bitkoin",
        ),
    ),
    (
        "Ethereum",
        (
            "ethereum",
            "etherium",
            "eterium",
            "etherum",
            "ekterum",
            "eterom",
            "etero",
        ),
    ),
    ("Dogecoin", ("dogecoin", "doge coin", "dogecoin")),
    ("Litecoin", ("litecoin", "lite coin")),
    ("Cardano", ("cardano", "kardano")),
    ("Solana", ("solana", "solano")),
    ("Ripple", ("ripple", "riple")),
    ("Binance", ("binance", "binace", "binans")),
    ("Coinbase", ("coinbase", "coin base")),
    ("altcoin", ("altcoin", "alt coin", "alcoin")),
    (
        "bullish",
        (
            "bullish",
            "bullis",
            "bulish",
            "bulis",
            "bullsi",
            "boolish",
            "bules",
            "prem bulis",
            "prembulis",
        ),
    ),
    ("bearish", ("bearish", "bearis", "berish", "beris", "bearist")),
    (
        "stop loss",
        ("stop loss", "stoploss", "stoplos", "stop los", "stoplos"),
    ),
    ("take profit", ("take profit", "takeprofit", "take provit")),
    ("support", ("support", "suport", "saport")),
    ("resistance", ("resistance", "resistansi", "resistensi", "resistens", "resisten")),
    ("breakout", ("breakout", "break out", "brekout")),
    ("breakdown", ("breakdown", "break down", "brekdown")),
    ("candlestick", ("candlestick", "candle stick", "candlestik")),
    ("Bank Mandiri", ("bank mandiri", "bang mandiri", "bangmandiri", "bangman diri")),
)


def _variant_regex(variant: str) -> str:
    """Turn a variant into a regex matching it with flexible separators."""
    tokens = [re.escape(tok) for tok in re.split(r"[\s-]+", variant.strip()) if tok]
    return r"[\s-]+".join(tokens)


def _build_patterns() -> tuple[tuple[re.Pattern[str], str], ...]:
    """Compile one boundary-anchored pattern per variant, longest first.



    Longest-first means multi-word phrases (``prem bulis``) are corrected before

    any single-word rule could touch a part of them.

    """
    items = [
        (len(variant), variant, canonical)
        for canonical, variants in _DOMAIN_TERMS
        for variant in variants
    ]
    items.sort(key=lambda item: item[0], reverse=True)
    compiled: list[tuple[re.Pattern[str], str]] = []
    for _, variant, canonical in items:
        core = _variant_regex(variant)
        # Alphanumeric lookarounds (instead of \b) also work for tokens that end
        # in punctuation-free letters and keep us from matching inside a larger
        # word such as "berisik" or "suportif".
        pattern = re.compile(
            rf"(?<![A-Za-z0-9]){core}(?![A-Za-z0-9])", re.IGNORECASE
        )
        compiled.append((pattern, canonical))
    return tuple(compiled)


_PATTERNS = _build_patterns()

# Proper-noun crypto names get a second, *fuzzy* pass so we don't have to
# enumerate every spelling Whisper invents ("Bicoin", "bitcon", "ekterum").
# Thresholds were calibrated so ordinary Indonesian words never match: e.g.
# "cardio" (0.769 vs Cardano), "sopan" (0.727 vs Solana) and "bikin" (0.667 vs
# Bitcoin) all fall below the cutoff, and 4-letter tokens like "sana" are
# skipped outright.
_FUZZY_VOCAB = (
    "Bitcoin",
    "Ethereum",
    "Dogecoin",
    "Litecoin",
    "Ripple",
    "Cardano",
    "Solana",
    "Binance",
    "Coinbase",
    "Tether",
    "Polkadot",
)
_FUZZY_MIN_LEN = 6
_FUZZY_CUTOFF = 0.80
_TOKEN_RE = re.compile(r"[A-Za-z]+")


def _fuzzy_fix(text: str) -> str:
    """Replace near-miss crypto names with their canonical spelling."""

    def repl(match: re.Match[str]) -> str:
        token = match.group(0)
        if len(token) < _FUZZY_MIN_LEN:
            return token
        low = token.lower()
        best: str | None = None
        best_ratio = 0.0
        for canonical in _FUZZY_VOCAB:
            # Same first letter: keeps "berisik"/"bulan" far from crypto names.
            if canonical[0].lower() != low[0]:
                continue
            ratio = difflib.SequenceMatcher(None, low, canonical.lower()).ratio()
            if ratio > best_ratio:
                best, best_ratio = canonical, ratio
        if best is not None and best_ratio >= _FUZZY_CUTOFF:
            return best
        return token

    return _TOKEN_RE.sub(repl, text)


def correct_domain_terms(text: str) -> str:
    """Repair known finance/crypto mis-hearings in a transcript.



    Applies the explicit variant table first, then a conservative fuzzy pass for

    crypto proper nouns. Idempotent: applying it to already-correct text leaves

    it unchanged.

    """
    if not text:
        return text
    for pattern, canonical in _PATTERNS:
        text = pattern.sub(canonical, text)
    return _fuzzy_fix(text)