Repository navigation
Expand file tree
/
Copy pathpybind_rapidspeech.cpp
More file actions
910 lines (773 loc) · 33.1 KB
/
Copy pathpybind_rapidspeech.cpp
File metadata and controls
910 lines (773 loc) · 33.1 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
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
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "rapidspeech.h"
namespace py = pybind11;
// -----------------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------------
static std::string rs_format_error(const char *prefix) {
rs_error_info_t err = rs_get_last_error();
std::string msg = prefix ? prefix : "rapidspeech error";
if (err.code != RS_OK) {
msg += " (code=";
msg += std::to_string((int)err.code);
msg += "): ";
msg += err.message;
}
return msg;
}
static void check_rs(rs_error_t e, const char *what) {
if (e != RS_OK) {
throw std::runtime_error(rs_format_error(what));
}
}
// -----------------------------------------------------------------------------
// ASR Offline
// -----------------------------------------------------------------------------
class RSAsrOffline {
public:
RSAsrOffline(const std::string &model_path,
int n_threads = 4,
bool use_gpu = true) {
rs_init_params_t p = rs_default_params();
p.model_path = model_path.c_str();
p.n_threads = n_threads;
p.use_gpu = use_gpu;
p.task_type = RS_TASK_ASR_OFFLINE;
ctx_ = rs_init_from_file(p);
if (!ctx_) {
throw std::runtime_error(rs_format_error("Failed to initialize ASR context"));
}
}
~RSAsrOffline() {
if (ctx_) {
rs_free(ctx_);
ctx_ = nullptr;
}
}
void push_audio(py::array_t<float, py::array::c_style | py::array::forcecast> pcm) {
auto buf = pcm.request();
if (buf.ndim != 1) {
throw std::runtime_error("PCM must be a 1-D float32 array");
}
float *data = static_cast<float *>(buf.ptr);
int n = static_cast<int>(buf.shape[0]);
py::gil_scoped_release nogil;
check_rs(rs_push_audio(ctx_, data, n), "rs_push_audio failed");
}
int process() { return rs_process(ctx_); }
int redecode() { return rs_redecode(ctx_); }
void reset() { check_rs(rs_reset(ctx_), "rs_reset failed"); }
std::string get_text() {
const char *res = rs_get_text_output(ctx_);
return res ? std::string(res) : std::string();
}
void set_user_input_prompt(const std::string &prompt) {
check_rs(rs_set_user_input_prompt(ctx_, prompt.c_str()),
"rs_set_user_input_prompt failed");
}
void set_use_llm(bool enable) {
check_rs(rs_set_use_llm(ctx_, enable), "rs_set_use_llm failed");
}
void set_ctc_precheck(bool enable) {
check_rs(rs_set_ctc_precheck(ctx_, enable), "rs_set_ctc_precheck failed");
}
// --- true streaming ASR (X-ASR, R2T2) ---
bool stream_supported() const { return rs_asr_stream_supported(ctx_); }
void set_chunk_len(int n_fbank_frames) {
check_rs(rs_asr_stream_set_chunk_len(ctx_, n_fbank_frames),
"rs_asr_stream_set_chunk_len failed");
}
void set_stream_language(const std::string &lang) {
check_rs(rs_asr_stream_set_language(ctx_, lang.c_str()),
"rs_asr_stream_set_language failed");
}
void set_stream_context(const std::string &context) {
check_rs(rs_asr_stream_set_context(ctx_, context.c_str()),
"rs_asr_stream_set_context failed");
}
// Push PCM; returns True if new tokens were emitted (partial updated).
bool stream_push(py::array_t<float, py::array::c_style | py::array::forcecast> pcm) {
auto buf = pcm.request();
if (buf.ndim != 1) {
throw std::runtime_error("PCM must be a 1-D float32 array");
}
float *data = static_cast<float *>(buf.ptr);
int n = static_cast<int>(buf.shape[0]);
int r;
{
py::gil_scoped_release nogil;
r = rs_asr_stream_push(ctx_, data, n);
}
if (r < 0) throw std::runtime_error("rs_asr_stream_push failed");
return r == 1;
}
std::string stream_get_text() {
const char *res = rs_asr_stream_get_text(ctx_);
return res ? std::string(res) : std::string();
}
void stream_finish() {
py::gil_scoped_release nogil;
check_rs(rs_asr_stream_finish(ctx_), "rs_asr_stream_finish failed");
}
void stream_reset() {
check_rs(rs_asr_stream_reset(ctx_), "rs_asr_stream_reset failed");
}
py::dict get_model_meta() const {
rs_model_meta_t m = rs_get_model_meta(ctx_);
py::dict d;
d["arch_name"] = std::string(m.arch_name);
d["audio_sample_rate"] = m.audio_sample_rate;
d["audio_channels"] = m.audio_channels;
d["n_mels"] = m.n_mels;
d["vocab_size"] = m.vocab_size;
return d;
}
std::string get_backend_name() const {
const char *n = rs_get_backend_name(ctx_);
return n ? std::string(n) : std::string();
}
private:
rs_context_t *ctx_ = nullptr;
};
// -----------------------------------------------------------------------------
// TTS Synthesizer
// -----------------------------------------------------------------------------
class RSTTSSynthesizer {
public:
RSTTSSynthesizer(const std::string &model_path,
int n_threads = 4,
bool use_gpu = true) {
rs_init_params_t p = rs_default_params();
p.model_path = model_path.c_str();
p.n_threads = n_threads;
p.use_gpu = use_gpu;
p.task_type = RS_TASK_TTS_ONLINE;
ctx_ = rs_init_from_file(p);
if (!ctx_) {
throw std::runtime_error(rs_format_error("Failed to initialize TTS context"));
}
}
~RSTTSSynthesizer() {
if (ctx_) {
rs_free(ctx_);
ctx_ = nullptr;
}
}
// ---- Configuration ----
void set_params(const std::string &instruct,
const std::string &language,
int seed) {
check_rs(rs_set_tts_params(ctx_, instruct.c_str(), language.c_str(), seed),
"rs_set_tts_params failed");
}
void set_diffusion_steps(int n_steps) {
check_rs(rs_set_tts_diffusion_steps(ctx_, n_steps),
"rs_set_tts_diffusion_steps failed");
}
// ---- Voice cloning ----
void set_reference_audio(py::array_t<float, py::array::c_style | py::array::forcecast> pcm,
int sample_rate = 16000) {
auto buf = pcm.request();
if (buf.ndim != 1) {
throw std::runtime_error("PCM must be a 1-D float32 array");
}
if (rs_push_reference_audio(ctx_,
static_cast<float *>(buf.ptr),
static_cast<int>(buf.shape[0]),
sample_rate) != 0) {
throw std::runtime_error(rs_format_error("rs_push_reference_audio failed"));
}
}
void set_reference_text(const std::string &text) {
check_rs(rs_push_reference_text(ctx_, text.c_str()),
"rs_push_reference_text failed");
}
// ---- Synthesis ----
py::array_t<float> synthesize(const std::string &text) {
std::vector<float> all_pcm;
bool errored = false;
{
py::gil_scoped_release nogil;
rs_reset(ctx_);
int push_rc = rs_push_text(ctx_, text.c_str());
if (push_rc != RS_OK) { errored = true; }
else {
int ret;
while ((ret = rs_process(ctx_)) >= 0) {
float *chunk = nullptr;
int n = rs_get_audio_output(ctx_, &chunk);
if (n > 0 && chunk) {
all_pcm.insert(all_pcm.end(), chunk, chunk + n);
}
if (ret == 0) break;
}
if (ret < 0) errored = true;
}
}
if (errored) {
throw std::runtime_error(rs_format_error("TTS inference error"));
}
auto result = py::array_t<float>(static_cast<py::ssize_t>(all_pcm.size()));
std::memcpy(result.mutable_data(), all_pcm.data(), all_pcm.size() * sizeof(float));
return result;
}
py::list synthesize_streaming(const std::string &text) {
py::list chunks;
bool errored = false;
{
// Reset + push text under GIL release (no Python touched here).
py::gil_scoped_release nogil;
rs_reset(ctx_);
if (rs_push_text(ctx_, text.c_str()) != RS_OK) errored = true;
}
if (errored) {
throw std::runtime_error(rs_format_error("rs_push_text failed"));
}
int ret;
while (true) {
{
py::gil_scoped_release nogil;
ret = rs_process(ctx_);
}
if (ret < 0) break;
float *chunk = nullptr;
int n = rs_get_audio_output(ctx_, &chunk);
if (n > 0 && chunk) {
auto arr = py::array_t<float>(n);
std::memcpy(arr.mutable_data(), chunk, n * sizeof(float));
chunks.append(arr);
}
if (ret == 0) break;
}
if (ret < 0) {
throw std::runtime_error(rs_format_error("TTS inference error"));
}
return chunks;
}
// ---- Metadata ----
py::dict get_model_meta() const {
rs_model_meta_t m = rs_get_model_meta(ctx_);
py::dict d;
d["arch_name"] = std::string(m.arch_name);
d["audio_sample_rate"] = m.audio_sample_rate;
d["audio_channels"] = m.audio_channels;
d["n_mels"] = m.n_mels;
d["vocab_size"] = m.vocab_size;
return d;
}
std::string get_backend_name() const {
const char *n = rs_get_backend_name(ctx_);
return n ? std::string(n) : std::string();
}
int get_sample_rate() const {
rs_model_meta_t m = rs_get_model_meta(ctx_);
return m.audio_sample_rate;
}
private:
rs_context_t *ctx_ = nullptr;
};
// -----------------------------------------------------------------------------
// Text-to-music (YuE2-3B)
// -----------------------------------------------------------------------------
class RSMusicGenerator {
public:
RSMusicGenerator(const std::string &model_path,
int n_threads = 4,
bool use_gpu = true) {
rs_init_params_t p = rs_default_params();
p.model_path = model_path.c_str();
p.n_threads = n_threads;
p.use_gpu = use_gpu;
p.task_type = RS_TASK_T2M;
ctx_ = rs_init_from_file(p);
if (!ctx_) {
throw std::runtime_error(rs_format_error("Failed to initialize music context"));
}
rs_model_meta_t m = rs_get_model_meta(ctx_);
if (std::string(m.arch_name) != "yue2") {
rs_free(ctx_);
ctx_ = nullptr;
throw std::runtime_error(
std::string("Not a YuE2 music model (arch='") + m.arch_name + "')");
}
channels_ = m.audio_channels > 0 ? m.audio_channels : 2;
sample_rate_ = m.audio_sample_rate;
}
~RSMusicGenerator() {
if (ctx_) {
rs_free(ctx_);
ctx_ = nullptr;
}
}
// ---- Configuration ----
void set_params(int seed = -1,
double temperature = 1.0,
double top_p = 0.95,
int top_k = 100,
double repetition_penalty = 1.2,
int max_tokens = 9000,
int ode_steps = 32) {
rs_music_params_t p = rs_default_music_params();
p.seed = seed; // < 0 = nondeterministic
p.temperature = static_cast<float>(temperature);
p.top_p = static_cast<float>(top_p);
p.top_k = top_k;
p.repetition_penalty = static_cast<float>(repetition_penalty);
p.max_tokens = max_tokens;
p.ode_steps = ode_steps;
check_rs(rs_set_music_params(ctx_, &p), "rs_set_music_params failed");
}
// ---- Generation ----
// Returns the generated music as a float32 array. Stereo is returned as
// [frames, channels] so it can be handed straight to soundfile.write() /
// torchaudio; pass interleaved=True for the raw 1-D buffer.
py::array_t<float> generate(const std::string &style,
const std::string &lyrics,
double peak_norm = 0.0,
bool interleaved = false) {
std::vector<float> pcm;
bool errored = false;
{
// No Python objects may be created while the GIL is released.
py::gil_scoped_release nogil;
if (rs_push_music_input(ctx_, style.c_str(), lyrics.c_str()) != RS_OK) {
errored = true;
} else if (rs_generate_music(ctx_) != RS_OK) {
errored = true;
} else {
float *out = nullptr;
int n = rs_get_audio_output(ctx_, &out);
if (n > 0 && out) {
pcm.assign(out, out + n);
}
}
}
if (errored) {
throw std::runtime_error(rs_format_error("Music generation failed"));
}
if (pcm.empty()) {
throw std::runtime_error("Music generation produced no audio");
}
if (peak_norm > 0.0) {
float peak = 0.0f;
for (float v : pcm) peak = std::max(peak, std::fabs(v));
if (peak > 1e-6f) {
const float scale = static_cast<float>(peak_norm) / peak;
for (float &v : pcm) v *= scale;
}
}
const py::ssize_t n = static_cast<py::ssize_t>(pcm.size());
if (interleaved || channels_ <= 1) {
auto result = py::array_t<float>(n);
std::memcpy(result.mutable_data(), pcm.data(), pcm.size() * sizeof(float));
return result;
}
auto result = py::array_t<float>(
{n / channels_, static_cast<py::ssize_t>(channels_)});
std::memcpy(result.mutable_data(), pcm.data(), pcm.size() * sizeof(float));
return result;
}
// ---- Metadata ----
int get_sample_rate() const { return sample_rate_; }
int get_channels() const { return channels_; }
py::dict get_model_meta() const {
rs_model_meta_t m = rs_get_model_meta(ctx_);
py::dict d;
d["arch_name"] = std::string(m.arch_name);
d["audio_sample_rate"] = m.audio_sample_rate;
d["audio_channels"] = m.audio_channels;
d["n_mels"] = m.n_mels;
d["vocab_size"] = m.vocab_size;
return d;
}
std::string get_backend_name() const {
const char *n = rs_get_backend_name(ctx_);
return n ? std::string(n) : std::string();
}
private:
rs_context_t *ctx_ = nullptr;
int channels_ = 2;
int sample_rate_ = 48000;
};
// -----------------------------------------------------------------------------
// VAD (silero-vad / firered-vad — auto-detected from GGUF `general.architecture`)
// -----------------------------------------------------------------------------
class RSVad {
public:
RSVad(const std::string &model_path, int n_threads = 2, bool use_gpu = false) {
vad_ = rs_vad_init_from_file(model_path.c_str(), n_threads, use_gpu);
if (!vad_) {
throw std::runtime_error(rs_format_error("Failed to initialize VAD"));
}
}
~RSVad() {
if (vad_) {
rs_vad_free(vad_);
vad_ = nullptr;
}
}
void reset() { check_rs(rs_vad_reset(vad_), "rs_vad_reset failed"); }
void set_threshold(float threshold) {
check_rs(rs_vad_set_threshold(vad_, threshold), "rs_vad_set_threshold failed");
}
void push_audio(py::array_t<float, py::array::c_style | py::array::forcecast> pcm) {
auto buf = pcm.request();
if (buf.ndim != 1) {
throw std::runtime_error("PCM must be a 1-D float32 array");
}
float *data = static_cast<float *>(buf.ptr);
int n = static_cast<int>(buf.shape[0]);
py::gil_scoped_release nogil;
check_rs(rs_vad_push_audio(vad_, data, n), "rs_vad_push_audio failed");
}
bool is_speech() const { return rs_vad_is_speech(vad_) != 0; }
float get_probability() const { return rs_vad_get_probability(vad_); }
std::string get_arch() const {
const char *a = rs_vad_get_arch(vad_);
return a ? std::string(a) : std::string();
}
py::list drain_segments(int max_count = 64) {
std::vector<rs_vad_segment_t> buf(max_count);
int n = rs_vad_drain_segments(vad_, buf.data(), max_count);
py::list out;
for (int i = 0; i < n; ++i) {
py::dict d;
d["start_s"] = buf[i].start_s;
d["end_s"] = buf[i].end_s;
out.append(d);
}
return out;
}
py::list drain_frames(int max_count = 256) {
std::vector<rs_vad_frame_t> buf(max_count);
int n = rs_vad_drain_frames(vad_, buf.data(), max_count);
py::list out;
for (int i = 0; i < n; ++i) {
py::dict d;
d["frame_idx"] = buf[i].frame_idx;
d["raw_prob"] = buf[i].raw_prob;
d["smoothed_prob"] = buf[i].smoothed_prob;
d["is_speech"] = buf[i].is_speech != 0;
d["is_speech_start"] = buf[i].is_speech_start != 0;
d["is_speech_end"] = buf[i].is_speech_end != 0;
out.append(d);
}
return out;
}
// One-shot: reset, push the whole clip, flush any open segment.
py::list detect_full(py::array_t<float, py::array::c_style | py::array::forcecast> pcm,
int max_segments = 1024) {
auto buf = pcm.request();
if (buf.ndim != 1) {
throw std::runtime_error("PCM must be a 1-D float32 array");
}
std::vector<rs_vad_segment_t> seg(max_segments);
int n;
{
py::gil_scoped_release nogil;
n = rs_vad_detect_full(vad_,
static_cast<float *>(buf.ptr),
static_cast<int>(buf.shape[0]),
seg.data(), max_segments);
}
py::list out;
for (int i = 0; i < std::min(n, max_segments); ++i) {
py::dict d;
d["start_s"] = seg[i].start_s;
d["end_s"] = seg[i].end_s;
out.append(d);
}
return out;
}
private:
rs_vad_t *vad_ = nullptr;
};
// -----------------------------------------------------------------------------
// Module
// -----------------------------------------------------------------------------
namespace {
using JevPcm = py::array_t<float, py::array::c_style | py::array::forcecast>;
rs_jev_audio_t jev_audio(const JevPcm &pcm)
{
if (pcm.ndim() != 1) throw py::value_error("Expected 1-D mono 16 kHz PCM");
return {pcm.data(), static_cast<size_t>(pcm.size())};
}
std::string jev_request(const py::dict &request)
{
return py::module_::import("json").attr("dumps")(
request, py::arg("ensure_ascii") = false, py::arg("allow_nan") = false).cast<std::string>();
}
py::object jev_result(char *json, const rs_error_info_t &error)
{
const std::unique_ptr<char, decltype(&rs_jev_json_free)> result(json, rs_jev_json_free);
if (!result) {
if (error.code == RS_ERR_INVALID_ARGS) throw py::value_error(error.message);
throw std::runtime_error(error.message);
}
return py::module_::import("json").attr("loads")(py::str(result.get()));
}
class RSJevStream
{
public:
explicit RSJevStream(rs_jev_stream_t *handle) : stream_(handle, rs_jev_stream_free) {}
py::object push_audio(const JevPcm &pcm)
{
const auto audio = jev_audio(pcm);
rs_error_info_t error{};
char *result;
{
py::gil_scoped_release release;
result = rs_jev_stream_push(stream_.get(), audio.samples, audio.count, &error);
}
return jev_result(result, error);
}
py::object finish()
{
rs_error_info_t error{};
char *result;
{
py::gil_scoped_release release;
result = rs_jev_stream_finish(stream_.get(), &error);
}
return jev_result(result, error);
}
private:
std::unique_ptr<rs_jev_stream_t, decltype(&rs_jev_stream_free)> stream_;
};
class RSJevModel
{
public:
RSJevModel(const std::string &path, int threads, bool gpu) : model_(nullptr, rs_jev_model_free)
{
rs_error_info_t error{};
{
py::gil_scoped_release release;
model_.reset(rs_jev_model_load(path.c_str(), threads, gpu, &error));
}
if (!model_) throw std::runtime_error(error.message);
}
py::object classify(const py::dict &request, const JevPcm &audio, const py::object &second)
{
const auto json = jev_request(request);
rs_jev_audio_t clips[2] = {jev_audio(audio), {}};
JevPcm other;
const bool has_second = !second.is_none();
if (has_second) {
other = second.cast<JevPcm>();
clips[1] = jev_audio(other);
}
rs_error_info_t error{};
char *result;
{
py::gil_scoped_release release;
result = rs_jev_classify(model_.get(), json.c_str(), clips, has_second ? 2 : 1, &error);
}
return jev_result(result, error);
}
std::unique_ptr<RSJevStream> stream(const py::dict &request)
{
const auto json = jev_request(request);
rs_error_info_t error{};
rs_jev_stream_t *handle;
{
py::gil_scoped_release release;
handle = rs_jev_stream_start(model_.get(), json.c_str(), &error);
}
if (!handle) {
if (error.code == RS_ERR_INVALID_ARGS) throw py::value_error(error.message);
throw std::runtime_error(error.message);
}
// The C stream retains the native model.
std::unique_ptr<rs_jev_stream_t, decltype(&rs_jev_stream_free)> guard(handle, rs_jev_stream_free);
auto result = std::make_unique<RSJevStream>(handle);
guard.release();
return result;
}
private:
std::unique_ptr<rs_jev_model_t, decltype(&rs_jev_model_free)> model_;
};
} // namespace
PYBIND11_MODULE(rapidspeech, m) {
m.doc() = "RapidSpeech Python bindings — offline/online ASR & TTS on ggml";
m.def("version", &rs_get_version, "Get the rapidspeech library version string");
py::class_<RSJevStream>(m, "JevStream")
.def("push_audio", &RSJevStream::push_audio, py::arg("pcm"))
.def("finish", &RSJevStream::finish);
py::class_<RSJevModel>(m, "JevModel")
.def(py::init<const std::string &, int, bool>(), py::arg("model_path"),
py::arg("n_threads") = 4, py::arg("use_gpu") = true)
.def("classify", &RSJevModel::classify, py::arg("request"), py::arg("pcm"),
py::arg("second_pcm") = py::none())
.def("stream", &RSJevModel::stream, py::arg("request"));
// ── ASR ────────────────────────────────────────────────────────
py::class_<RSAsrOffline>(m, "asr_offline")
.def(py::init<const std::string &, int, bool>(),
py::arg("model_path"),
py::arg("n_threads") = 4,
py::arg("use_gpu") = true,
"Load an offline ASR model (e.g. SenseVoice / FunASRNano).")
.def("push_audio", &RSAsrOffline::push_audio,
py::arg("pcm"),
"Push mono float32 PCM in [-1, 1] at the model's native sample rate.")
.def("process", &RSAsrOffline::process,
py::call_guard<py::gil_scoped_release>(),
"Run one inference step. Returns 0 (no output), 1 (has output), -1 (error).")
.def("redecode", &RSAsrOffline::redecode,
py::call_guard<py::gil_scoped_release>(),
"Re-run the decoder on the cached encoder output (e.g. after set_use_llm).")
.def("reset", &RSAsrOffline::reset,
"Clear audio buffer and text accumulator.")
.def("get_text", &RSAsrOffline::get_text,
"Return the transcribed text from the last process() / redecode().")
.def("set_user_input_prompt", &RSAsrOffline::set_user_input_prompt,
py::arg("prompt"),
"Set the LLM decoder prompt (default: \"语音转写:\"; FunASRNano only).")
.def("set_use_llm", &RSAsrOffline::set_use_llm,
py::arg("enable"),
"Toggle the 2nd-pass LLM decoder (FunASRNano only). False = CTC greedy.")
.def("set_ctc_precheck", &RSAsrOffline::set_ctc_precheck,
py::arg("enable"),
"Skip LLM decode on silence by running a quick CTC precheck first.")
// ── true streaming ASR (X-ASR, R2T2) ──
.def("stream_supported", &RSAsrOffline::stream_supported,
"True if the model supports chunked streaming (X-ASR, R2T2).")
.def("set_chunk_len", &RSAsrOffline::set_chunk_len,
py::arg("n_fbank_frames"),
"Streaming chunk length in fbank frames (10 ms each). X-ASR: "
"16/32/48/96/192 (multiples of 16). R2T2: any positive value "
"(80..2000 ms). Larger = higher latency, lower RTF.")
.def("set_stream_language", &RSAsrOffline::set_stream_language,
py::arg("language"),
"Streaming language hint (R2T2 only; e.g. \"Chinese\"). "
"Forces text-only output.")
.def("set_stream_context", &RSAsrOffline::set_stream_context,
py::arg("context"),
"Streaming context / hotword hint (R2T2 only).")
.def("stream_push", &RSAsrOffline::stream_push, py::arg("pcm"),
"Push 16 kHz mono float32 PCM in [-1,1]; returns True if the "
"partial was updated. Read it with stream_get_text().")
.def("stream_get_text", &RSAsrOffline::stream_get_text,
"Current running transcription for the stream.")
.def("stream_finish", &RSAsrOffline::stream_finish,
"Flush the tail (pads silence) so trailing speech is emitted.")
.def("stream_reset", &RSAsrOffline::stream_reset,
"Reset streaming state to start a fresh utterance.")
.def("get_model_meta", &RSAsrOffline::get_model_meta,
"Return a dict with arch_name, audio_sample_rate, audio_channels, n_mels, vocab_size.")
.def("get_backend_name", &RSAsrOffline::get_backend_name,
"Return the ggml backend in use (e.g. \"CUDA0\", \"Metal\", \"CPU\").");
// ── TTS ────────────────────────────────────────────────────────
py::class_<RSTTSSynthesizer>(m, "tts_synthesizer")
.def(py::init<const std::string &, int, bool>(),
py::arg("model_path"),
py::arg("n_threads") = 4,
py::arg("use_gpu") = true,
"Load a TTS model (e.g. OmniVoice / OpenVoice2).")
.def("set_params", &RSTTSSynthesizer::set_params,
py::arg("instruct") = "male",
py::arg("language") = "English",
py::arg("seed") = 42,
"Set voice description, target language, and RNG seed (OmniVoice only).")
.def("set_diffusion_steps", &RSTTSSynthesizer::set_diffusion_steps,
py::arg("n_steps"),
"Set MaskGIT diffusion steps (1-128, default 32; OmniVoice only).")
.def("set_reference_audio", &RSTTSSynthesizer::set_reference_audio,
py::arg("pcm"), py::arg("sample_rate") = 16000,
"Set reference audio for voice cloning (mono float32 PCM).")
.def("set_reference_text", &RSTTSSynthesizer::set_reference_text,
py::arg("text"),
"Set the transcript of the reference audio (required for voice cloning).")
.def("synthesize", &RSTTSSynthesizer::synthesize,
py::arg("text"),
"Synthesize text and return the full PCM as a 1-D float32 numpy array.")
.def("synthesize_streaming", &RSTTSSynthesizer::synthesize_streaming,
py::arg("text"),
"Synthesize text and return a list of PCM chunks (1-D float32 arrays).")
.def("get_sample_rate", &RSTTSSynthesizer::get_sample_rate,
"Return the audio sample rate produced by the TTS model.")
.def("get_model_meta", &RSTTSSynthesizer::get_model_meta,
"Return a dict with arch_name, audio_sample_rate, audio_channels, n_mels, vocab_size.")
.def("get_backend_name", &RSTTSSynthesizer::get_backend_name,
"Return the ggml backend in use (e.g. \"CUDA0\", \"Metal\", \"CPU\").");
// Backwards-compatible alias (old name from earlier examples)
m.attr("AsrOffline") = m.attr("asr_offline");
m.attr("TtsSynthesizer") = m.attr("tts_synthesizer");
// ── Text-to-music (YuE2) ───────────────────────────────────────
py::class_<RSMusicGenerator>(m, "music_generator")
.def(py::init<const std::string &, int, bool>(),
py::arg("model_path"),
py::arg("n_threads") = 4,
py::arg("use_gpu") = true,
"Load a YuE2 text-to-music model (raises if the GGUF is not a "
"`yue2` architecture).")
.def("set_params", &RSMusicGenerator::set_params,
py::arg("seed") = -1,
py::arg("temperature") = 1.0,
py::arg("top_p") = 0.95,
py::arg("top_k") = 100,
py::arg("repetition_penalty") = 1.2,
py::arg("max_tokens") = 9000,
py::arg("ode_steps") = 32,
"Set music generation parameters. seed < 0 = nondeterministic.")
.def("generate", &RSMusicGenerator::generate,
py::arg("style"),
py::arg("lyrics") = "",
py::arg("peak_norm") = 0.0,
py::arg("interleaved") = false,
"Generate music from a style description + lyrics.\n\n"
"Returns a float32 array shaped [frames, channels] (stereo), ready "
"for soundfile/ torchaudio — pass interleaved=True for the raw 1-D "
"interleaved buffer. peak_norm > 0 rescales the peak to that level.")
.def("get_sample_rate", &RSMusicGenerator::get_sample_rate,
"Return the sample rate of the generated audio (48000 for YuE2).")
.def("get_channels", &RSMusicGenerator::get_channels,
"Return the channel count of the generated audio (2 for YuE2).")
.def("get_model_meta", &RSMusicGenerator::get_model_meta,
"Return a dict with arch_name, audio_sample_rate, audio_channels, "
"n_mels, vocab_size.")
.def("get_backend_name", &RSMusicGenerator::get_backend_name,
"Return the ggml backend in use (e.g. \"CUDA0\", \"Metal\", \"CPU\").");
m.attr("MusicGenerator") = m.attr("music_generator");
// ── VAD ────────────────────────────────────────────────────────
py::class_<RSVad>(m, "vad")
.def(py::init<const std::string &, int, bool>(),
py::arg("model_path"),
py::arg("n_threads") = 2,
py::arg("use_gpu") = false,
"Load a VAD model (silero-vad or firered-vad, auto-detected from GGUF).")
.def("reset", &RSVad::reset,
"Reset all streaming state (caches, postprocessor, sample counter).")
.def("set_threshold", &RSVad::set_threshold,
py::arg("threshold"),
"Set speech-probability threshold (0..1).")
.def("push_audio", &RSVad::push_audio,
py::arg("pcm"),
"Push 16 kHz mono float32 PCM. Drives the segment/frame queues.")
.def("is_speech", &RSVad::is_speech,
"Latest post-push speech-state.")
.def("get_probability", &RSVad::get_probability,
"Latest post-push speech probability (0..1).")
.def("get_arch", &RSVad::get_arch,
"Architecture string (\"silero-vad\" or \"firered-vad\").")
.def("drain_segments", &RSVad::drain_segments,
py::arg("max_count") = 64,
"Drain queued [{start_s, end_s}, ...] segments. Empties internal queue.")
.def("drain_frames", &RSVad::drain_frames,
py::arg("max_count") = 256,
"Drain queued per-frame events. Empties internal queue.")
.def("detect_full", &RSVad::detect_full,
py::arg("pcm"),
py::arg("max_segments") = 1024,
"One-shot offline detection: reset, push the whole clip, "
"flush any open segment, return segments list.");
m.attr("Vad") = m.attr("vad");
}