File size: 10,491 Bytes
7dc7029
 
 
 
 
 
 
525a9b4
7dc7029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83a30c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc7029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525a9b4
 
 
 
 
 
 
 
 
 
 
 
83a30c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc7029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6fc9f
 
7dc7029
 
 
9a6fc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc7029
 
 
 
 
 
 
 
 
 
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
"""Meetings that switch language: planning by time, and routing each part to its model."""
import unittest
from types import SimpleNamespace

import numpy as np

from src.transcription.language_runs import (
    Run, Window, build_runs, candidates_for, drop_repeats, label_windows, pieces, scoring_codes,
)


def sc(**v):
    return dict(v)


class PlanTests(unittest.TestCase):
    def test_candidates(self):
        auto = ("en", "yo", "ha", "fr")
        self.assertEqual(candidates_for([], auto), (list(auto), None))
        self.assertEqual(candidates_for(["yo"], auto), (["yo", "en"], None))
        self.assertEqual(candidates_for(["en"], auto), (["en"], None))
        self.assertEqual(candidates_for(["ig"], auto), (["ig", "en"], "ig"))
        self.assertEqual(candidates_for(["yo", "ha"], auto), (["yo", "ha"], None))
        self.assertEqual(scoring_codes(["ig", "en"], "ig"), ["en", "yo", "ha", "sw", "fr"])

    def test_one_doubtful_window_does_not_split(self):
        ws = [Window(0, 10), Window(10, 15), Window(15, 25)]
        label_windows(ws, [sc(yo=-0.1, en=-5), sc(yo=-1.2, en=-0.6), sc(yo=-0.1, en=-5)], ["yo", "en"], "yo")
        self.assertEqual([w.language for w in ws], ["yo", "yo", "yo"])

    def test_real_yoruba_english_meeting(self):
        """Window scores from a real recording: FLEURS Yoruba speakers and
        AfriSpeech Yoruba-accented English (EN, YO, EN, YO, EN)."""
        data = [(0.0, 7.3, -0.44, -4.27, {'en': -0.44, 'sw': -1.3, 'yo': -4.27}), (9.9, 13.0, -3.28, -1.33, {'yo': -1.33, 'fr': -2.75, 'tr': -2.84}), (14.3, 15.4, -0.45, -4.25, {'en': -0.45, 'fr': -3.52, 'yo': -4.25}), (16.2, 21.3, -5.81, -0.08, {'yo': -0.08, 'en': -5.81, 'sw': -6.89}), (24.1, 24.7, -3.58, -8.4, {'en': -3.58, 'ko': -3.8, 'id': -4.03}), (30.2, 44.7, -5.99, -0.02, {'yo': -0.02, 'en': -5.99, 'tr': -9.14}), (44.8, 45.3, -1.37, -7.81, {'en': -1.37, 'pt': -1.79, 'es': -2.56}), (50.2, 59.2, -5.97, -0.03, {'yo': -0.03, 'en': -5.97, 'sw': -6.69}), (61.3, 67.0, -0.55, -1.04, {'en': -0.55, 'yo': -1.04, 'sw': -3.49}), (67.7, 71.6, -2.12, -6.71, {'sw': -1.93, 'en': -2.12, 'pt': -4.95}), (72.2, 77.7, -3.25, -0.07, {'yo': -0.07, 'en': -3.25, 'sw': -5.95}), (79.7, 88.4, -8.32, -0.05, {'yo': -0.05, 'sw': -7.03, 'en': -8.32}), (90.8, 96.8, -5.22, -0.08, {'yo': -0.08, 'sw': -3.95, 'en': -5.22}), (98.9, 103.5, -6.42, -0.12, {'yo': -0.12, 'fr': -5.55, 'en': -6.42}), (104.2, 106.0, -3.68, -2.97, {'pt': -1.66, 'fr': -2.81, 'es': -2.96}), (108.0, 117.5, -0.04, -3.56, {'en': -0.04, 'yo': -3.56, 'sw': -6.91})]
        ws = [Window(s, e) for s, e, *_ in data]
        scores = [(dict(top, en=en, yo=yo) if e - s >= 2.0 else None) for s, e, en, yo, top in data]
        cands = ["en", "yo", "ha", "fr", "sw", "pt", "es", "tr", "ko", "id"]
        label_windows(ws, scores, cands, "yo", {"en": 1.0, "yo": 1.0, "ha": 0.5})
        runs = build_runs(ws, "yo")
        self.assertEqual([r.language for r in runs], ["en", "yo", "en", "yo", "en"])
        # Only the languages actually spoken; no stray Swahili or Portuguese.
        self.assertEqual({w.language for w in ws}, {"en", "yo"})
        self.assertLess(runs[0].end, 9)                 # first English ends ~7 s
        self.assertTrue(60 <= runs[2].start <= 62)      # middle English starts ~61 s

    def test_short_windows_inherit_and_short_runs_absorbed(self):
        ws = [Window(0, 20), Window(20, 21), Window(21, 24), Window(24, 60)]
        label_windows(ws, [sc(yo=5, en=1), None, sc(yo=0, en=9), sc(yo=5, en=1)], ["yo", "en"], "yo")
        self.assertEqual([w.language for w in ws], ["yo", "yo", "en", "yo"])
        runs = build_runs(ws, "yo")
        # A 3 s English detour inside Yoruba is not worth splitting.
        self.assertEqual([(r.language, r.start, r.end) for r in runs], [("yo", 0, 60)])

    def test_real_switch_becomes_runs(self):
        ws = [Window(0, 15), Window(15, 30), Window(30, 45), Window(45, 60)]
        label_windows(ws, [sc(en=9, yo=1), sc(en=9, yo=1), sc(en=1, yo=9), sc(en=1, yo=9)], ["en", "yo"], "en")
        runs = build_runs(ws, "en")
        self.assertEqual([(r.language, r.start, r.end) for r in runs], [("en", 0, 30), ("yo", 30, 60)])

    def test_igbo_is_whatever_english_does_not_clearly_win(self):
        ws = [Window(0, 10), Window(10, 20)]
        label_windows(ws, [sc(en=9, yo=2, ha=1), sc(en=3, yo=4, ha=2)], ["ig", "en"], "ig", implied="ig")
        self.assertEqual([w.language for w in ws], ["en", "ig"])


