aboutsummaryrefslogtreecommitdiffstats
path: root/openai_realtime.py
blob: 56ba849ba8edd47f1b11603d35f39c705be72404 (plain) (blame)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import base64
import json
import queue
import re
import threading
import time
from typing import Any, Callable, List, Optional, Tuple

import numpy as np
import websocket


AddRuntimeLogFn = Callable[[str, str], None]
BroadcastSubtitleFn = Callable[[str], None]
ResampleAudioFn = Callable[[np.ndarray, int, int], np.ndarray]


class OpenAIRealtimeTranslator:
    def __init__(
        self,
        *,
        api_key: str,
        model: str,
        output_language: str,
        safety_identifier: str,
        add_runtime_log: AddRuntimeLogFn,
        broadcast_subtitle: BroadcastSubtitleFn,
        resample_audio: ResampleAudioFn,
        target_sample_rate: int = 24000,
        reconnect_seconds: float = 2.0,
        buffer_stale_seconds: float = 1.1,
        ws_url_template: str = "wss://api.openai.com/v1/realtime/translations?model={model}",
        queue_maxsize: int = 200,
    ) -> None:
        self.api_key = api_key
        self.model = model
        self.output_language = output_language
        self.safety_identifier = safety_identifier

        self.target_sample_rate = target_sample_rate
        self.reconnect_seconds = reconnect_seconds
        self.buffer_stale_seconds = buffer_stale_seconds
        self.ws_url_template = ws_url_template

        self._add_runtime_log = add_runtime_log
        self._broadcast_subtitle = broadcast_subtitle
        self._resample_audio = resample_audio

        self._audio_queue: queue.Queue = queue.Queue(maxsize=queue_maxsize)
        self._stop_sentinel: object = object()
        self._stop_event: threading.Event = threading.Event()
        self._transcript_buffer: str = ""
        self._last_delta_monotonic: float = 0.0
        self._transcript_lock: threading.Lock = threading.Lock()
        self._thread: Optional[threading.Thread] = None

    @staticmethod
    def _float_audio_to_pcm16_base64(audio_np: np.ndarray) -> str:
        if len(audio_np) == 0:
            return ""
        clipped = np.clip(audio_np, -1.0, 1.0)
        pcm16 = (clipped * 32767.0).astype(np.int16)
        return base64.b64encode(pcm16.tobytes()).decode("ascii")

    @staticmethod
    def _normalize_subtitle_chunk(text: str) -> str:
        return re.sub(r"\s+", " ", text).strip()

    def _extract_completed_sentences(self, buffer: str) -> Tuple[List[str], str]:
        completed: List[str] = []
        remaining = buffer

        while True:
            match = re.search(r"(.+?[.!?])(?=\s|$)", remaining, flags=re.DOTALL)
            if not match:
                break
            sentence = self._normalize_subtitle_chunk(match.group(1))
            if sentence:
                completed.append(sentence)
            remaining = remaining[match.end() :].lstrip()

        if "\n" in remaining:
            parts = [part.strip() for part in remaining.split("\n")]
            for part in parts[:-1]:
                normalized_part = self._normalize_subtitle_chunk(part)
                if normalized_part:
                    completed.append(normalized_part)
            remaining = parts[-1] if parts else ""

        return completed, remaining

    @staticmethod
    def _clear_queue(target_queue: queue.Queue) -> None:
        while True:
            try:
                target_queue.get_nowait()
            except queue.Empty:
                break

    def _flush_transcript_buffer(self, force: bool = False) -> None:
        with self._transcript_lock:
            text = self._normalize_subtitle_chunk(self._transcript_buffer)
            if not text:
                self._transcript_buffer = ""
                return
            if not force and len(text) < 2:
                return
            self._transcript_buffer = ""

        self._add_runtime_log("FINAL", text)
        self._broadcast_subtitle(text)

    def _flush_transcript_buffer_if_stale(self) -> None:
        with self._transcript_lock:
            if not self._transcript_buffer:
                return
            elapsed = time.monotonic() - self._last_delta_monotonic
            if elapsed < self.buffer_stale_seconds:
                return
        self._flush_transcript_buffer(force=True)

    def _handle_transcript_delta(self, delta: str) -> None:
        if not delta:
            return

        delta = delta.replace("\r", "")

        with self._transcript_lock:
            self._last_delta_monotonic = time.monotonic()
            self._transcript_buffer += delta
            completed, remaining = self._extract_completed_sentences(self._transcript_buffer)

            if len(remaining) > 180:
                split_idx = remaining.rfind(" ")
                if split_idx > 80:
                    overflow = self._normalize_subtitle_chunk(remaining[:split_idx])
                    if overflow:
                        completed.append(overflow)
                    remaining = remaining[split_idx:].lstrip()

            self._transcript_buffer = remaining

        for sentence in completed:
            self._add_runtime_log("FINAL", sentence)
            self._broadcast_subtitle(sentence)

    def _audio_sender_loop(self, ws: websocket.WebSocket) -> None:
        while not self._stop_event.is_set():
            try:
                item = self._audio_queue.get(timeout=0.2)
            except queue.Empty:
                continue

            if item is self._stop_sentinel:
                break
            if not isinstance(item, str) or not item:
                continue

            payload = {
                "type": "session.input_audio_buffer.append",
                "audio": item,
            }
            try:
                ws.send(json.dumps(payload))
            except Exception:
                break

    def _run_loop(self) -> None:
        ws_url = self.ws_url_template.format(model=self.model)

        while not self._stop_event.is_set():
            ws: Any = None
            sender_thread: Optional[threading.Thread] = None

            try:
                headers: List[str] = [f"Authorization: Bearer {self.api_key}"]
                if self.safety_identifier:
                    headers.append(f"OpenAI-Safety-Identifier: {self.safety_identifier}")

                ws = websocket.WebSocket()
                ws.connect(ws_url, header=headers)
                ws.settimeout(0.6)

                session_update = {
                    "type": "session.update",
                    "session": {
                        "audio": {
                            "output": {
                                "language": self.output_language,
                            },
                        },
                    },
                }
                ws.send(json.dumps(session_update))
                self._add_runtime_log(
                    "OPENAI",
                    f"Connected to realtime translation (lang={self.output_language}, model={self.model})",
                )

                sender_thread = threading.Thread(target=self._audio_sender_loop, args=(ws,), daemon=True)
                sender_thread.start()

                while not self._stop_event.is_set():
                    try:
                        incoming = ws.recv()
                    except websocket.WebSocketTimeoutException:
                        self._flush_transcript_buffer_if_stale()
                        continue

                    if incoming is None:
                        break
                    incoming = incoming.strip()
                    if not incoming:
                        continue

                    try:
                        event = json.loads(incoming)
                    except json.JSONDecodeError:
                        self._add_runtime_log("OPENAI", "Received non-JSON event from realtime translation socket")
                        continue

                    event_type = str(event.get("type", ""))
                    if event_type == "session.output_transcript.delta":
                        delta = str(event.get("delta", ""))
                        self._handle_transcript_delta(delta)
                    elif event_type in {"session.output_transcript.done", "session.output_transcript.completed"}:
                        self._flush_transcript_buffer(force=True)
                    elif event_type in {"error", "session.error"}:
                        self._add_runtime_log("OPENAI", f"Realtime API error: {json.dumps(event, ensure_ascii=False)}")
                    elif event_type == "session.updated":
                        self._add_runtime_log("OPENAI", "Realtime session configured")

            except Exception as exc:
                if self._stop_event.is_set():
                    break
                self._add_runtime_log("OPENAI", f"Realtime connection failed: {exc}")
                time.sleep(self.reconnect_seconds)
            finally:
                if ws is not None:
                    try:
                        ws.close()
                    except Exception:
                        pass
                self._flush_transcript_buffer(force=True)
                if sender_thread is not None and sender_thread.is_alive():
                    sender_thread.join(timeout=1.0)

    def start(self) -> None:
        if self._thread is not None and self._thread.is_alive():
            return

        self._clear_queue(self._audio_queue)
        self._stop_event.clear()
        with self._transcript_lock:
            self._transcript_buffer = ""
            self._last_delta_monotonic = 0.0

        self._thread = threading.Thread(target=self._run_loop, daemon=True)
        self._thread.start()

    def stop(self) -> None:
        self._stop_event.set()
        try:
            self._audio_queue.put_nowait(self._stop_sentinel)
        except queue.Full:
            self._clear_queue(self._audio_queue)
            try:
                self._audio_queue.put_nowait(self._stop_sentinel)
            except queue.Full:
                pass

        if self._thread is not None and self._thread.is_alive():
            self._thread.join(timeout=2.0)

    def enqueue_audio_chunk(self, chunk: np.ndarray, capture_sample_rate: int) -> None:
        if capture_sample_rate <= 0 or len(chunk) == 0:
            return

        resampled = self._resample_audio(chunk, capture_sample_rate, self.target_sample_rate)
        encoded = self._float_audio_to_pcm16_base64(resampled)
        if not encoded:
            return

        try:
            self._audio_queue.put_nowait(encoded)
        except queue.Full:
            try:
                self._audio_queue.get_nowait()
            except queue.Empty:
                pass
            try:
                self._audio_queue.put_nowait(encoded)
            except queue.Full:
                pass
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage