-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsonioxservice.cpp
More file actions
335 lines (277 loc) · 10.2 KB
/
sonioxservice.cpp
File metadata and controls
335 lines (277 loc) · 10.2 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#include "sonioxservice.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkProxy>
#include <QNetworkRequest>
#include <QRegularExpression>
#include <QUrl>
#include <QtGlobal>
namespace {
/// Keepalive interval to prevent WebSocket timeout (server timeout is 20s)
constexpr int KEEPALIVE_INTERVAL_MS = 15000;
/// Allowed range for Soniox endpoint detection delay in milliseconds.
constexpr int SONIOX_MIN_ENDPOINT_DELAY_MS = 500;
constexpr int SONIOX_MAX_ENDPOINT_DELAY_MS = 3000;
} // namespace
SonioxService::SonioxService(QObject *parent)
: SpeechService(parent) {
connect(&socket, &QWebSocket::connected, this, &SonioxService::handleConnected);
connect(&socket, &QWebSocket::disconnected, this, &SonioxService::handleDisconnected);
connect(&socket, &QWebSocket::textMessageReceived, this, &SonioxService::handleTextMessage);
connect(&socket, &QWebSocket::errorOccurred, this, &SonioxService::handleSocketError);
keepaliveTimer.setInterval(KEEPALIVE_INTERVAL_MS);
keepaliveTimer.setSingleShot(false);
connect(&keepaliveTimer, &QTimer::timeout, this, &SonioxService::sendKeepalive);
}
QString SonioxService::providerId() const {
return QStringLiteral("soniox");
}
void SonioxService::start(const AppConfig &config, const AudioSpec &spec) {
start(config, spec, 0);
}
void SonioxService::start(const AppConfig &config, const AudioSpec &spec, int sessionId) {
serviceSessionId = sessionId;
resetState();
stopRequested = false;
currentSettings = config.soniox;
currentSpec = spec;
if (currentSettings.apiKey.trimmed().isEmpty()) {
emit errorOccurred(tr("Soniox API key is missing."));
return;
}
if (currentSpec.sampleRate <= 0 || currentSpec.channels <= 0 || currentSpec.format.isEmpty()) {
emit errorOccurred(tr("Invalid audio format settings."));
return;
}
sessionActive = true;
// If already connected, just signal ready
// Soniox doesn't need start config resent - it's stream-based
if (socket.state() == QAbstractSocket::ConnectedState) {
emit readyForAudio();
return;
}
// If currently connecting, wait
if (socket.state() == QAbstractSocket::ConnectingState) {
return;
}
// Open new connection
stopKeepaliveTimer();
if (socket.state() != QAbstractSocket::UnconnectedState) {
socket.abort();
}
QString endpoint = currentSettings.endpoint.trimmed();
if (endpoint.isEmpty())
endpoint = QStringLiteral("wss://stt-rt.soniox.com/transcribe-websocket");
QUrl url(endpoint);
if (url.scheme().isEmpty())
url = QUrl(QStringLiteral("wss://") + endpoint);
if (!url.isValid()) {
emit errorOccurred(tr("Invalid Soniox API endpoint."));
return;
}
if (!applyProxy(currentSettings.proxy))
return;
QNetworkRequest request(url);
socket.open(request);
}
void SonioxService::stop() {
stopRequested = true;
sessionActive = false;
// Don't close the socket - keep it alive for next session
}
void SonioxService::sendAudio(const QByteArray &data) {
if (!sessionActive || socket.state() != QAbstractSocket::ConnectedState || data.isEmpty())
return;
socket.sendBinaryMessage(data);
// Reset keepalive timer when audio is sent
if (keepaliveTimer.isActive()) {
keepaliveTimer.stop();
keepaliveTimer.start();
}
}
void SonioxService::sendEou() {
if (!sessionActive || socket.state() != QAbstractSocket::ConnectedState)
return;
const QJsonObject finalize{{"type", QStringLiteral("finalize")}};
const QJsonDocument doc(finalize);
socket.sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
}
bool SonioxService::isActive() const {
return sessionActive && socket.state() == QAbstractSocket::ConnectedState;
}
void SonioxService::disconnect() {
sessionActive = false;
stopKeepaliveTimer();
if (socket.state() == QAbstractSocket::ConnectedState) {
socket.sendTextMessage(QString());
}
if (socket.state() != QAbstractSocket::UnconnectedState) {
socket.abort();
}
}
void SonioxService::handleConnected() {
const QJsonObject payload = buildStartConfig(currentSettings, currentSpec);
const QJsonDocument doc(payload);
socket.sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
startKeepaliveTimer();
emit readyForAudio();
}
void SonioxService::handleDisconnected() {
stopKeepaliveTimer();
if (sessionActive) {
sessionActive = false;
emit errorOccurred(tr("Connection lost."));
}
}
void SonioxService::handleTextMessage(const QString &message) {
QJsonParseError parseError{};
const QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &parseError);
if (parseError.error != QJsonParseError::NoError || !doc.isObject()) {
return;
}
const QJsonObject root = doc.object();
// Check for error response
if (root.contains("error_code")) {
const QString error = root.value("error_message").toString(tr("Soniox error."));
emit errorOccurred(error);
return;
}
// Check for finished response
if (root.value("finished").toBool(false)) {
// Server is about to close connection
if (!stopRequested) {
// Unexpected finish - emit final text if any
const QString finalText = committedText + currentText;
if (!finalText.isEmpty()) {
emit transcriptUpdated(finalText);
}
}
socket.close();
return;
}
// Process tokens
if (root.contains("tokens")) {
const QJsonArray tokens = root.value("tokens").toArray();
QString finalPhrase;
QString nonFinalPhrase;
for (const auto &entry : tokens) {
const QJsonObject token = entry.toObject();
const QString text = token.value("text").toString();
const bool isFinal = token.value("is_final").toBool(false);
// Skip special markers (legacy format support)
if (text == QStringLiteral("<fin>") || text == QStringLiteral("<end>"))
continue;
if (!text.isEmpty()) {
if (isFinal) {
finalPhrase += text;
} else {
nonFinalPhrase += text;
}
}
}
// IMPORTANT: Accumulate final tokens, don't replace!
if (!finalPhrase.isEmpty()) {
committedText += finalPhrase;
}
// Update current (non-final) text
currentText = nonFinalPhrase;
// Emit combined result
const QString fullText = committedText + currentText;
if (!fullText.isEmpty()) {
emit transcriptUpdated(fullText);
}
}
}
void SonioxService::handleSocketError(QAbstractSocket::SocketError) {
emit errorOccurred(socket.errorString());
}
void SonioxService::resetState() {
committedText.clear();
currentText.clear();
stopRequested = false;
sessionActive = false;
}
void SonioxService::startKeepaliveTimer() {
keepaliveTimer.start();
}
void SonioxService::stopKeepaliveTimer() {
keepaliveTimer.stop();
}
void SonioxService::sendKeepalive() {
if (socket.state() != QAbstractSocket::ConnectedState)
return;
const QJsonObject keepalive{{"type", "keepalive"}};
const QJsonDocument doc(keepalive);
socket.sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
}
bool SonioxService::applyProxy(const QString &proxyString) {
const QString trimmed = proxyString.trimmed();
if (trimmed.isEmpty()) {
socket.setProxy(QNetworkProxy::NoProxy);
return true;
}
QUrl url(trimmed);
if (url.scheme().isEmpty())
url = QUrl(QStringLiteral("http://") + trimmed);
QNetworkProxy proxy;
if (url.scheme().startsWith("socks", Qt::CaseInsensitive))
proxy.setType(QNetworkProxy::Socks5Proxy);
else
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(url.host());
proxy.setPort(static_cast<quint16>(url.port(443)));
proxy.setUser(url.userName());
proxy.setPassword(url.password());
if (proxy.hostName().isEmpty() || proxy.port() == 0) {
emit errorOccurred(tr("Invalid proxy address."));
socket.setProxy(QNetworkProxy::NoProxy);
return false;
}
socket.setProxy(proxy);
return true;
}
QJsonObject SonioxService::buildStartConfig(const SonioxSettings &settings,
const AudioSpec &spec) const {
QJsonObject payload{
{"api_key", settings.apiKey},
{"audio_format", spec.format},
{"sample_rate", spec.sampleRate},
{"num_channels", spec.channels}
};
const QString model = settings.model.trimmed();
if (!model.isEmpty())
payload.insert("model", model);
if (settings.endpointDetection)
payload.insert("enable_endpoint_detection", true);
if (settings.endpointDetection && settings.useMaxEndpointDelay) {
const int endpointDelayMs = qBound(SONIOX_MIN_ENDPOINT_DELAY_MS,
settings.maxEndpointDelayMs,
SONIOX_MAX_ENDPOINT_DELAY_MS);
payload.insert("max_endpoint_delay_ms", endpointDelayMs);
}
const QStringList hints = parseLanguageHints(settings.languageHints);
if (!hints.isEmpty()) {
QJsonArray hintArray;
for (const auto &hint : hints)
hintArray.append(hint);
payload.insert("language_hints", hintArray);
if (settings.languageHintsStrict)
payload.insert("language_hints_strict", true);
}
const QString context = settings.context.trimmed();
if (!context.isEmpty())
payload.insert("context", context);
return payload;
}
QStringList SonioxService::parseLanguageHints(const QString &value) const {
QStringList result;
const QStringList parts = value.split(QRegularExpression("[,;]"),
Qt::SkipEmptyParts);
for (const auto &raw : parts) {
const QString hint = raw.trimmed();
if (!hint.isEmpty())
result.append(hint);
}
return result;
}