trading-analyst / transcript_fix.py
ojaq's picture
Deploy Tradiora Analyst from local project
f4ac846 verified
Raw History Blame Contribute Delete
6.23 kB
"""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)