class PieceTests(unittest.TestCase):
    def test_real_yoruba_windows(self):
        # From a real FLEURS Yoruba recording: a 0.6 s fragment after a long
        # sentence, then 5 s of silence, then the last sentence.
        ws = [Window(*w) for w in [(1.8, 5.3), (6.3, 7.6), (8.2, 13.5), (16.2, 17.0), (22.3, 36.9), (36.9, 37.5), (42.3, 51.3)]]
        self.assertEqual(pieces(ws, 0, 53), [(1.8, 7.6), (8.2, 13.5), (16.2, 17.0), (22.3, 37.5), (42.3, 51.3)])

    def test_mixed_meeting_windows(self):
        ws = [Window(*w) for w in [(72.2, 77.7), (79.7, 88.4), (90.8, 96.8), (98.9, 103.5), (104.2, 106.0)]]
        self.assertEqual(pieces(ws, 72, 106), [(72.2, 77.7), (79.7, 88.4), (90.8, 96.8), (98.9, 106.0)])


class RepeatTests(unittest.TestCase):
    def test_looped_sentence_is_merged(self):
        segs = [
            {"start": 107.9, "end": 113.7, "text": "Admiral de Barras violated his orders to operate off Newfoundland, making possible"},
            {"start": 113.7, "end": 117.5, "text": "Admiral de Barras violated his orders to operate off Newfoundland, making possible the timely delivery of the"},
            {"start": 118.0, "end": 120.0, "text": "Thank you all."},
        ]
        out = drop_repeats(segs)
        self.assertEqual(len(out), 2)
        self.assertTrue(out[0]["text"].endswith("timely delivery of the"))
        self.assertEqual((out[0]["start"], out[0]["end"]), (107.9, 117.5))

    def test_different_sentences_untouched(self):
        segs = [{"start": 0, "end": 2, "text": "Good morning everyone."}, {"start": 2, "end": 4, "text": "Good morning, Tunde."}]
        self.assertEqual(len(drop_repeats(segs)), 2)


class FakePipe:
    def __init__(self, key):
        self.key = key
        self.calls = []

    def _initialize_pipeline(self):
        pass

    def language_scores(self, clips, codes, sr=16000):
        # Loud clips are "English", quiet ones "Yoruba".
        out = []
        for c in clips:
            en = float(np.abs(c).mean()) > 0.5
            out.append({k: (9.0 if (k == "en") == en else 1.0) for k in codes})
        return out

    def transcribe(self, audio, **kw):
        self.calls.append((len(audio), kw.get("language")))
        text = f"{self.key}:{kw.get('language')}"
        return SimpleNamespace(text=text, segments=[{"start": 0.5, "end": 1.5, "text": text}])


