-
Notifications
You must be signed in to change notification settings - Fork 4
/
sherpa_onnx.go
1387 lines (1069 loc) · 43 KB
/
sherpa_onnx.go
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Speech recognition with [Next-gen Kaldi].
[sherpa-onnx] is an open-source speech recognition framework for [Next-gen Kaldi].
It depends only on [onnxruntime], supporting both streaming and non-streaming
speech recognition.
It does not need to access the network during recognition and everything
runs locally.
It supports a variety of platforms, such as Linux (x86_64, aarch64, arm),
Windows (x86_64, x86), macOS (x86_64, arm64), etc.
Usage examples:
1. Real-time speech recognition from a microphone
Please see
https://github.com/k2-fsa/sherpa-onnx/tree/master/go-api-examples/real-time-speech-recognition-from-microphone
2. Decode files using a non-streaming model
Please see
https://github.com/k2-fsa/sherpa-onnx/tree/master/go-api-examples/non-streaming-decode-files
3. Decode files using a streaming model
Please see
https://github.com/k2-fsa/sherpa-onnx/tree/master/go-api-examples/streaming-decode-files
4. Convert text to speech using a non-streaming model
Please see
https://github.com/k2-fsa/sherpa-onnx/tree/master/go-api-examples/non-streaming-tts
[sherpa-onnx]: https://github.com/k2-fsa/sherpa-onnx
[onnxruntime]: https://github.com/microsoft/onnxruntime
[Next-gen Kaldi]: https://github.com/k2-fsa/
*/
package sherpa_onnx
// #include <stdlib.h>
// #include "c-api.h"
import "C"
import "unsafe"
// Configuration for online/streaming transducer models
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-transducer/index.html
// to download pre-trained models
type OnlineTransducerModelConfig struct {
Encoder string // Path to the encoder model, e.g., encoder.onnx or encoder.int8.onnx
Decoder string // Path to the decoder model.
Joiner string // Path to the joiner model.
}
// Configuration for online/streaming paraformer models
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-paraformer/index.html
// to download pre-trained models
type OnlineParaformerModelConfig struct {
Encoder string // Path to the encoder model, e.g., encoder.onnx or encoder.int8.onnx
Decoder string // Path to the decoder model.
}
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-ctc/index.html
// to download pre-trained models
type OnlineZipformer2CtcModelConfig struct {
Model string // Path to the onnx model
}
// Configuration for online/streaming models
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-transducer/index.html
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/online-paraformer/index.html
// to download pre-trained models
type OnlineModelConfig struct {
Transducer OnlineTransducerModelConfig
Paraformer OnlineParaformerModelConfig
Zipformer2Ctc OnlineZipformer2CtcModelConfig
Tokens string // Path to tokens.txt
NumThreads int // Number of threads to use for neural network computation
Provider string // Optional. Valid values are: cpu, cuda, coreml
Debug int // 1 to show model meta information while loading it.
ModelType string // Optional. You can specify it for faster model initialization
ModelingUnit string // Optional. cjkchar, bpe, cjkchar+bpe
BpeVocab string // Optional.
TokensBuf string // Optional.
TokensBufSize int // Optional.
}
// Configuration for the feature extractor
type FeatureConfig struct {
// Sample rate expected by the model. It is 16000 for all
// pre-trained models provided by us
SampleRate int
// Feature dimension expected by the model. It is 80 for all
// pre-trained models provided by us
FeatureDim int
}
type OnlineCtcFstDecoderConfig struct {
Graph string
MaxActive int
}
// Configuration for the online/streaming recognizer.
type OnlineRecognizerConfig struct {
FeatConfig FeatureConfig
ModelConfig OnlineModelConfig
// Valid decoding methods: greedy_search, modified_beam_search
DecodingMethod string
// Used only when DecodingMethod is modified_beam_search. It specifies
// the maximum number of paths to keep during the search
MaxActivePaths int
EnableEndpoint int // 1 to enable endpoint detection.
// Please see
// https://k2-fsa.github.io/sherpa/ncnn/endpoint.html
// for the meaning of Rule1MinTrailingSilence, Rule2MinTrailingSilence
// and Rule3MinUtteranceLength.
Rule1MinTrailingSilence float32
Rule2MinTrailingSilence float32
Rule3MinUtteranceLength float32
HotwordsFile string
HotwordsScore float32
BlankPenalty float32
CtcFstDecoderConfig OnlineCtcFstDecoderConfig
RuleFsts string
RuleFars string
HotwordsBuf string
HotwordsBufSize int
}
// It contains the recognition result for a online stream.
type OnlineRecognizerResult struct {
Text string
}
// The online recognizer class. It wraps a pointer from C.
type OnlineRecognizer struct {
impl *C.struct_SherpaOnnxOnlineRecognizer
}
// The online stream class. It wraps a pointer from C.
type OnlineStream struct {
impl *C.struct_SherpaOnnxOnlineStream
}
// Free the internal pointer inside the recognizer to avoid memory leak.
func DeleteOnlineRecognizer(recognizer *OnlineRecognizer) {
C.SherpaOnnxDestroyOnlineRecognizer(recognizer.impl)
recognizer.impl = nil
}
// The user is responsible to invoke [DeleteOnlineRecognizer]() to free
// the returned recognizer to avoid memory leak
func NewOnlineRecognizer(config *OnlineRecognizerConfig) *OnlineRecognizer {
c := C.struct_SherpaOnnxOnlineRecognizerConfig{}
c.feat_config.sample_rate = C.int(config.FeatConfig.SampleRate)
c.feat_config.feature_dim = C.int(config.FeatConfig.FeatureDim)
c.model_config.transducer.encoder = C.CString(config.ModelConfig.Transducer.Encoder)
defer C.free(unsafe.Pointer(c.model_config.transducer.encoder))
c.model_config.transducer.decoder = C.CString(config.ModelConfig.Transducer.Decoder)
defer C.free(unsafe.Pointer(c.model_config.transducer.decoder))
c.model_config.transducer.joiner = C.CString(config.ModelConfig.Transducer.Joiner)
defer C.free(unsafe.Pointer(c.model_config.transducer.joiner))
c.model_config.paraformer.encoder = C.CString(config.ModelConfig.Paraformer.Encoder)
defer C.free(unsafe.Pointer(c.model_config.paraformer.encoder))
c.model_config.paraformer.decoder = C.CString(config.ModelConfig.Paraformer.Decoder)
defer C.free(unsafe.Pointer(c.model_config.paraformer.decoder))
c.model_config.zipformer2_ctc.model = C.CString(config.ModelConfig.Zipformer2Ctc.Model)
defer C.free(unsafe.Pointer(c.model_config.zipformer2_ctc.model))
c.model_config.tokens = C.CString(config.ModelConfig.Tokens)
defer C.free(unsafe.Pointer(c.model_config.tokens))
c.model_config.tokens_buf = C.CString(config.ModelConfig.TokensBuf)
defer C.free(unsafe.Pointer(c.model_config.tokens_buf))
c.model_config.tokens_buf_size = C.int(config.ModelConfig.TokensBufSize)
c.model_config.num_threads = C.int(config.ModelConfig.NumThreads)
c.model_config.provider = C.CString(config.ModelConfig.Provider)
defer C.free(unsafe.Pointer(c.model_config.provider))
c.model_config.debug = C.int(config.ModelConfig.Debug)
c.model_config.model_type = C.CString(config.ModelConfig.ModelType)
defer C.free(unsafe.Pointer(c.model_config.model_type))
c.model_config.modeling_unit = C.CString(config.ModelConfig.ModelingUnit)
defer C.free(unsafe.Pointer(c.model_config.modeling_unit))
c.model_config.bpe_vocab = C.CString(config.ModelConfig.BpeVocab)
defer C.free(unsafe.Pointer(c.model_config.bpe_vocab))
c.decoding_method = C.CString(config.DecodingMethod)
defer C.free(unsafe.Pointer(c.decoding_method))
c.max_active_paths = C.int(config.MaxActivePaths)
c.enable_endpoint = C.int(config.EnableEndpoint)
c.rule1_min_trailing_silence = C.float(config.Rule1MinTrailingSilence)
c.rule2_min_trailing_silence = C.float(config.Rule2MinTrailingSilence)
c.rule3_min_utterance_length = C.float(config.Rule3MinUtteranceLength)
c.hotwords_file = C.CString(config.HotwordsFile)
defer C.free(unsafe.Pointer(c.hotwords_file))
c.hotwords_buf = C.CString(config.HotwordsBuf)
defer C.free(unsafe.Pointer(c.hotwords_buf))
c.hotwords_buf_size = C.int(config.HotwordsBufSize)
c.hotwords_score = C.float(config.HotwordsScore)
c.blank_penalty = C.float(config.BlankPenalty)
c.rule_fsts = C.CString(config.RuleFsts)
defer C.free(unsafe.Pointer(c.rule_fsts))
c.rule_fars = C.CString(config.RuleFars)
defer C.free(unsafe.Pointer(c.rule_fars))
c.ctc_fst_decoder_config.graph = C.CString(config.CtcFstDecoderConfig.Graph)
defer C.free(unsafe.Pointer(c.ctc_fst_decoder_config.graph))
c.ctc_fst_decoder_config.max_active = C.int(config.CtcFstDecoderConfig.MaxActive)
recognizer := &OnlineRecognizer{}
recognizer.impl = C.SherpaOnnxCreateOnlineRecognizer(&c)
return recognizer
}
// Delete the internal pointer inside the stream to avoid memory leak.
func DeleteOnlineStream(stream *OnlineStream) {
C.SherpaOnnxDestroyOnlineStream(stream.impl)
stream.impl = nil
}
// The user is responsible to invoke [DeleteOnlineStream]() to free
// the returned stream to avoid memory leak
func NewOnlineStream(recognizer *OnlineRecognizer) *OnlineStream {
stream := &OnlineStream{}
stream.impl = C.SherpaOnnxCreateOnlineStream(recognizer.impl)
return stream
}
// Input audio samples for the stream.
//
// sampleRate is the actual sample rate of the input audio samples. If it
// is different from the sample rate expected by the feature extractor, we will
// do resampling inside.
//
// samples contains audio samples. Each sample is in the range [-1, 1]
func (s *OnlineStream) AcceptWaveform(sampleRate int, samples []float32) {
C.SherpaOnnxOnlineStreamAcceptWaveform(s.impl, C.int(sampleRate), (*C.float)(&samples[0]), C.int(len(samples)))
}
// Signal that there will be no incoming audio samples.
// After calling this function, you cannot call [OnlineStream.AcceptWaveform] any longer.
//
// The main purpose of this function is to flush the remaining audio samples
// buffered inside for feature extraction.
func (s *OnlineStream) InputFinished() {
C.SherpaOnnxOnlineStreamInputFinished(s.impl)
}
// Check whether the stream has enough feature frames for decoding.
// Return true if this stream is ready for decoding. Return false otherwise.
//
// You will usually use it like below:
//
// for recognizer.IsReady(s) {
// recognizer.Decode(s)
// }
func (recognizer *OnlineRecognizer) IsReady(s *OnlineStream) bool {
return C.SherpaOnnxIsOnlineStreamReady(recognizer.impl, s.impl) == 1
}
// Return true if an endpoint is detected.
//
// You usually use it like below:
//
// if recognizer.IsEndpoint(s) {
// // do your own stuff after detecting an endpoint
//
// recognizer.Reset(s)
// }
func (recognizer *OnlineRecognizer) IsEndpoint(s *OnlineStream) bool {
return C.SherpaOnnxOnlineStreamIsEndpoint(recognizer.impl, s.impl) == 1
}
// After calling this function, the internal neural network model states
// are reset and IsEndpoint(s) would return false. GetResult(s) would also
// return an empty string.
func (recognizer *OnlineRecognizer) Reset(s *OnlineStream) {
C.SherpaOnnxOnlineStreamReset(recognizer.impl, s.impl)
}
// Decode the stream. Before calling this function, you have to ensure
// that recognizer.IsReady(s) returns true. Otherwise, you will be SAD.
//
// You usually use it like below:
//
// for recognizer.IsReady(s) {
// recognizer.Decode(s)
// }
func (recognizer *OnlineRecognizer) Decode(s *OnlineStream) {
C.SherpaOnnxDecodeOnlineStream(recognizer.impl, s.impl)
}
// Decode multiple streams in parallel, i.e., in batch.
// You have to ensure that each stream is ready for decoding. Otherwise,
// you will be SAD.
func (recognizer *OnlineRecognizer) DecodeStreams(s []*OnlineStream) {
ss := make([]*C.struct_SherpaOnnxOnlineStream, len(s))
for i, v := range s {
ss[i] = v.impl
}
C.SherpaOnnxDecodeMultipleOnlineStreams(recognizer.impl, &ss[0], C.int(len(s)))
}
// Get the current result of stream since the last invoke of Reset()
func (recognizer *OnlineRecognizer) GetResult(s *OnlineStream) *OnlineRecognizerResult {
p := C.SherpaOnnxGetOnlineStreamResult(recognizer.impl, s.impl)
defer C.SherpaOnnxDestroyOnlineRecognizerResult(p)
result := &OnlineRecognizerResult{}
result.Text = C.GoString(p.text)
return result
}
// Configuration for offline/non-streaming transducer.
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/offline-transducer/index.html
// to download pre-trained models
type OfflineTransducerModelConfig struct {
Encoder string // Path to the encoder model, i.e., encoder.onnx or encoder.int8.onnx
Decoder string // Path to the decoder model
Joiner string // Path to the joiner model
}
// Configuration for offline/non-streaming paraformer.
//
// please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/offline-paraformer/index.html
// to download pre-trained models
type OfflineParaformerModelConfig struct {
Model string // Path to the model, e.g., model.onnx or model.int8.onnx
}
// Configuration for offline/non-streaming NeMo CTC models.
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/pretrained_models/offline-ctc/index.html
// to download pre-trained models
type OfflineNemoEncDecCtcModelConfig struct {
Model string // Path to the model, e.g., model.onnx or model.int8.onnx
}
type OfflineWhisperModelConfig struct {
Encoder string
Decoder string
Language string
Task string
TailPaddings int
}
type OfflineMoonshineModelConfig struct {
Preprocessor string
Encoder string
UncachedDecoder string
CachedDecoder string
}
type OfflineTdnnModelConfig struct {
Model string
}
type OfflineSenseVoiceModelConfig struct {
Model string
Language string
UseInverseTextNormalization int
}
// Configuration for offline LM.
type OfflineLMConfig struct {
Model string // Path to the model
Scale float32 // scale for LM score
}
type OfflineModelConfig struct {
Transducer OfflineTransducerModelConfig
Paraformer OfflineParaformerModelConfig
NemoCTC OfflineNemoEncDecCtcModelConfig
Whisper OfflineWhisperModelConfig
Tdnn OfflineTdnnModelConfig
SenseVoice OfflineSenseVoiceModelConfig
Moonshine OfflineMoonshineModelConfig
Tokens string // Path to tokens.txt
// Number of threads to use for neural network computation
NumThreads int
// 1 to print model meta information while loading
Debug int
// Optional. Valid values: cpu, cuda, coreml
Provider string
// Optional. Specify it for faster model initialization.
ModelType string
ModelingUnit string // Optional. cjkchar, bpe, cjkchar+bpe
BpeVocab string // Optional.
TeleSpeechCtc string // Optional.
}
// Configuration for the offline/non-streaming recognizer.
type OfflineRecognizerConfig struct {
FeatConfig FeatureConfig
ModelConfig OfflineModelConfig
LmConfig OfflineLMConfig
// Valid decoding method: greedy_search, modified_beam_search
DecodingMethod string
// Used only when DecodingMethod is modified_beam_search.
MaxActivePaths int
HotwordsFile string
HotwordsScore float32
BlankPenalty float32
RuleFsts string
RuleFars string
}
// It wraps a pointer from C
type OfflineRecognizer struct {
impl *C.struct_SherpaOnnxOfflineRecognizer
}
// It wraps a pointer from C
type OfflineStream struct {
impl *C.struct_SherpaOnnxOfflineStream
}
// It contains recognition result of an offline stream.
type OfflineRecognizerResult struct {
Text string
Tokens []string
Timestamps []float32
Lang string
Emotion string
Event string
}
// Frees the internal pointer of the recognition to avoid memory leak.
func DeleteOfflineRecognizer(recognizer *OfflineRecognizer) {
C.SherpaOnnxDestroyOfflineRecognizer(recognizer.impl)
recognizer.impl = nil
}
// The user is responsible to invoke [DeleteOfflineRecognizer]() to free
// the returned recognizer to avoid memory leak
func NewOfflineRecognizer(config *OfflineRecognizerConfig) *OfflineRecognizer {
c := C.struct_SherpaOnnxOfflineRecognizerConfig{}
c.feat_config.sample_rate = C.int(config.FeatConfig.SampleRate)
c.feat_config.feature_dim = C.int(config.FeatConfig.FeatureDim)
c.model_config.transducer.encoder = C.CString(config.ModelConfig.Transducer.Encoder)
defer C.free(unsafe.Pointer(c.model_config.transducer.encoder))
c.model_config.transducer.decoder = C.CString(config.ModelConfig.Transducer.Decoder)
defer C.free(unsafe.Pointer(c.model_config.transducer.decoder))
c.model_config.transducer.joiner = C.CString(config.ModelConfig.Transducer.Joiner)
defer C.free(unsafe.Pointer(c.model_config.transducer.joiner))
c.model_config.paraformer.model = C.CString(config.ModelConfig.Paraformer.Model)
defer C.free(unsafe.Pointer(c.model_config.paraformer.model))
c.model_config.nemo_ctc.model = C.CString(config.ModelConfig.NemoCTC.Model)
defer C.free(unsafe.Pointer(c.model_config.nemo_ctc.model))
c.model_config.whisper.encoder = C.CString(config.ModelConfig.Whisper.Encoder)
defer C.free(unsafe.Pointer(c.model_config.whisper.encoder))
c.model_config.whisper.decoder = C.CString(config.ModelConfig.Whisper.Decoder)
defer C.free(unsafe.Pointer(c.model_config.whisper.decoder))
c.model_config.whisper.language = C.CString(config.ModelConfig.Whisper.Language)
defer C.free(unsafe.Pointer(c.model_config.whisper.language))
c.model_config.whisper.task = C.CString(config.ModelConfig.Whisper.Task)
defer C.free(unsafe.Pointer(c.model_config.whisper.task))
c.model_config.whisper.tail_paddings = C.int(config.ModelConfig.Whisper.TailPaddings)
c.model_config.tdnn.model = C.CString(config.ModelConfig.Tdnn.Model)
defer C.free(unsafe.Pointer(c.model_config.tdnn.model))
c.model_config.sense_voice.model = C.CString(config.ModelConfig.SenseVoice.Model)
defer C.free(unsafe.Pointer(c.model_config.sense_voice.model))
c.model_config.sense_voice.language = C.CString(config.ModelConfig.SenseVoice.Language)
defer C.free(unsafe.Pointer(c.model_config.sense_voice.language))
c.model_config.sense_voice.use_itn = C.int(config.ModelConfig.SenseVoice.UseInverseTextNormalization)
c.model_config.moonshine.preprocessor = C.CString(config.ModelConfig.Moonshine.Preprocessor)
defer C.free(unsafe.Pointer(c.model_config.moonshine.preprocessor))
c.model_config.moonshine.encoder = C.CString(config.ModelConfig.Moonshine.Encoder)
defer C.free(unsafe.Pointer(c.model_config.moonshine.encoder))
c.model_config.moonshine.uncached_decoder = C.CString(config.ModelConfig.Moonshine.UncachedDecoder)
defer C.free(unsafe.Pointer(c.model_config.moonshine.uncached_decoder))
c.model_config.moonshine.cached_decoder = C.CString(config.ModelConfig.Moonshine.CachedDecoder)
defer C.free(unsafe.Pointer(c.model_config.moonshine.cached_decoder))
c.model_config.tokens = C.CString(config.ModelConfig.Tokens)
defer C.free(unsafe.Pointer(c.model_config.tokens))
c.model_config.num_threads = C.int(config.ModelConfig.NumThreads)
c.model_config.debug = C.int(config.ModelConfig.Debug)
c.model_config.provider = C.CString(config.ModelConfig.Provider)
defer C.free(unsafe.Pointer(c.model_config.provider))
c.model_config.model_type = C.CString(config.ModelConfig.ModelType)
defer C.free(unsafe.Pointer(c.model_config.model_type))
c.model_config.modeling_unit = C.CString(config.ModelConfig.ModelingUnit)
defer C.free(unsafe.Pointer(c.model_config.modeling_unit))
c.model_config.bpe_vocab = C.CString(config.ModelConfig.BpeVocab)
defer C.free(unsafe.Pointer(c.model_config.bpe_vocab))
c.model_config.telespeech_ctc = C.CString(config.ModelConfig.TeleSpeechCtc)
defer C.free(unsafe.Pointer(c.model_config.telespeech_ctc))
c.lm_config.model = C.CString(config.LmConfig.Model)
defer C.free(unsafe.Pointer(c.lm_config.model))
c.lm_config.scale = C.float(config.LmConfig.Scale)
c.decoding_method = C.CString(config.DecodingMethod)
defer C.free(unsafe.Pointer(c.decoding_method))
c.max_active_paths = C.int(config.MaxActivePaths)
c.hotwords_file = C.CString(config.HotwordsFile)
defer C.free(unsafe.Pointer(c.hotwords_file))
c.hotwords_score = C.float(config.HotwordsScore)
c.blank_penalty = C.float(config.BlankPenalty)
c.rule_fsts = C.CString(config.RuleFsts)
defer C.free(unsafe.Pointer(c.rule_fsts))
c.rule_fars = C.CString(config.RuleFars)
defer C.free(unsafe.Pointer(c.rule_fars))
recognizer := &OfflineRecognizer{}
recognizer.impl = C.SherpaOnnxCreateOfflineRecognizer(&c)
return recognizer
}
// Frees the internal pointer of the stream to avoid memory leak.
func DeleteOfflineStream(stream *OfflineStream) {
C.SherpaOnnxDestroyOfflineStream(stream.impl)
stream.impl = nil
}
// The user is responsible to invoke [DeleteOfflineStream]() to free
// the returned stream to avoid memory leak
func NewOfflineStream(recognizer *OfflineRecognizer) *OfflineStream {
stream := &OfflineStream{}
stream.impl = C.SherpaOnnxCreateOfflineStream(recognizer.impl)
return stream
}
// Input audio samples for the offline stream.
// Please only call it once. That is, input all samples at once.
//
// sampleRate is the sample rate of the input audio samples. If it is different
// from the value expected by the feature extractor, we will do resampling inside.
//
// samples contains the actual audio samples. Each sample is in the range [-1, 1].
func (s *OfflineStream) AcceptWaveform(sampleRate int, samples []float32) {
C.SherpaOnnxAcceptWaveformOffline(s.impl, C.int(sampleRate), (*C.float)(&samples[0]), C.int(len(samples)))
}
// Decode the offline stream.
func (recognizer *OfflineRecognizer) Decode(s *OfflineStream) {
C.SherpaOnnxDecodeOfflineStream(recognizer.impl, s.impl)
}
// Decode multiple streams in parallel, i.e., in batch.
func (recognizer *OfflineRecognizer) DecodeStreams(s []*OfflineStream) {
ss := make([]*C.struct_SherpaOnnxOfflineStream, len(s))
for i, v := range s {
ss[i] = v.impl
}
C.SherpaOnnxDecodeMultipleOfflineStreams(recognizer.impl, &ss[0], C.int(len(s)))
}
// Get the recognition result of the offline stream.
func (s *OfflineStream) GetResult() *OfflineRecognizerResult {
p := C.SherpaOnnxGetOfflineStreamResult(s.impl)
defer C.SherpaOnnxDestroyOfflineRecognizerResult(p)
n := int(p.count)
if n == 0 {
return nil
}
result := &OfflineRecognizerResult{}
result.Text = C.GoString(p.text)
result.Lang = C.GoString(p.lang)
result.Emotion = C.GoString(p.emotion)
result.Event = C.GoString(p.event)
result.Tokens = make([]string, n)
tokens := (*[1 << 28]*C.char)(unsafe.Pointer(p.tokens_arr))[:n:n]
for i := 0; i < n; i++ {
result.Tokens[i] = C.GoString(tokens[i])
}
if p.timestamps == nil {
return result
}
result.Timestamps = make([]float32, n)
timestamps := (*[1 << 28]C.float)(unsafe.Pointer(p.timestamps))[:n:n]
for i := 0; i < n; i++ {
result.Timestamps[i] = float32(timestamps[i])
}
return result
}
// Configuration for offline/non-streaming text-to-speech (TTS).
//
// Please refer to
// https://k2-fsa.github.io/sherpa/onnx/tts/pretrained_models/index.html
// to download pre-trained models
type OfflineTtsVitsModelConfig struct {
Model string // Path to the VITS onnx model
Lexicon string // Path to lexicon.txt
Tokens string // Path to tokens.txt
DataDir string // Path to espeak-ng-data directory
NoiseScale float32 // noise scale for vits models. Please use 0.667 in general
NoiseScaleW float32 // noise scale for vits models. Please use 0.8 in general
LengthScale float32 // Please use 1.0 in general. Smaller -> Faster speech speed. Larger -> Slower speech speed
DictDir string // Path to dict directory for jieba (used only in Chinese tts)
}
type OfflineTtsModelConfig struct {
Vits OfflineTtsVitsModelConfig
// Number of threads to use for neural network computation
NumThreads int
// 1 to print model meta information while loading
Debug int
// Optional. Valid values: cpu, cuda, coreml
Provider string
}
type OfflineTtsConfig struct {
Model OfflineTtsModelConfig
RuleFsts string
RuleFars string
MaxNumSentences int
}
type GeneratedAudio struct {
// Normalized samples in the range [-1, 1]
Samples []float32
SampleRate int
}
// The offline tts class. It wraps a pointer from C.
type OfflineTts struct {
impl *C.struct_SherpaOnnxOfflineTts
}
// Free the internal pointer inside the tts to avoid memory leak.
func DeleteOfflineTts(tts *OfflineTts) {
C.SherpaOnnxDestroyOfflineTts(tts.impl)
tts.impl = nil
}
// The user is responsible to invoke [DeleteOfflineTts]() to free
// the returned tts to avoid memory leak
func NewOfflineTts(config *OfflineTtsConfig) *OfflineTts {
c := C.struct_SherpaOnnxOfflineTtsConfig{}
c.rule_fsts = C.CString(config.RuleFsts)
defer C.free(unsafe.Pointer(c.rule_fsts))
c.rule_fars = C.CString(config.RuleFars)
defer C.free(unsafe.Pointer(c.rule_fars))
c.max_num_sentences = C.int(config.MaxNumSentences)
c.model.vits.model = C.CString(config.Model.Vits.Model)
defer C.free(unsafe.Pointer(c.model.vits.model))
c.model.vits.lexicon = C.CString(config.Model.Vits.Lexicon)
defer C.free(unsafe.Pointer(c.model.vits.lexicon))
c.model.vits.tokens = C.CString(config.Model.Vits.Tokens)
defer C.free(unsafe.Pointer(c.model.vits.tokens))
c.model.vits.data_dir = C.CString(config.Model.Vits.DataDir)
defer C.free(unsafe.Pointer(c.model.vits.data_dir))
c.model.vits.noise_scale = C.float(config.Model.Vits.NoiseScale)
c.model.vits.noise_scale_w = C.float(config.Model.Vits.NoiseScaleW)
c.model.vits.length_scale = C.float(config.Model.Vits.LengthScale)
c.model.vits.dict_dir = C.CString(config.Model.Vits.DictDir)
defer C.free(unsafe.Pointer(c.model.vits.dict_dir))
c.model.num_threads = C.int(config.Model.NumThreads)
c.model.debug = C.int(config.Model.Debug)
c.model.provider = C.CString(config.Model.Provider)
defer C.free(unsafe.Pointer(c.model.provider))
tts := &OfflineTts{}
tts.impl = C.SherpaOnnxCreateOfflineTts(&c)
return tts
}
func (tts *OfflineTts) Generate(text string, sid int, speed float32) *GeneratedAudio {
s := C.CString(text)
defer C.free(unsafe.Pointer(s))
audio := C.SherpaOnnxOfflineTtsGenerate(tts.impl, s, C.int(sid), C.float(speed))
defer C.SherpaOnnxDestroyOfflineTtsGeneratedAudio(audio)
ans := &GeneratedAudio{}
ans.SampleRate = int(audio.sample_rate)
n := int(audio.n)
ans.Samples = make([]float32, n)
// see https://stackoverflow.com/questions/48756732/what-does-1-30c-yourtype-do-exactly-in-cgo
// :n:n means 0:n:n, means low:high:capacity
samples := (*[1 << 28]C.float)(unsafe.Pointer(audio.samples))[:n:n]
// copy(ans.Samples, samples)
for i := 0; i < n; i++ {
ans.Samples[i] = float32(samples[i])
}
return ans
}
func (audio *GeneratedAudio) Save(filename string) bool {
s := C.CString(filename)
defer C.free(unsafe.Pointer(s))
ok := int(C.SherpaOnnxWriteWave((*C.float)(&audio.Samples[0]), C.int(len(audio.Samples)), C.int(audio.SampleRate), s))
return ok == 1
}
// ============================================================
// For VAD
// ============================================================
type SileroVadModelConfig struct {
Model string
Threshold float32
MinSilenceDuration float32
MinSpeechDuration float32
WindowSize int
MaxSpeechDuration float32
}
type VadModelConfig struct {
SileroVad SileroVadModelConfig
SampleRate int
NumThreads int
Provider string
Debug int
}
type CircularBuffer struct {
impl *C.struct_SherpaOnnxCircularBuffer
}
func DeleteCircularBuffer(buffer *CircularBuffer) {
C.SherpaOnnxDestroyCircularBuffer(buffer.impl)
buffer.impl = nil
}
func NewCircularBuffer(capacity int) *CircularBuffer {
circularBuffer := &CircularBuffer{}
circularBuffer.impl = C.SherpaOnnxCreateCircularBuffer(C.int(capacity))
return circularBuffer
}
func (buffer *CircularBuffer) Push(samples []float32) {
C.SherpaOnnxCircularBufferPush(buffer.impl, (*C.float)(&samples[0]), C.int(len(samples)))
}
func (buffer *CircularBuffer) Get(start int, n int) []float32 {
samples := C.SherpaOnnxCircularBufferGet(buffer.impl, C.int(start), C.int(n))
defer C.SherpaOnnxCircularBufferFree(samples)
result := make([]float32, n)
p := (*[1 << 28]C.float)(unsafe.Pointer(samples))[:n:n]
for i := 0; i < n; i++ {
result[i] = float32(p[i])
}
return result
}
func (buffer *CircularBuffer) Pop(n int) {
C.SherpaOnnxCircularBufferPop(buffer.impl, C.int(n))
}
func (buffer *CircularBuffer) Size() int {
return int(C.SherpaOnnxCircularBufferSize(buffer.impl))
}
func (buffer *CircularBuffer) Head() int {
return int(C.SherpaOnnxCircularBufferHead(buffer.impl))
}
func (buffer *CircularBuffer) Reset() {
C.SherpaOnnxCircularBufferReset(buffer.impl)
}
type SpeechSegment struct {
Start int
Samples []float32
}
type VoiceActivityDetector struct {
impl *C.struct_SherpaOnnxVoiceActivityDetector
}
func NewVoiceActivityDetector(config *VadModelConfig, bufferSizeInSeconds float32) *VoiceActivityDetector {
c := C.struct_SherpaOnnxVadModelConfig{}
c.silero_vad.model = C.CString(config.SileroVad.Model)
defer C.free(unsafe.Pointer(c.silero_vad.model))
c.silero_vad.threshold = C.float(config.SileroVad.Threshold)
c.silero_vad.min_silence_duration = C.float(config.SileroVad.MinSilenceDuration)
c.silero_vad.min_speech_duration = C.float(config.SileroVad.MinSpeechDuration)
c.silero_vad.window_size = C.int(config.SileroVad.WindowSize)
c.silero_vad.max_speech_duration = C.float(config.SileroVad.MaxSpeechDuration)
c.sample_rate = C.int(config.SampleRate)
c.num_threads = C.int(config.NumThreads)
c.provider = C.CString(config.Provider)
defer C.free(unsafe.Pointer(c.provider))
c.debug = C.int(config.Debug)
vad := &VoiceActivityDetector{}
vad.impl = C.SherpaOnnxCreateVoiceActivityDetector(&c, C.float(bufferSizeInSeconds))
return vad
}
func DeleteVoiceActivityDetector(vad *VoiceActivityDetector) {
C.SherpaOnnxDestroyVoiceActivityDetector(vad.impl)
vad.impl = nil
}
func (vad *VoiceActivityDetector) AcceptWaveform(samples []float32) {
C.SherpaOnnxVoiceActivityDetectorAcceptWaveform(vad.impl, (*C.float)(&samples[0]), C.int(len(samples)))
}
func (vad *VoiceActivityDetector) IsEmpty() bool {
return int(C.SherpaOnnxVoiceActivityDetectorEmpty(vad.impl)) == 1
}
func (vad *VoiceActivityDetector) IsSpeech() bool {
return int(C.SherpaOnnxVoiceActivityDetectorDetected(vad.impl)) == 1
}
func (vad *VoiceActivityDetector) Pop() {
C.SherpaOnnxVoiceActivityDetectorPop(vad.impl)
}
func (vad *VoiceActivityDetector) Clear() {
C.SherpaOnnxVoiceActivityDetectorClear(vad.impl)
}
func (vad *VoiceActivityDetector) Front() *SpeechSegment {
f := C.SherpaOnnxVoiceActivityDetectorFront(vad.impl)
defer C.SherpaOnnxDestroySpeechSegment(f)
ans := &SpeechSegment{}
ans.Start = int(f.start)
n := int(f.n)
ans.Samples = make([]float32, n)
samples := (*[1 << 28]C.float)(unsafe.Pointer(f.samples))[:n:n]
for i := 0; i < n; i++ {
ans.Samples[i] = float32(samples[i])
}
return ans
}
func (vad *VoiceActivityDetector) Reset() {
C.SherpaOnnxVoiceActivityDetectorReset(vad.impl)
}
func (vad *VoiceActivityDetector) Flush() {
C.SherpaOnnxVoiceActivityDetectorFlush(vad.impl)
}
// Spoken language identification
type SpokenLanguageIdentificationWhisperConfig struct {
Encoder string
Decoder string
TailPaddings int
}
type SpokenLanguageIdentificationConfig struct {
Whisper SpokenLanguageIdentificationWhisperConfig
NumThreads int
Debug int
Provider string
}
type SpokenLanguageIdentification struct {
impl *C.struct_SherpaOnnxSpokenLanguageIdentification
}
type SpokenLanguageIdentificationResult struct {
Lang string
}
func NewSpokenLanguageIdentification(config *SpokenLanguageIdentificationConfig) *SpokenLanguageIdentification {
c := C.struct_SherpaOnnxSpokenLanguageIdentificationConfig{}
c.whisper.encoder = C.CString(config.Whisper.Encoder)
defer C.free(unsafe.Pointer(c.whisper.encoder))
c.whisper.decoder = C.CString(config.Whisper.Decoder)
defer C.free(unsafe.Pointer(c.whisper.decoder))
c.whisper.tail_paddings = C.int(config.Whisper.TailPaddings)
c.num_threads = C.int(config.NumThreads)
c.debug = C.int(config.Debug)
c.provider = C.CString(config.Provider)
defer C.free(unsafe.Pointer(c.provider))
slid := &SpokenLanguageIdentification{}
slid.impl = C.SherpaOnnxCreateSpokenLanguageIdentification(&c)
return slid
}
func DeleteSpokenLanguageIdentification(slid *SpokenLanguageIdentification) {
C.SherpaOnnxDestroySpokenLanguageIdentification(slid.impl)
slid.impl = nil
}
// The user has to invoke DeleteOfflineStream() to free the returned value
// to avoid memory leak
func (slid *SpokenLanguageIdentification) CreateStream() *OfflineStream {
stream := &OfflineStream{}
stream.impl = C.SherpaOnnxSpokenLanguageIdentificationCreateOfflineStream(slid.impl)
return stream
}