-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazurespeechservice.cpp
More file actions
772 lines (676 loc) · 28.4 KB
/
azurespeechservice.cpp
File metadata and controls
772 lines (676 loc) · 28.4 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
#include "azurespeechservice.h"
#include <QDateTime>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkProxy>
#include <QNetworkRequest>
#include <QRegularExpression>
#include <QUrl>
#include <QUrlQuery>
#include <QUuid>
#include <QtGlobal>
#include <cstring>
namespace {
QStringList splitList(const QString &value) {
QStringList result;
const QStringList parts = value.split(QRegularExpression("[,;]"),
Qt::SkipEmptyParts);
for (const auto &raw : parts) {
const QString item = raw.trimmed();
if (!item.isEmpty())
result.append(item);
}
return result;
}
} // namespace
AzureSpeechService::AzureSpeechService(QObject *parent)
: SpeechService(parent) {
connect(&socket, &QWebSocket::connected, this, &AzureSpeechService::handleConnected);
connect(&socket, &QWebSocket::disconnected, this, &AzureSpeechService::handleDisconnected);
connect(&socket, &QWebSocket::textMessageReceived, this, &AzureSpeechService::handleTextMessage);
connect(&socket, &QWebSocket::errorOccurred, this, &AzureSpeechService::handleSocketError);
}
QString AzureSpeechService::providerId() const {
return QStringLiteral("azure");
}
void AzureSpeechService::start(const AppConfig &config, const AudioSpec &spec) {
start(config, spec, 0);
}
void AzureSpeechService::start(const AppConfig &config, const AudioSpec &spec, int sessionId) {
serviceSessionId = sessionId;
resetState();
stopRequested = false;
currentSettings = config.azure;
currentSpec = spec;
if (currentSettings.apiKey.trimmed().isEmpty()) {
emit errorOccurred(tr("Azure API key is missing."));
return;
}
if (currentSpec.sampleRate <= 0 || currentSpec.channels <= 0 || currentSpec.format.isEmpty()) {
emit errorOccurred(tr("Invalid audio format settings."));
return;
}
QString headerError;
bool littleEndian = true;
SampleType sampleType = SampleType::Signed;
int bitsPerSample = 0;
if (!parsePcmFormat(currentSpec.format, &bitsPerSample, &littleEndian, &sampleType, &headerError)) {
emit errorOccurred(headerError.isEmpty()
? tr("Unsupported audio format for Azure.")
: headerError);
return;
}
if (!littleEndian) {
emit errorOccurred(tr("Only little-endian PCM is supported."));
return;
}
inputBitsPerSample = bitsPerSample;
inputSampleType = sampleType;
needsConversion = !(sampleType == SampleType::Signed && bitsPerSample == 16);
const int wavBitsPerSample = needsConversion ? 16 : bitsPerSample;
if (!buildWavHeader(currentSpec, wavBitsPerSample, &wavHeader, &headerError)) {
emit errorOccurred(headerError.isEmpty()
? tr("Unsupported audio format for Azure.")
: headerError);
return;
}
sessionActive = true;
// Generate new requestId for each session
requestId = QUuid::createUuid().toString(QUuid::WithoutBraces);
requestId.remove(QLatin1Char('-'));
// If already connected, send config and signal ready
if (socket.state() == QAbstractSocket::ConnectedState) {
sendAzureConfig();
emit readyForAudio();
return;
}
// If currently connecting, wait
if (socket.state() == QAbstractSocket::ConnectingState) {
return;
}
// Open new connection
if (socket.state() != QAbstractSocket::UnconnectedState) {
socket.abort();
}
if (!applyProxy(currentSettings.proxy))
return;
connectionId = QUuid::createUuid().toString(QUuid::WithoutBraces);
connectionId.remove(QLatin1Char('-'));
const QUrl url = buildServiceUrl(currentSettings, connectionId);
if (!url.isValid()) {
emit errorOccurred(tr("Invalid Azure API endpoint."));
return;
}
QNetworkRequest request(url);
request.setRawHeader("Ocp-Apim-Subscription-Key", currentSettings.apiKey.toUtf8());
if (!connectionId.isEmpty())
request.setRawHeader("X-ConnectionId", connectionId.toUtf8());
socket.open(request);
}
void AzureSpeechService::stop() {
stopRequested = true;
sessionActive = false;
// Send final audio marker to complete this turn
if (socket.state() == QAbstractSocket::ConnectedState) {
socket.sendBinaryMessage(buildBinaryMessage(QStringLiteral("audio"),
requestId,
QString(),
QByteArray()));
}
// Don't close socket - keep it alive for next session
}
void AzureSpeechService::sendAudio(const QByteArray &data) {
if (!sessionActive || socket.state() != QAbstractSocket::ConnectedState || data.isEmpty())
return;
const QByteArray payload = needsConversion ? convertToPcm16(data) : data;
if (payload.isEmpty())
return;
socket.sendBinaryMessage(buildBinaryMessage(QStringLiteral("audio"),
requestId,
QString(),
payload));
}
bool AzureSpeechService::isActive() const {
return sessionActive && socket.state() == QAbstractSocket::ConnectedState;
}
void AzureSpeechService::disconnect() {
sessionActive = false;
if (socket.state() != QAbstractSocket::UnconnectedState) {
socket.abort();
}
}
void AzureSpeechService::handleConnected() {
sendAzureConfig();
emit readyForAudio();
}
void AzureSpeechService::handleDisconnected() {
if (sessionActive) {
sessionActive = false;
emit errorOccurred(tr("Connection lost."));
}
}
void AzureSpeechService::handleTextMessage(const QString &message) {
QString headerBlock;
QString body;
int separator = message.indexOf(QStringLiteral("\r\n\r\n"));
if (separator >= 0) {
headerBlock = message.left(separator);
body = message.mid(separator + 4);
} else {
separator = message.indexOf(QStringLiteral("\n\n"));
if (separator >= 0) {
headerBlock = message.left(separator);
body = message.mid(separator + 2);
} else {
body = message;
}
}
const QMap<QString, QString> headers = parseHeaders(headerBlock);
const QString path = headers.value(QStringLiteral("path")).toLower();
if (path == QStringLiteral("turn.end")) {
// Don't close socket - keep persistent connection
// Just signal that this dictation session is complete
if (sessionActive) {
emit finished(serviceSessionId);
}
return;
}
if (body.trimmed().isEmpty())
return;
QJsonParseError parseError{};
const QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8(), &parseError);
if (parseError.error != QJsonParseError::NoError || !doc.isObject())
return;
const QJsonObject root = doc.object();
if (path == QStringLiteral("speech.hypothesis") ||
path == QStringLiteral("speech.fragment")) {
const QString text = extractResultText(root);
if (!text.isEmpty()) {
currentText = text;
emitTranscript();
}
return;
}
if (path == QStringLiteral("speech.phrase")) {
const QString errorText = extractErrorText(root);
if (!errorText.isEmpty()) {
emit errorOccurred(errorText);
return;
}
const QString status = root.value(QStringLiteral("RecognitionStatus")).toString();
if (!status.isEmpty()) {
const QString lower = status.toLower();
if (lower == QStringLiteral("nomatch") ||
lower == QStringLiteral("initialsilencetimeout") ||
lower == QStringLiteral("babbletimeout")) {
return;
}
if (lower == QStringLiteral("endofdictation")) {
return;
}
}
const QString text = extractResultText(root);
if (!text.isEmpty()) {
appendCommittedText(text);
currentText.clear();
emitTranscript();
}
}
}
void AzureSpeechService::handleSocketError(QAbstractSocket::SocketError error) {
Q_UNUSED(error);
emit errorOccurred(socket.errorString());
}
void AzureSpeechService::sendAzureConfig() {
QJsonObject system{
{"name", QStringLiteral("VoiceToKeys")},
{"version", QStringLiteral("1.0")},
{"build", QStringLiteral("Qt")},
{"lang", QStringLiteral("C++")}
};
QJsonObject configRoot{
{"context", QJsonObject{{"system", system}}},
{"recognition", QStringLiteral("conversation")}
};
const QJsonDocument configDoc(configRoot);
socket.sendTextMessage(buildTextMessage(QStringLiteral("speech.config"),
requestId,
QStringLiteral("application/json"),
QString::fromUtf8(configDoc.toJson(QJsonDocument::Compact))));
QJsonObject contextRoot;
const QStringList phraseHints = splitList(currentSettings.phraseHints);
if (!phraseHints.isEmpty()) {
QJsonArray items;
for (const auto &phrase : phraseHints) {
items.append(QJsonObject{{"text", phrase}});
}
QJsonArray groups;
groups.append(QJsonObject{
{"type", QStringLiteral("Generic")},
{"items", items}
});
contextRoot.insert("dgi", QJsonObject{
{"groups", groups},
{"bias", 1.0}
});
}
const QStringList languageHints = splitList(currentSettings.languageHints);
if (currentSettings.languageHintsStrict && !languageHints.isEmpty()) {
QJsonArray languages;
for (const auto &lang : languageHints)
languages.append(lang);
contextRoot.insert("languageId", QJsonObject{
{"languages", languages},
{"mode", QStringLiteral("DetectAtAudioStart")},
{"onSuccess", QJsonObject{{"action", QStringLiteral("Recognize")}}},
{"onUnknown", QJsonObject{{"action", QStringLiteral("None")}}},
{"priority", QStringLiteral("PrioritizeLatency")}
});
contextRoot.insert("phraseOutput", QJsonObject{
{"interimResults", QJsonObject{{"resultType", QStringLiteral("Auto")}}},
{"phraseResults", QJsonObject{{"resultType", QStringLiteral("Always")}}}
});
}
const QJsonDocument contextDoc(contextRoot);
socket.sendTextMessage(buildTextMessage(QStringLiteral("speech.context"),
requestId,
QStringLiteral("application/json"),
QString::fromUtf8(contextDoc.toJson(QJsonDocument::Compact))));
socket.sendBinaryMessage(buildBinaryMessage(QStringLiteral("audio"),
requestId,
QStringLiteral("audio/x-wav"),
wavHeader));
}
void AzureSpeechService::resetState() {
committedText.clear();
currentText.clear();
requestId.clear();
connectionId.clear();
wavHeader.clear();
stopRequested = false;
needsConversion = false;
inputBitsPerSample = 0;
inputSampleType = SampleType::Signed;
}
bool AzureSpeechService::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;
}
bool AzureSpeechService::buildWavHeader(const AudioSpec &spec, int bitsPerSample,
QByteArray *header, QString *error) const {
if (!header)
return false;
if (bitsPerSample <= 0 || bitsPerSample % 8 != 0) {
if (error)
*error = tr("Unsupported audio sample size.");
return false;
}
if (spec.sampleRate <= 0 || spec.channels <= 0) {
if (error)
*error = tr("Invalid audio format settings.");
return false;
}
const int blockAlign = spec.channels * (bitsPerSample / 8);
const int byteRate = spec.sampleRate * blockAlign;
QByteArray wav(44, 0);
auto write16 = [&wav](int offset, quint16 value) {
wav[offset] = static_cast<char>(value & 0xff);
wav[offset + 1] = static_cast<char>((value >> 8) & 0xff);
};
auto write32 = [&wav](int offset, quint32 value) {
wav[offset] = static_cast<char>(value & 0xff);
wav[offset + 1] = static_cast<char>((value >> 8) & 0xff);
wav[offset + 2] = static_cast<char>((value >> 16) & 0xff);
wav[offset + 3] = static_cast<char>((value >> 24) & 0xff);
};
memcpy(wav.data() + 0, "RIFF", 4);
write32(4, 0);
memcpy(wav.data() + 8, "WAVEfmt ", 8);
write32(16, 16);
write16(20, 1);
write16(22, static_cast<quint16>(spec.channels));
write32(24, static_cast<quint32>(spec.sampleRate));
write32(28, static_cast<quint32>(byteRate));
write16(32, static_cast<quint16>(blockAlign));
write16(34, static_cast<quint16>(bitsPerSample));
memcpy(wav.data() + 36, "data", 4);
write32(40, 0);
*header = wav;
return true;
}
bool AzureSpeechService::parsePcmFormat(const QString &format, int *bitsPerSample,
bool *littleEndian, SampleType *sampleType,
QString *error) const {
if (bitsPerSample)
*bitsPerSample = 0;
if (littleEndian)
*littleEndian = true;
if (sampleType)
*sampleType = SampleType::Signed;
const QString trimmed = format.trimmed();
if (trimmed.isEmpty()) {
if (error)
*error = tr("Unsupported audio format for Azure.");
return false;
}
QRegularExpression regex(QStringLiteral("^pcm_([usf])(\\d+)(le|be)?$"),
QRegularExpression::CaseInsensitiveOption);
const QRegularExpressionMatch match = regex.match(trimmed);
if (!match.hasMatch()) {
if (error)
*error = tr("Unsupported audio format for Azure.");
return false;
}
const QString type = match.captured(1).toLower();
const int bits = match.captured(2).toInt();
const QString endian = match.captured(3).toLower();
if (!endian.isEmpty() && endian != QStringLiteral("le")) {
if (error)
*error = tr("Only little-endian PCM is supported.");
return false;
}
if (sampleType) {
if (type == QStringLiteral("f"))
*sampleType = SampleType::Float;
else if (type == QStringLiteral("u"))
*sampleType = SampleType::Unsigned;
else
*sampleType = SampleType::Signed;
}
if (bitsPerSample)
*bitsPerSample = bits;
if (littleEndian)
*littleEndian = true;
return bits > 0;
}
QByteArray AzureSpeechService::convertToPcm16(const QByteArray &data) const {
if (inputBitsPerSample <= 0)
return QByteArray();
const int bytesPerSample = inputBitsPerSample / 8;
if (bytesPerSample <= 0)
return QByteArray();
const int sampleCount = data.size() / bytesPerSample;
if (sampleCount <= 0)
return QByteArray();
QByteArray out(sampleCount * 2, 0);
const char *src = data.constData();
char *dst = out.data();
auto writeSample = [dst](int index, qint16 value) {
dst[index * 2] = static_cast<char>(value & 0xff);
dst[index * 2 + 1] = static_cast<char>((value >> 8) & 0xff);
};
switch (inputSampleType) {
case SampleType::Signed: {
if (inputBitsPerSample == 8) {
for (int i = 0; i < sampleCount; ++i) {
const qint8 sample = static_cast<qint8>(src[i]);
writeSample(i, static_cast<qint16>(sample) << 8);
}
} else if (inputBitsPerSample == 16) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 2;
const qint16 sample = static_cast<qint16>(
static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8));
writeSample(i, sample);
}
} else if (inputBitsPerSample == 24) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 3;
const quint32 packed = static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8) |
(static_cast<quint8>(src[offset + 2]) << 16);
qint32 value = (packed & 0x800000)
? static_cast<qint32>(packed | 0xFF000000)
: static_cast<qint32>(packed);
writeSample(i, static_cast<qint16>(value >> 8));
}
} else if (inputBitsPerSample == 32) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 4;
const qint32 value = static_cast<qint32>(
static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8) |
(static_cast<quint8>(src[offset + 2]) << 16) |
(static_cast<quint8>(src[offset + 3]) << 24));
writeSample(i, static_cast<qint16>(value >> 16));
}
} else {
return QByteArray();
}
break;
}
case SampleType::Unsigned: {
if (inputBitsPerSample == 8) {
for (int i = 0; i < sampleCount; ++i) {
const quint8 sample = static_cast<quint8>(src[i]);
const qint16 value = static_cast<qint16>(static_cast<int>(sample) - 128) << 8;
writeSample(i, value);
}
} else if (inputBitsPerSample == 16) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 2;
const quint16 sample = static_cast<quint16>(
static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8));
const qint32 value = static_cast<qint32>(sample) - 32768;
writeSample(i, static_cast<qint16>(value));
}
} else if (inputBitsPerSample == 24) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 3;
const quint32 sample = static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8) |
(static_cast<quint8>(src[offset + 2]) << 16);
const qint32 value = static_cast<qint32>(sample) - 0x800000;
writeSample(i, static_cast<qint16>(value >> 8));
}
} else if (inputBitsPerSample == 32) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 4;
const quint32 sample = static_cast<quint32>(
static_cast<quint8>(src[offset]) |
(static_cast<quint8>(src[offset + 1]) << 8) |
(static_cast<quint8>(src[offset + 2]) << 16) |
(static_cast<quint8>(src[offset + 3]) << 24));
const qint64 value = static_cast<qint64>(sample) - 0x80000000LL;
writeSample(i, static_cast<qint16>(value >> 16));
}
} else {
return QByteArray();
}
break;
}
case SampleType::Float: {
if (inputBitsPerSample == 32) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 4;
float value = 0.0f;
memcpy(&value, src + offset, sizeof(float));
const float clamped = qBound(-1.0f, value, 1.0f);
writeSample(i, static_cast<qint16>(clamped * 32767.0f));
}
} else if (inputBitsPerSample == 64) {
for (int i = 0; i < sampleCount; ++i) {
const int offset = i * 8;
double value = 0.0;
memcpy(&value, src + offset, sizeof(double));
const double clamped = qBound(-1.0, value, 1.0);
writeSample(i, static_cast<qint16>(clamped * 32767.0));
}
} else {
return QByteArray();
}
break;
}
}
return out;
}
QUrl AzureSpeechService::buildServiceUrl(const AzureSettings &settings, const QString &connectionId) const {
QString endpoint = settings.endpoint.trimmed();
if (endpoint.isEmpty()) {
endpoint = QStringLiteral("wss://eastus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1");
}
QUrl url(endpoint);
if (url.scheme().isEmpty())
url = QUrl(QStringLiteral("wss://") + endpoint);
if (url.scheme().compare(QStringLiteral("https"), Qt::CaseInsensitive) == 0)
url.setScheme(QStringLiteral("wss"));
if (url.scheme().compare(QStringLiteral("http"), Qt::CaseInsensitive) == 0)
url.setScheme(QStringLiteral("ws"));
if (!url.isValid())
return QUrl();
QUrlQuery query(url);
if (!settings.endpointId.trimmed().isEmpty() && !query.hasQueryItem(QStringLiteral("cid")))
query.addQueryItem(QStringLiteral("cid"), settings.endpointId.trimmed());
if (!query.hasQueryItem(QStringLiteral("format")))
query.addQueryItem(QStringLiteral("format"), QStringLiteral("simple"));
const QStringList languageHints = splitList(settings.languageHints);
const bool autoDetect = settings.languageHintsStrict && !languageHints.isEmpty()
&& !query.hasQueryItem(QStringLiteral("language"));
if (autoDetect) {
if (!query.hasQueryItem(QStringLiteral("lidEnabled")))
query.addQueryItem(QStringLiteral("lidEnabled"), QStringLiteral("true"));
} else if (!settings.language.trimmed().isEmpty() && !query.hasQueryItem(QStringLiteral("language"))) {
query.addQueryItem(QStringLiteral("language"), settings.language.trimmed());
}
if (!query.hasQueryItem(QStringLiteral("Ocp-Apim-Subscription-Key")))
query.addQueryItem(QStringLiteral("Ocp-Apim-Subscription-Key"), settings.apiKey.trimmed());
if (!connectionId.isEmpty() && !query.hasQueryItem(QStringLiteral("X-ConnectionId")))
query.addQueryItem(QStringLiteral("X-ConnectionId"), connectionId);
url.setQuery(query);
return url;
}
QString AzureSpeechService::buildTextMessage(const QString &path, const QString &requestId,
const QString &contentType, const QString &body) const {
QString message;
message += QStringLiteral("Path: ") + path + QStringLiteral("\r\n");
message += QStringLiteral("X-RequestId: ") + requestId + QStringLiteral("\r\n");
message += QStringLiteral("X-Timestamp: ")
+ QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)
+ QStringLiteral("\r\n");
if (!contentType.isEmpty()) {
message += QStringLiteral("Content-Type: ") + contentType + QStringLiteral("\r\n");
}
message += QStringLiteral("\r\n");
message += body;
return message;
}
QByteArray AzureSpeechService::buildBinaryMessage(const QString &path, const QString &requestId,
const QString &contentType, const QByteArray &body) const {
QString headers;
headers += QStringLiteral("Path: ") + path + QStringLiteral("\r\n");
headers += QStringLiteral("X-RequestId: ") + requestId + QStringLiteral("\r\n");
headers += QStringLiteral("X-Timestamp: ")
+ QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)
+ QStringLiteral("\r\n");
if (!contentType.isEmpty())
headers += QStringLiteral("Content-Type: ") + contentType + QStringLiteral("\r\n");
const QByteArray headerBytes = headers.toUtf8();
const quint16 headerLength = static_cast<quint16>(headerBytes.size());
QByteArray payload;
payload.resize(2 + headerLength + body.size());
payload[0] = static_cast<char>((headerLength >> 8) & 0xff);
payload[1] = static_cast<char>(headerLength & 0xff);
memcpy(payload.data() + 2, headerBytes.constData(), headerBytes.size());
if (!body.isEmpty())
memcpy(payload.data() + 2 + headerBytes.size(), body.constData(), body.size());
return payload;
}
QMap<QString, QString> AzureSpeechService::parseHeaders(const QString &headerBlock) const {
QMap<QString, QString> headers;
if (headerBlock.isEmpty())
return headers;
const QStringList lines = headerBlock.split(QStringLiteral("\r\n"), Qt::SkipEmptyParts);
for (const auto &line : lines) {
const int separator = line.indexOf(QLatin1Char(':'));
if (separator <= 0)
continue;
const QString name = line.left(separator).trimmed().toLower();
const QString value = line.mid(separator + 1).trimmed();
if (!name.isEmpty())
headers.insert(name, value);
}
return headers;
}
QString AzureSpeechService::extractResultText(const QJsonObject &root) const {
QString text = root.value(QStringLiteral("DisplayText")).toString();
if (text.isEmpty())
text = root.value(QStringLiteral("Text")).toString();
if (text.isEmpty()) {
const QJsonArray nbest = root.value(QStringLiteral("NBest")).toArray();
if (!nbest.isEmpty()) {
const QJsonObject best = nbest.at(0).toObject();
text = best.value(QStringLiteral("Display")).toString();
if (text.isEmpty())
text = best.value(QStringLiteral("DisplayText")).toString();
if (text.isEmpty())
text = best.value(QStringLiteral("Lexical")).toString();
if (text.isEmpty())
text = best.value(QStringLiteral("ITN")).toString();
}
}
return text.trimmed();
}
QString AzureSpeechService::extractErrorText(const QJsonObject &root) const {
const QString status = root.value(QStringLiteral("RecognitionStatus")).toString();
if (status.isEmpty())
return QString();
const QString lower = status.toLower();
if (lower == QStringLiteral("error") ||
lower == QStringLiteral("badrequest") ||
lower == QStringLiteral("forbidden") ||
lower == QStringLiteral("toomanyrequests")) {
QString details = root.value(QStringLiteral("ErrorDetails")).toString();
if (details.isEmpty())
details = root.value(QStringLiteral("errorDetails")).toString();
if (details.isEmpty())
details = status;
return details;
}
return QString();
}
void AzureSpeechService::appendCommittedText(const QString &text) {
if (text.isEmpty())
return;
if (!committedText.isEmpty() && !committedText.endsWith(QLatin1Char(' '))
&& !text.startsWith(QLatin1Char(' '))) {
committedText += QLatin1Char(' ');
}
committedText += text;
}
void AzureSpeechService::emitTranscript() {
QString fullText = committedText;
if (!currentText.isEmpty()) {
if (!fullText.isEmpty() && !fullText.endsWith(QLatin1Char(' '))
&& !currentText.startsWith(QLatin1Char(' '))) {
fullText += QLatin1Char(' ');
}
fullText += currentText;
}
if (!fullText.isEmpty())
emit transcriptUpdated(fullText);
}