class EngineMixedTests(unittest.TestCase):
    def make_engine(self):
        from src.transcription import engine as eng
        e = eng.TranscriptionEngine.__new__(eng.TranscriptionEngine)
        e.config = {"models": {"default": "whisper-large-v3"}}
        e.current_model_key = "ncair-yoruba"
        pipes = {}
        avail = {"whisper-large-v3": {}, "ncair-yoruba": {}, "ncair-igbo": {}, "ncair-hausa": {}}
        e.registry = SimpleNamespace(list_available_models=lambda: avail)

        def set_model(k):
            e.current_model_key = k
        e.set_model = set_model
        e._get_pipeline = lambda: pipes.setdefault(e.current_model_key, FakePipe(e.current_model_key))
        return e, pipes, eng

    def test_yoruba_meeting_with_english_part(self):
        e, pipes, eng = self.make_engine()
        sr = 16000
        # 0-20 s quiet speech ("Yoruba"), 20-40 s loud ("English"), short pauses between.
        audio = np.concatenate([np.full(sr * 20, 0.2), np.zeros(sr // 2), np.full(sr * 20, 0.9)]).astype(np.float32)
        noise = np.random.default_rng(0).normal(0, 0.05, len(audio)).astype(np.float32)
        audio = audio * np.sign(noise + 1e-9)  # make it look like audio, keep loudness
        plan = e._language_plan(audio, sr, ["yo"], len(audio) / sr)
        self.assertEqual([r.language for r in plan], ["yo", "en"])
        result = e._transcribe_mixed(audio, sr, plan, "ncair-yoruba", {"language": "yo"}, None)
        self.assertEqual(result.languages, ["yo", "en"])
        langs = [s["language"] for s in result.segments]
        self.assertEqual([l for i, l in enumerate(langs) if i == 0 or langs[i - 1] != l], ["yo", "en"])
        # Yoruba part on the Yoruba model (no forced token), English on large-v3 with "en".
        self.assertEqual(pipes["ncair-yoruba"].calls[0][1], "yo")
        self.assertEqual(pipes["whisper-large-v3"].calls[0][1], "en")
        starts = [s["start"] for s in result.segments]
        self.assertEqual(starts, sorted(starts))
        first_en = next(s for s in result.segments if s["language"] == "en")
        self.assertGreaterEqual(first_en["start"], 19.0)

    def test_native_model_gets_sentence_pieces_with_clamped_times(self):
        e, pipes, eng = self.make_engine()
        sr = 16000
        speech = lambda sec: np.random.default_rng(1).normal(0, 0.3, sr * sec).astype(np.float32)
        audio = np.concatenate([speech(12), np.zeros(sr), speech(14), np.zeros(sr), speech(9)])

        class LongStamp(FakePipe):
            def transcribe(self, audio, **kw):
                self.calls.append((len(audio), kw.get("language")))
                # Dedicated models often claim a segment far past the audio.
                return SimpleNamespace(text="x", segments=[{"start": 0.2, "end": 999.0, "text": f"piece{len(self.calls)}"}])
        pipes["ncair-yoruba"] = LongStamp("ncair-yoruba")
        meta = SimpleNamespace(duration=len(audio) / sr)
        r = e._transcribe_native(audio, sr, meta, {"language": "yo"}, None, 0.0)
        self.assertEqual([s["text"] for s in r.segments], ["piece1", "piece2", "piece3"])
        for seg in r.segments:
            self.assertLess(seg["end"], len(audio) / sr + 0.2)
        # Pieces end where the speech ends, not at 999 s.
        self.assertTrue(r.segments[0]["end"] < 13.5 and 12.5 < r.segments[1]["start"] < 14)

    def test_english_only_skips_detection(self):
        e, pipes, eng = self.make_engine()
        plan = e._language_plan(np.zeros(16000 * 30, dtype=np.float32), 16000, ["en"], 30.0)
        self.assertEqual([(r.language) for r in plan], ["en"])
        self.assertNotIn("whisper-large-v3", pipes)


if __name__ == "__main__":
    unittest.main()