Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d497c3a0a5 | |||
| f37ee638a4 | |||
| e0b29bb17f | |||
| c3e3fc002f | |||
| 62fc308bdf | |||
| 60c0e33901 | |||
| 5d09ee8b2b | |||
| 12f29a3415 | |||
| d56221bcf2 | |||
| a2eb39d2d7 | |||
| 128c216c61 | |||
| da87d0dad3 | |||
| 9cee2899bb | |||
| a40742bbaf | |||
| d714dff8d3 | |||
| 790c564d14 | |||
| 988ba3f257 | |||
| 2796da0a50 | |||
| d9c6fc4958 | |||
| fff40ce1a1 | |||
| 2deb7de1dd | |||
| 7d87267c31 | |||
| 64d84b01b1 |
+26
-38
@@ -4,62 +4,50 @@ buildscript {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:4.2.0'
|
||||
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.18.0'
|
||||
classpath 'com.android.tools.build:gradle:7.4.0'
|
||||
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.24.0'
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
version = '0.3.45'
|
||||
version = '0.3.47'
|
||||
}
|
||||
|
||||
subprojects {
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'maven-publish'
|
||||
apply plugin: 'com.vanniktech.maven.publish'
|
||||
|
||||
plugins.withId('com.vanniktech.maven.publish') {
|
||||
mavenPublish {
|
||||
group = 'com.alphacephei'
|
||||
version = version
|
||||
sonatypeHost = 's01'
|
||||
androidVariantToPublish = 'release'
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
aar(MavenPublication) {
|
||||
groupId 'com.alphacephei'
|
||||
version version
|
||||
pom {
|
||||
url = 'http://www.alphacephei.com.com/vosk/'
|
||||
licenses {
|
||||
license {
|
||||
name = 'The Apache License, Version 2.0'
|
||||
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
|
||||
}
|
||||
}
|
||||
developers {
|
||||
developer {
|
||||
id = 'com.alphacephei'
|
||||
name = 'Alpha Cephei Inc'
|
||||
email = 'contact@alphacephei.com'
|
||||
}
|
||||
}
|
||||
scm {
|
||||
connection = 'scm:git:git://github.com/alphacep/vosk-api.git'
|
||||
url = 'https://github.com/alphacep/vosk-api/'
|
||||
}
|
||||
mavenPublishing {
|
||||
publishToMavenCentral(com.vanniktech.maven.publish.SonatypeHost.S01, false)
|
||||
signAllPublications()
|
||||
}
|
||||
|
||||
mavenPublishing {
|
||||
pom {
|
||||
url = 'http://www.alphacephei.com.com/vosk/'
|
||||
licenses {
|
||||
license {
|
||||
name = 'The Apache License, Version 2.0'
|
||||
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
|
||||
}
|
||||
}
|
||||
developers {
|
||||
developer {
|
||||
id = 'com.alphacephei'
|
||||
name = 'Alpha Cephei Inc'
|
||||
email = 'contact@alphacephei.com'
|
||||
}
|
||||
}
|
||||
scm {
|
||||
connection = 'scm:git:git://github.com/alphacep/vosk-api.git'
|
||||
url = 'https://github.com/alphacep/vosk-api/'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+11
-27
@@ -3,14 +3,15 @@ def pomName = "Vosk Android"
|
||||
def pomDescription = "Vosk speech recognition library for Android"
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
namespace 'org.vosk'
|
||||
compileSdkVersion 33
|
||||
defaultConfig {
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 29
|
||||
versionCode 6
|
||||
targetSdkVersion 33
|
||||
versionCode 10
|
||||
versionName = version
|
||||
archivesBaseName = archiveName
|
||||
ndkVersion = "22.1.7171670"
|
||||
ndkVersion = "25.2.9519653"
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
@@ -24,32 +25,15 @@ task buildVosk(type: Exec) {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api 'net.java.dev.jna:jna:4.4.0@aar'
|
||||
api 'net.java.dev.jna:jna:5.13.0@aar'
|
||||
}
|
||||
|
||||
//preBuild.dependsOn buildVosk
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
aar(MavenPublication) {
|
||||
artifactId = archiveName
|
||||
artifact("$buildDir/outputs/aar/$archiveName-release.aar")
|
||||
pom {
|
||||
name = pomName
|
||||
description = pomDescription
|
||||
}
|
||||
//generate pom nodes for dependencies
|
||||
pom.withXml {
|
||||
def dependenciesNode = asNode().appendNode('dependencies')
|
||||
configurations.implementation.allDependencies.each { dependency ->
|
||||
if (dependency.name != 'unspecified') {
|
||||
def dependencyNode = dependenciesNode.appendNode('dependency')
|
||||
dependencyNode.appendNode('groupId', dependency.group)
|
||||
dependencyNode.appendNode('artifactId', dependency.name)
|
||||
dependencyNode.appendNode('version', dependency.version)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mavenPublishing {
|
||||
coordinates("com.alphacephei", archiveName, version)
|
||||
pom {
|
||||
name = pomName
|
||||
description = pomDescription
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.vosk">
|
||||
<manifest>
|
||||
</manifest>
|
||||
@@ -52,10 +52,20 @@ public class LibVosk {
|
||||
|
||||
public static native String vosk_recognizer_partial_result(Pointer recognizer);
|
||||
|
||||
public static native void vosk_recognizer_set_grm(Pointer recognizer, String grammar);
|
||||
|
||||
public static native void vosk_recognizer_reset(Pointer recognizer);
|
||||
|
||||
public static native void vosk_recognizer_free(Pointer recognizer);
|
||||
|
||||
/**
|
||||
* Set log level for Kaldi messages.
|
||||
*
|
||||
* @param loglevel the level
|
||||
* 0 - default value to print info and error messages but no debug
|
||||
* less than 0 - don't print info messages
|
||||
* greater than 0 - more verbose mode
|
||||
*/
|
||||
public static void setLogLevel(LogLevel loglevel) {
|
||||
vosk_set_log_level(loglevel.getValue());
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package org.vosk;
|
||||
|
||||
import java.io.IOException;
|
||||
import com.sun.jna.PointerType;
|
||||
|
||||
public class Model extends PointerType implements AutoCloseable {
|
||||
public Model() {
|
||||
}
|
||||
|
||||
public Model(String path) {
|
||||
public Model(String path) throws IOException {
|
||||
super(LibVosk.vosk_model_new(path));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a model");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,36 +1,163 @@
|
||||
package org.vosk;
|
||||
|
||||
import com.sun.jna.PointerType;
|
||||
import java.io.IOException;
|
||||
|
||||
public class Recognizer extends PointerType implements AutoCloseable {
|
||||
public Recognizer(Model model, float sampleRate) {
|
||||
/**
|
||||
* Creates the recognizer object.
|
||||
*
|
||||
* The recognizers process the speech and return text using shared model data
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new(model, sampleRate));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a recognizer");
|
||||
}
|
||||
}
|
||||
|
||||
public Recognizer(Model model, float sampleRate, SpeakerModel spkModel) {
|
||||
/**
|
||||
* Creates the recognizer object with speaker recognition.
|
||||
*
|
||||
* With the speaker recognition mode the recognizer not just recognize
|
||||
* text but also return speaker vectors one can use for speaker identification
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param spkModel speaker model for speaker identification
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate, SpeakerModel spkModel) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new_spk(model.getPointer(), sampleRate, spkModel.getPointer()));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a recognizer");
|
||||
}
|
||||
}
|
||||
|
||||
public Recognizer(Model model, float sampleRate, String grammar) {
|
||||
/**
|
||||
* Creates the recognizer object with the phrase list.
|
||||
*
|
||||
* Sometimes when you want to improve recognition accuracy and when you don't need
|
||||
* to recognize large vocabulary you can specify a list of phrases to recognize. This
|
||||
* will improve recognizer speed and accuracy but might return [unk] if user said
|
||||
* something different.
|
||||
*
|
||||
* Only recognizers with lookahead models support this type of quick configuration.
|
||||
* Precompiled HCLG graph models are not supported.
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param grammar The string with the list of phrases to recognize as JSON array of strings,
|
||||
* for example "["one two three four five", "[unk]"]".
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate, String grammar) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new_grm(model.getPointer(), sampleRate, grammar));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a recognizer");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures recognizer to output n-best results.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "alternatives": [
|
||||
* { "text": "one two three four five", "confidence": 0.97 },
|
||||
* { "text": "one two three for five", "confidence": 0.03 },
|
||||
* ]
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param maxAlternatives - maximum alternatives to return from recognition results
|
||||
*/
|
||||
public void setMaxAlternatives(int maxAlternatives) {
|
||||
LibVosk.vosk_recognizer_set_max_alternatives(this.getPointer(), maxAlternatives);
|
||||
}
|
||||
|
||||
/** Enables words with times in the output
|
||||
*
|
||||
* <pre>
|
||||
* "result" : [{
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.110000,
|
||||
* "start" : 0.870000,
|
||||
* "word" : "what"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.530000,
|
||||
* "start" : 1.110000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.950000,
|
||||
* "start" : 1.530000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.340000,
|
||||
* "start" : 1.950000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.610000,
|
||||
* "start" : 2.340000,
|
||||
* "word" : "one"
|
||||
* }],
|
||||
* </pre>
|
||||
*
|
||||
* @param words - boolean value
|
||||
*/
|
||||
public void setWords(boolean words) {
|
||||
LibVosk.vosk_recognizer_set_words(this.getPointer(), words);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like above return words and confidences in partial results.
|
||||
*
|
||||
* @param partial_words - boolean value
|
||||
*/
|
||||
public void setPartialWords(boolean partial_words) {
|
||||
LibVosk.vosk_recognizer_set_partial_words(this.getPointer(), partial_words);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds speaker model to already initialized recognizer.
|
||||
*
|
||||
* Can add speaker recognition model to already created recognizer.
|
||||
* Helps to initialize speaker recognition for grammar-based recognizer.
|
||||
*
|
||||
* @param spkModel Speaker recognition model
|
||||
*/
|
||||
public void setSpeakerModel(SpeakerModel spkModel) {
|
||||
LibVosk.vosk_recognizer_set_spk_model(this.getPointer(), spkModel.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept and process new chunk of voice data.
|
||||
*
|
||||
* @param data - audio data in PCM 16-bit mono format
|
||||
* @param len - length of the audio data
|
||||
* @return 1 if silence is occurred and you can retrieve a new utterance with result method
|
||||
* 0 if decoding continues
|
||||
* -1 if exception occurred
|
||||
*/
|
||||
public boolean acceptWaveForm(byte[] data, int len) {
|
||||
return LibVosk.vosk_recognizer_accept_waveform(this.getPointer(), data, len);
|
||||
}
|
||||
@@ -43,22 +170,76 @@ public class Recognizer extends PointerType implements AutoCloseable {
|
||||
return LibVosk.vosk_recognizer_accept_waveform_f(this.getPointer(), data, len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns speech recognition result
|
||||
*
|
||||
* @return the result in JSON format which contains decoded line, decoded
|
||||
* words, times in seconds and confidences. You can parse this result
|
||||
* with any json parser
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "text" : "what zero zero zero one"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* If alternatives enabled it returns result with alternatives, see also #setMaxAlternatives().
|
||||
*
|
||||
* If word times enabled returns word time, see also #setWordTimes().
|
||||
*/
|
||||
public String getResult() {
|
||||
return LibVosk.vosk_recognizer_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns partial speech recognition.
|
||||
*
|
||||
* @return partial speech recognition text which is not yet finalized.
|
||||
* result may change as recognizer process more data.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "partial" : "cyril one eight zero"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
public String getPartialResult() {
|
||||
return LibVosk.vosk_recognizer_partial_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns speech recognition result. Same as result, but doesn't wait for silence.
|
||||
* You usually call it in the end of the stream to get final bits of audio. It
|
||||
* flushes the feature pipeline, so all remaining audio chunks got processed.
|
||||
*
|
||||
* @return speech result in JSON format.
|
||||
*/
|
||||
public String getFinalResult() {
|
||||
return LibVosk.vosk_recognizer_final_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconfigures recognizer to use grammar.
|
||||
*
|
||||
* @param grammar Set of phrases in JSON array of strings or "[]" to use default model graph.
|
||||
* @see #Recognizer(Model, float, String)
|
||||
*/
|
||||
public void setGrammar(String grammar) {
|
||||
LibVosk.vosk_recognizer_set_grm(this.getPointer(), grammar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the recognizer.
|
||||
* Resets current results so the recognition can continue from scratch.
|
||||
*/
|
||||
public void reset() {
|
||||
LibVosk.vosk_recognizer_reset(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases recognizer object.
|
||||
* Underlying model is also unreferenced and if needed, released.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
LibVosk.vosk_recognizer_free(this.getPointer());
|
||||
|
||||
@@ -1,13 +1,36 @@
|
||||
package org.vosk;
|
||||
|
||||
import com.sun.jna.PointerType;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Helps to initialize speaker recognition for grammar-based recognizer.
|
||||
*/
|
||||
public class SpeakerModel extends PointerType implements AutoCloseable {
|
||||
public SpeakerModel() {
|
||||
}
|
||||
|
||||
public SpeakerModel(String path) {
|
||||
/**
|
||||
* Loads speaker model data from the file.
|
||||
*
|
||||
* The path must contain:
|
||||
* - a config file: mfcc.conf
|
||||
* - kaldi nnet: final.ext.raw
|
||||
* - mean.vec
|
||||
* - transform.mat
|
||||
*
|
||||
* @param path the path of the model on the filesystem
|
||||
* @throws IOException if the model could not be created
|
||||
*
|
||||
* @see <a href="http://kaldi-asr.org/doc/structkaldi_1_1MfccOptions.html">Kaldi MfccOptions</a>
|
||||
* @see <a href="http://kaldi-asr.org/doc/classkaldi_1_1nnet3_1_1Nnet.html">Kaldi Nnet</a>
|
||||
*/
|
||||
public SpeakerModel(String path) throws IOException {
|
||||
super(LibVosk.vosk_spk_model_new(path));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a speaker model");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -19,9 +19,9 @@ import android.media.AudioRecord;
|
||||
import android.media.MediaRecorder.AudioSource;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.annotation.SuppressLint;
|
||||
|
||||
import org.vosk.Recognizer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
@@ -48,6 +48,7 @@ public class SpeechService {
|
||||
*
|
||||
* @throws IOException thrown if audio recorder can not be created for some reason.
|
||||
*/
|
||||
@SuppressLint("MissingPermission")
|
||||
public SpeechService(Recognizer recognizer, float sampleRate) throws IOException {
|
||||
this.recognizer = recognizer;
|
||||
this.sampleRate = (int) sampleRate;
|
||||
|
||||
@@ -3,11 +3,12 @@ def pomName = "Vosk English Model"
|
||||
def pomDescription = "Small English model for Android"
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
namespace "org.vosk"
|
||||
compileSdkVersion 33
|
||||
defaultConfig {
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 29
|
||||
versionCode 6
|
||||
targetSdkVersion 33
|
||||
versionCode 10
|
||||
versionName = version
|
||||
archivesBaseName = archiveName
|
||||
}
|
||||
@@ -33,15 +34,10 @@ tasks.register('genUUID') {
|
||||
|
||||
preBuild.dependsOn(genUUID)
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
aar(MavenPublication) {
|
||||
artifactId = archiveName
|
||||
artifact("$buildDir/outputs/aar/$archiveName-release.aar")
|
||||
pom {
|
||||
name = pomName
|
||||
description = pomDescription
|
||||
}
|
||||
}
|
||||
mavenPublishing {
|
||||
coordinates("com.alphacephei", archiveName, version)
|
||||
pom {
|
||||
name = pomName
|
||||
description = pomDescription
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.vosk.model.en">
|
||||
<manifest>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
|
||||
namespace Vosk
|
||||
{
|
||||
public class BatchModel : global::System.IDisposable
|
||||
{
|
||||
private global::System.Runtime.InteropServices.HandleRef handle;
|
||||
|
||||
internal BatchModel(global::System.IntPtr cPtr)
|
||||
{
|
||||
handle = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
|
||||
}
|
||||
|
||||
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(BatchModel obj)
|
||||
{
|
||||
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.handle;
|
||||
}
|
||||
|
||||
~BatchModel()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
global::System.GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (handle.Handle != global::System.IntPtr.Zero)
|
||||
{
|
||||
VoskPINVOKE.delete_BatchModel(handle);
|
||||
handle = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public BatchModel(string model_path) : this(VoskPINVOKE.new_BatchModel(model_path))
|
||||
{
|
||||
}
|
||||
|
||||
public void WaitForCompletion()
|
||||
{
|
||||
if (handle.Handle != global::System.IntPtr.Zero)
|
||||
{
|
||||
VoskPINVOKE.wait_BatchModel(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
|
||||
namespace Vosk
|
||||
{
|
||||
public class VoskBatchRecognizer : System.IDisposable
|
||||
{
|
||||
private System.Runtime.InteropServices.HandleRef handle;
|
||||
|
||||
internal VoskBatchRecognizer(System.IntPtr cPtr)
|
||||
{
|
||||
handle = new System.Runtime.InteropServices.HandleRef(this, cPtr);
|
||||
}
|
||||
|
||||
internal static System.Runtime.InteropServices.HandleRef getCPtr(VoskBatchRecognizer obj)
|
||||
{
|
||||
return (obj == null) ? new System.Runtime.InteropServices.HandleRef(null, System.IntPtr.Zero) : obj.handle;
|
||||
}
|
||||
|
||||
~VoskBatchRecognizer()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
System.GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (handle.Handle != System.IntPtr.Zero)
|
||||
{
|
||||
VoskPINVOKE.delete_VoskBatchRecognizer(handle);
|
||||
handle = new System.Runtime.InteropServices.HandleRef(null, System.IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public VoskBatchRecognizer(BatchModel model, float sample_rate) : this(VoskPINVOKE.new_VoskBatchRecognizer(BatchModel.getCPtr(model), sample_rate))
|
||||
{
|
||||
}
|
||||
|
||||
public bool AcceptWaveform(byte[] data, int len)
|
||||
{
|
||||
return VoskPINVOKE.VoskBatchRecognizer_AcceptWaveform(handle, data, len);
|
||||
}
|
||||
|
||||
private static string PtrToStringUTF8(System.IntPtr ptr)
|
||||
{
|
||||
int len = 0;
|
||||
while (System.Runtime.InteropServices.Marshal.ReadByte(ptr, len) != 0)
|
||||
len++;
|
||||
byte[] array = new byte[len];
|
||||
System.Runtime.InteropServices.Marshal.Copy(ptr, array, 0, len);
|
||||
return System.Text.Encoding.UTF8.GetString(array);
|
||||
}
|
||||
|
||||
public string FrontResult()
|
||||
{
|
||||
return PtrToStringUTF8(VoskPINVOKE.VoskBatchRecognizer_FrontResult(handle));
|
||||
}
|
||||
|
||||
public string Result()
|
||||
{
|
||||
string result = PtrToStringUTF8(VoskPINVOKE.VoskBatchRecognizer_FrontResult(handle));
|
||||
VoskPINVOKE.VoskBatchRecognizer_Pop(handle);
|
||||
return result;
|
||||
}
|
||||
|
||||
public int GetNumPendingChunks()
|
||||
{
|
||||
return VoskPINVOKE.VoskBatchRecognizer_GetPendingChunks(handle);
|
||||
}
|
||||
|
||||
public void FinishStream()
|
||||
{
|
||||
VoskPINVOKE.VoskBatchRecognizer_FinishStream(handle);
|
||||
}
|
||||
|
||||
public void SetNLSML(bool nlsml)
|
||||
{
|
||||
VoskPINVOKE.VoskBatchRecognizer_SetNLSML(handle, Convert.ToInt32(nlsml));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,41 @@ class VoskPINVOKE {
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint="vosk_gpu_thread_init")]
|
||||
public static extern void GpuThreadInit();
|
||||
}
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_model_new")]
|
||||
public static extern global::System.IntPtr new_BatchModel(string jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_model_free")]
|
||||
public static extern void delete_BatchModel(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_model_wait")]
|
||||
public static extern void wait_BatchModel(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_new")]
|
||||
public static extern global::System.IntPtr new_VoskBatchRecognizer(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_free")]
|
||||
public static extern void delete_VoskBatchRecognizer(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_accept_waveform")]
|
||||
public static extern bool VoskBatchRecognizer_AcceptWaveform(global::System.Runtime.InteropServices.HandleRef jarg1, [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(global::System.Runtime.InteropServices.UnmanagedType.LPArray)] byte[] jarg2, int jarg3);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_set_nlsml")]
|
||||
public static extern void VoskBatchRecognizer_SetNLSML(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_finish_stream")]
|
||||
public static extern void VoskBatchRecognizer_FinishStream(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_front_result")]
|
||||
public static extern global::System.IntPtr VoskBatchRecognizer_FrontResult(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_pop")]
|
||||
public static extern void VoskBatchRecognizer_Pop(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
[global::System.Runtime.InteropServices.DllImport("libvosk", EntryPoint = "vosk_batch_recognizer_get_pending_chunks")]
|
||||
public static extern int VoskBatchRecognizer_GetPendingChunks(global::System.Runtime.InteropServices.HandleRef jarg1);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"encoding/json"
|
||||
|
||||
vosk "github.com/alphacep/vosk-api/go"
|
||||
)
|
||||
@@ -38,11 +37,10 @@ func main() {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
reader := bufio.NewReader(file)
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
for {
|
||||
_, err := reader.Read(buf)
|
||||
_, err := file.Read(buf)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
log.Fatal(err)
|
||||
|
||||
@@ -102,6 +102,13 @@ func (r *VoskRecognizer) SetSpkModel(spkModel *VoskSpkModel) {
|
||||
C.vosk_recognizer_set_spk_model(r.rec, spkModel.spkModel)
|
||||
}
|
||||
|
||||
// SetGrm sets which phrases to recognize on an already initialized recognizer.
|
||||
func (r *VoskRecognizer) SetGrm(grammar string) {
|
||||
cgrammar := C.CString(grammar)
|
||||
defer C.free(unsafe.Pointer(cgrammar))
|
||||
C.vosk_recognizer_set_grm(r.rec, cgrammar)
|
||||
}
|
||||
|
||||
// SetMaxAlternatives configures the recognizer to output n-best results.
|
||||
func (r *VoskRecognizer) SetMaxAlternatives(maxAlternatives int) {
|
||||
C.vosk_recognizer_set_max_alternatives(r.rec, C.int(maxAlternatives))
|
||||
|
||||
@@ -11,6 +11,5 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation group: 'net.java.dev.jna', name: 'jna', version: '5.7.0'
|
||||
implementation group: 'com.alphacephei', name: 'vosk', version: '0.3.40+'
|
||||
implementation group: 'com.alphacephei', name: 'vosk', version: '0.3.45'
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ mavenPublish {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api group: 'net.java.dev.jna', name: 'jna', version: '5.7.0'
|
||||
api group: 'net.java.dev.jna', name: 'jna', version: '5.13.0'
|
||||
testImplementation 'junit:junit:4.13'
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.vosk;
|
||||
|
||||
import com.sun.jna.Native;
|
||||
import com.sun.jna.Library;
|
||||
import com.sun.jna.Platform;
|
||||
import com.sun.jna.Pointer;
|
||||
import java.io.File;
|
||||
@@ -13,8 +12,9 @@ import java.nio.file.StandardCopyOption;
|
||||
public class LibVosk {
|
||||
|
||||
private static void unpackDll(File targetDir, String lib) throws IOException {
|
||||
InputStream source = LibVosk.class.getResourceAsStream("/win32-x86-64/" + lib + ".dll");
|
||||
Files.copy(source, new File(targetDir, lib + ".dll").toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
try (InputStream source = LibVosk.class.getResourceAsStream("/win32-x86-64/" + lib + ".dll")) {
|
||||
Files.copy(source, new File(targetDir, lib + ".dll").toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
@@ -23,7 +23,7 @@ public class LibVosk {
|
||||
// We have to unpack dependencies
|
||||
try {
|
||||
// To get a tmp folder we unpack small library and mark it for deletion
|
||||
File tmpFile = Native.extractFromResourcePath("/win32-x86-64/empty");
|
||||
File tmpFile = Native.extractFromResourcePath("/win32-x86-64/empty", LibVosk.class.getClassLoader());
|
||||
File tmpDir = tmpFile.getParentFile();
|
||||
new File(tmpDir, tmpFile.getName() + ".x").createNewFile();
|
||||
|
||||
@@ -78,10 +78,20 @@ public class LibVosk {
|
||||
|
||||
public static native String vosk_recognizer_partial_result(Pointer recognizer);
|
||||
|
||||
public static native void vosk_recognizer_set_grm(Pointer recognizer, String grammar);
|
||||
|
||||
public static native void vosk_recognizer_reset(Pointer recognizer);
|
||||
|
||||
public static native void vosk_recognizer_free(Pointer recognizer);
|
||||
|
||||
/**
|
||||
* Set log level for Kaldi messages.
|
||||
*
|
||||
* @param loglevel the level
|
||||
* 0 - default value to print info and error messages but no debug
|
||||
* less than 0 - don't print info messages
|
||||
* greater than 0 - more verbose mode
|
||||
*/
|
||||
public static void setLogLevel(LogLevel loglevel) {
|
||||
vosk_set_log_level(loglevel.getValue());
|
||||
}
|
||||
|
||||
@@ -4,6 +4,17 @@ import com.sun.jna.PointerType;
|
||||
import java.io.IOException;
|
||||
|
||||
public class Recognizer extends PointerType implements AutoCloseable {
|
||||
/**
|
||||
* Creates the recognizer object.
|
||||
*
|
||||
* The recognizers process the speech and return text using shared model data
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new(model, sampleRate));
|
||||
|
||||
@@ -12,30 +23,141 @@ public class Recognizer extends PointerType implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
public Recognizer(Model model, float sampleRate, SpeakerModel spkModel) {
|
||||
/**
|
||||
* Creates the recognizer object with speaker recognition.
|
||||
*
|
||||
* With the speaker recognition mode the recognizer not just recognize
|
||||
* text but also return speaker vectors one can use for speaker identification
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param spkModel speaker model for speaker identification
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate, SpeakerModel spkModel) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new_spk(model.getPointer(), sampleRate, spkModel.getPointer()));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a recognizer");
|
||||
}
|
||||
}
|
||||
|
||||
public Recognizer(Model model, float sampleRate, String grammar) {
|
||||
/**
|
||||
* Creates the recognizer object with the phrase list.
|
||||
*
|
||||
* Sometimes when you want to improve recognition accuracy and when you don't need
|
||||
* to recognize large vocabulary you can specify a list of phrases to recognize. This
|
||||
* will improve recognizer speed and accuracy but might return [unk] if user said
|
||||
* something different.
|
||||
*
|
||||
* Only recognizers with lookahead models support this type of quick configuration.
|
||||
* Precompiled HCLG graph models are not supported.
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you are going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param grammar The string with the list of phrases to recognize as JSON array of strings,
|
||||
* for example "["one two three four five", "[unk]"]".
|
||||
* @throws IOException if the recognizer could not be created
|
||||
*/
|
||||
public Recognizer(Model model, float sampleRate, String grammar) throws IOException {
|
||||
super(LibVosk.vosk_recognizer_new_grm(model.getPointer(), sampleRate, grammar));
|
||||
|
||||
if (getPointer() == null) {
|
||||
throw new IOException("Failed to create a recognizer");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures recognizer to output n-best results.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "alternatives": [
|
||||
* { "text": "one two three four five", "confidence": 0.97 },
|
||||
* { "text": "one two three for five", "confidence": 0.03 },
|
||||
* ]
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param maxAlternatives - maximum alternatives to return from recognition results
|
||||
*/
|
||||
public void setMaxAlternatives(int maxAlternatives) {
|
||||
LibVosk.vosk_recognizer_set_max_alternatives(this.getPointer(), maxAlternatives);
|
||||
}
|
||||
|
||||
/** Enables words with times in the output
|
||||
*
|
||||
* <pre>
|
||||
* "result" : [{
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.110000,
|
||||
* "start" : 0.870000,
|
||||
* "word" : "what"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.530000,
|
||||
* "start" : 1.110000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.950000,
|
||||
* "start" : 1.530000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.340000,
|
||||
* "start" : 1.950000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.610000,
|
||||
* "start" : 2.340000,
|
||||
* "word" : "one"
|
||||
* }],
|
||||
* </pre>
|
||||
*
|
||||
* @param words - boolean value
|
||||
*/
|
||||
public void setWords(boolean words) {
|
||||
LibVosk.vosk_recognizer_set_words(this.getPointer(), words);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like above return words and confidences in partial results.
|
||||
*
|
||||
* @param partial_words - boolean value
|
||||
*/
|
||||
public void setPartialWords(boolean partial_words) {
|
||||
LibVosk.vosk_recognizer_set_partial_words(this.getPointer(), partial_words);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds speaker model to already initialized recognizer.
|
||||
*
|
||||
* Can add speaker recognition model to already created recognizer.
|
||||
* Helps to initialize speaker recognition for grammar-based recognizer.
|
||||
*
|
||||
* @param spkModel Speaker recognition model
|
||||
*/
|
||||
public void setSpeakerModel(SpeakerModel spkModel) {
|
||||
LibVosk.vosk_recognizer_set_spk_model(this.getPointer(), spkModel.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept and process new chunk of voice data.
|
||||
*
|
||||
* @param data - audio data in PCM 16-bit mono format
|
||||
* @param len - length of the audio data
|
||||
* @return 1 if silence is occurred and you can retrieve a new utterance with result method
|
||||
* 0 if decoding continues
|
||||
* -1 if exception occurred
|
||||
*/
|
||||
public boolean acceptWaveForm(byte[] data, int len) {
|
||||
return LibVosk.vosk_recognizer_accept_waveform(this.getPointer(), data, len);
|
||||
}
|
||||
@@ -48,22 +170,76 @@ public class Recognizer extends PointerType implements AutoCloseable {
|
||||
return LibVosk.vosk_recognizer_accept_waveform_f(this.getPointer(), data, len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns speech recognition result
|
||||
*
|
||||
* @return the result in JSON format which contains decoded line, decoded
|
||||
* words, times in seconds and confidences. You can parse this result
|
||||
* with any json parser
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "text" : "what zero zero zero one"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* If alternatives enabled it returns result with alternatives, see also #setMaxAlternatives().
|
||||
*
|
||||
* If word times enabled returns word time, see also #setWordTimes().
|
||||
*/
|
||||
public String getResult() {
|
||||
return LibVosk.vosk_recognizer_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns partial speech recognition.
|
||||
*
|
||||
* @return partial speech recognition text which is not yet finalized.
|
||||
* result may change as recognizer process more data.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "partial" : "cyril one eight zero"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
public String getPartialResult() {
|
||||
return LibVosk.vosk_recognizer_partial_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns speech recognition result. Same as result, but doesn't wait for silence.
|
||||
* You usually call it in the end of the stream to get final bits of audio. It
|
||||
* flushes the feature pipeline, so all remaining audio chunks got processed.
|
||||
*
|
||||
* @return speech result in JSON format.
|
||||
*/
|
||||
public String getFinalResult() {
|
||||
return LibVosk.vosk_recognizer_final_result(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconfigures recognizer to use grammar.
|
||||
*
|
||||
* @param grammar Set of phrases in JSON array of strings or "[]" to use default model graph.
|
||||
* @see #Recognizer(Model, float, String)
|
||||
*/
|
||||
public void setGrammar(String grammar) {
|
||||
LibVosk.vosk_recognizer_set_grm(this.getPointer(), grammar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the recognizer.
|
||||
* Resets current results so the recognition can continue from scratch.
|
||||
*/
|
||||
public void reset() {
|
||||
LibVosk.vosk_recognizer_reset(this.getPointer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases recognizer object.
|
||||
* Underlying model is also unreferenced and if needed, released.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
LibVosk.vosk_recognizer_free(this.getPointer());
|
||||
|
||||
@@ -3,10 +3,28 @@ package org.vosk;
|
||||
import com.sun.jna.PointerType;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Helps to initialize speaker recognition for grammar-based recognizer.
|
||||
*/
|
||||
public class SpeakerModel extends PointerType implements AutoCloseable {
|
||||
public SpeakerModel() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads speaker model data from the file.
|
||||
*
|
||||
* The path must contain:
|
||||
* - a config file: mfcc.conf
|
||||
* - kaldi nnet: final.ext.raw
|
||||
* - mean.vec
|
||||
* - transform.mat
|
||||
*
|
||||
* @param path the path of the model on the filesystem
|
||||
* @throws IOException if the model could not be created
|
||||
*
|
||||
* @see <a href="http://kaldi-asr.org/doc/structkaldi_1_1MfccOptions.html">Kaldi MfccOptions</a>
|
||||
* @see <a href="http://kaldi-asr.org/doc/classkaldi_1_1nnet3_1_1Nnet.html">Kaldi Nnet</a>
|
||||
*/
|
||||
public SpeakerModel(String path) throws IOException {
|
||||
super(LibVosk.vosk_spk_model_new(path));
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.gradle/
|
||||
.idea/
|
||||
build/
|
||||
Generated
+3
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
Generated
+1
@@ -0,0 +1 @@
|
||||
vosk-api-kotlin
|
||||
Generated
+127
@@ -0,0 +1,127 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<code_scheme name="Project" version="173">
|
||||
<JetCodeStyleSettings>
|
||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||
</JetCodeStyleSettings>
|
||||
<codeStyleSettings language="XML">
|
||||
<option name="FORCE_REARRANGE_MODE" value="1" />
|
||||
<indentOptions>
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="4" />
|
||||
</indentOptions>
|
||||
<arrangement>
|
||||
<rules>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>xmlns:android</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>xmlns:.*</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
<order>BY_NAME</order>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>.*:id</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>.*:name</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>name</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>style</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>.*</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
<order>BY_NAME</order>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>.*</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
<order>ANDROID_ATTRIBUTE_ORDER</order>
|
||||
</rule>
|
||||
</section>
|
||||
<section>
|
||||
<rule>
|
||||
<match>
|
||||
<AND>
|
||||
<NAME>.*</NAME>
|
||||
<XML_ATTRIBUTE />
|
||||
<XML_NAMESPACE>.*</XML_NAMESPACE>
|
||||
</AND>
|
||||
</match>
|
||||
<order>BY_NAME</order>
|
||||
</rule>
|
||||
</section>
|
||||
</rules>
|
||||
</arrangement>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="kotlin">
|
||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||
<indentOptions>
|
||||
<option name="USE_TAB_CHARACTER" value="true" />
|
||||
<option name="SMART_TABS" value="true" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
</component>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
||||
</state>
|
||||
</component>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="11" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<component name="CopyrightManager">
|
||||
<copyright>
|
||||
<option name="notice" value="Copyright &#36;today.year Alpha Cephei Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." />
|
||||
<option name="myName" value="Apache-2.0" />
|
||||
</copyright>
|
||||
</component>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<component name="CopyrightManager">
|
||||
<settings default="Apache-2.0">
|
||||
<module2copyright>
|
||||
<element module="All" copyright="Apache-2.0" />
|
||||
</module2copyright>
|
||||
</settings>
|
||||
</component>
|
||||
Generated
+18
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="testRunner" value="GRADLE" />
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+25
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="jboss.community" />
|
||||
<option name="name" value="JBoss Community repository" />
|
||||
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="MavenRepo" />
|
||||
<option name="name" value="MavenRepo" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="Google" />
|
||||
<option name="name" value="Google" />
|
||||
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
|
||||
</remote-repository>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="Embedded JDK" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1 @@
|
||||
Doomsdayrs doomsdayrs@gmail.com
|
||||
@@ -0,0 +1,8 @@
|
||||
# Maintenance
|
||||
|
||||
To maintain this module, please ensure the following.
|
||||
1. Kotlin version is kept up to date.
|
||||
This will be found in the plugins block of the [build.gradle.kts](./build.gradle.kts).
|
||||
Ensure both multiplatform and serialization have the same value.
|
||||
2. Ensure dependencies are up to date
|
||||
3. Ensure that the android min & target sdks are up to date.
|
||||
@@ -0,0 +1,63 @@
|
||||
# vosk-api-kotlin
|
||||
|
||||
The vosk-api wrapped using Kotlin Multiplatform.
|
||||
|
||||
## Usage
|
||||
|
||||
The following are ways to use this wrapper.
|
||||
|
||||
### JVM
|
||||
|
||||
For Java & Android targets.
|
||||
|
||||
```kotlin
|
||||
dependencoes {
|
||||
val voskVersion = "0.4.0-alpha0"
|
||||
|
||||
// Generic
|
||||
implementation("com.alphacephei:vosk-api-kotlin:$voskVersion")
|
||||
|
||||
// Android
|
||||
implementation("com.alphacephei:vosk-api-kotlin-android:$voskVersion")
|
||||
}
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To build this project, follow the following steps.
|
||||
|
||||
1. Install `libvosk`.
|
||||
This can be done from [source][source install] (parent monorepo)
|
||||
or [downloaded][download].
|
||||
2. Download a [Vosk model](https://alphacephei.com/vosk/models) to use.
|
||||
- It is suggested to use a small model to speed up tests.
|
||||
3. Once both are downloaded and placed into a proper location (hopefully following UNIX specification).
|
||||
Set the following environment variables:
|
||||
- `VOSK_MODEL` to the path of the model.
|
||||
- `VOSK_PATH` to the path of `libvosk`.
|
||||
These are used by the various tests to operate.
|
||||
4. Now that the required steps are complete, one can run `./gradlew build`.
|
||||
|
||||
## Kotlin/Native
|
||||
|
||||
Currently, the native target is disabled due to a lack of vosk-api packaging on platforms.
|
||||
Further worsened by the fact that installing the vosk-api on Linux systems is a chore.
|
||||
|
||||
First, either install from [source][source install]
|
||||
or [download][download] and install into the proper unix directories as expected in
|
||||
[libvosk.def](./src/nativeInterop/cinterop/libvosk.def).
|
||||
|
||||
To enable development for Kotlin/Native, do either for the following.
|
||||
- Add `NATIVE_EXPERIMENT=true` to your environment.
|
||||
- Go into [build.gradle.kts](./build.gradle.kts) & find `enableNative` & set the right side to true.
|
||||
|
||||
Afterwards, when syncing the project, the native source sets will become available to work on.
|
||||
It is suggested to run `cinteropLibvoskNative` to generate the Kotlin C bindings to work with.
|
||||
|
||||
## Future
|
||||
|
||||
- Possibly target Kotlin/JS
|
||||
- Possibly target Kotlin/Objective-C (?)
|
||||
|
||||
[source install]: https://alphacephei.com/vosk/install
|
||||
[download]: https://github.com/alphacep/vosk-api/releases/latest
|
||||
@@ -0,0 +1,190 @@
|
||||
import org.jetbrains.dokka.gradle.DokkaTask
|
||||
import org.jetbrains.kotlin.config.JvmTarget
|
||||
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
kotlin("multiplatform") version "1.8.10"
|
||||
id("com.android.library")
|
||||
`maven-publish`
|
||||
id("org.jetbrains.dokka") version "1.7.20"
|
||||
kotlin("plugin.serialization") version "1.8.10"
|
||||
}
|
||||
|
||||
group = "com.alphacephei"
|
||||
version = "0.4.0-alpha0"
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
val dokkaOutputDir = "$buildDir/dokka"
|
||||
|
||||
tasks.getByName<DokkaTask>("dokkaHtml") {
|
||||
outputDirectory.set(file(dokkaOutputDir))
|
||||
}
|
||||
|
||||
val deleteDokkaOutputDir by tasks.register<Delete>("deleteDokkaOutputDirectory") {
|
||||
delete(dokkaOutputDir)
|
||||
}
|
||||
|
||||
val javadocJar = tasks.register<Jar>("javadocJar") {
|
||||
dependsOn(deleteDokkaOutputDir, tasks.dokkaHtml)
|
||||
archiveClassifier.set("javadoc")
|
||||
from(dokkaOutputDir)
|
||||
}
|
||||
|
||||
fun org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension.native(
|
||||
configure: org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithHostTests.() -> Unit = {}
|
||||
) {
|
||||
when {
|
||||
org.jetbrains.kotlin.konan.target.HostManager.hostIsMingw -> mingwX64("native")
|
||||
org.jetbrains.kotlin.konan.target.HostManager.hostIsLinux -> linuxX64("native")
|
||||
org.jetbrains.kotlin.konan.target.HostManager.hostIsMac -> if (org.jetbrains.kotlin.konan.target.HostManager.hostArch() == "arm64") {
|
||||
macosArm64("native")
|
||||
} else {
|
||||
macosX64("native")
|
||||
}
|
||||
|
||||
else -> error("Unsupported Host OS: ${org.jetbrains.kotlin.konan.target.HostManager.hostOs()}")
|
||||
}.apply(configure)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvm {
|
||||
compilations.all {
|
||||
kotlinOptions.jvmTarget = JvmTarget.JVM_11.description
|
||||
}
|
||||
testRuns["test"].executionTask.configure {
|
||||
useJUnitPlatform()
|
||||
environment("MODEL", "VOSK_MODEL")
|
||||
//environment("MODEL", "/home/doomsdayrs/Downloads/vosk-model-small-en-us-0.15/")
|
||||
environment("LIBRARY", "VOSK_PATH")
|
||||
//environment("LIBRARY", "/usr/local/lib64/libvosk/libvosk.so")
|
||||
environment("AUDIO", "$projectDir/../python/example/test.wav")
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
publishAllLibraryVariants()
|
||||
}
|
||||
|
||||
/**
|
||||
* If native target should be enabled or not.
|
||||
*
|
||||
* Currently disabled as there is no proper packaging distribution currently.
|
||||
*/
|
||||
@Suppress("SimplifyBooleanWithConstants") // Ignore, the false is for overrides
|
||||
val enableNative = System.getenv("NATIVE_EXPERIMENT") == "true" || false
|
||||
|
||||
if (enableNative)
|
||||
native {
|
||||
val main by compilations.getting
|
||||
val libvosk by main.cinterops.creating
|
||||
|
||||
binaries {
|
||||
sharedLib()
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
withType<MavenPublication> {
|
||||
artifact(javadocJar)
|
||||
pom {
|
||||
url.set("http://www.alphacephei.com.com/vosk/")
|
||||
licenses {
|
||||
license {
|
||||
name.set("The Apache License, Version 2.0")
|
||||
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
|
||||
}
|
||||
}
|
||||
developers {
|
||||
developer {
|
||||
id.set("com.alphacephei")
|
||||
name.set("Alpha Cephei Inc")
|
||||
email.set("contact@alphacephei.com")
|
||||
}
|
||||
}
|
||||
scm {
|
||||
connection.set("scm:git:git://github.com/alphacep/vosk-api.git")
|
||||
url.set("https://github.com/alphacep/vosk-api/")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val jna_version = "5.13.0"
|
||||
val coroutines_version = "1.6.4"
|
||||
|
||||
sourceSets {
|
||||
val commonMain by getting {
|
||||
dependencies {
|
||||
api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
|
||||
api("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version")
|
||||
}
|
||||
}
|
||||
val commonTest by getting {
|
||||
dependencies {
|
||||
implementation(kotlin("test"))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version")
|
||||
}
|
||||
}
|
||||
val jvmMain by getting {
|
||||
dependencies {
|
||||
api("net.java.dev.jna:jna:$jna_version")
|
||||
}
|
||||
}
|
||||
val jvmTest by getting
|
||||
if (enableNative) {
|
||||
val nativeMain by getting
|
||||
}
|
||||
val androidMain by getting {
|
||||
dependsOn(jvmMain)
|
||||
dependencies {
|
||||
api("net.java.dev.jna:jna:$jna_version@aar")
|
||||
}
|
||||
}
|
||||
val androidTest by getting {
|
||||
dependencies {
|
||||
implementation("junit:junit:4.13.2")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdk = 33
|
||||
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
targetSdk = 33
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
publishing {
|
||||
multipleVariants {
|
||||
withSourcesJar()
|
||||
withJavadocJar()
|
||||
allVariants()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
gradlePluginPortal()
|
||||
mavenCentral()
|
||||
}
|
||||
resolutionStrategy {
|
||||
eachPlugin {
|
||||
if (requested.id.namespace == "com.android") {
|
||||
useModule("com.android.tools.build:gradle:7.3.0")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rootProject.name = "vosk-api-kotlin"
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.alphacephei.library">
|
||||
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.vosk.android
|
||||
|
||||
/**
|
||||
* Interface to receive recognition results
|
||||
*/
|
||||
interface RecognitionListener {
|
||||
/**
|
||||
* Called when partial recognition result is available.
|
||||
*/
|
||||
fun onPartialResult(hypothesis: String)
|
||||
|
||||
/**
|
||||
* Called after silence occured.
|
||||
*/
|
||||
fun onResult(hypothesis: String)
|
||||
|
||||
/**
|
||||
* Called after stream end.
|
||||
*/
|
||||
fun onFinalResult(hypothesis: String)
|
||||
|
||||
/**
|
||||
* Called when an error occurs.
|
||||
*/
|
||||
fun onError(exception: Exception)
|
||||
|
||||
/**
|
||||
* Called after timeout expired
|
||||
*/
|
||||
fun onTimeout()
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.vosk.android
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaRecorder.AudioSource
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import org.vosk.Recognizer
|
||||
import java.io.IOException
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Service that records audio in a thread, passes it to a recognizer and emits
|
||||
* recognition results. Recognition events are passed to a client using
|
||||
* [RecognitionListener]
|
||||
*/
|
||||
class SpeechService @Throws(IOException::class) constructor(
|
||||
private val recognizer: Recognizer,
|
||||
sampleRate: Float
|
||||
) {
|
||||
private val sampleRate: Int
|
||||
private val bufferSize: Int
|
||||
private val recorder: AudioRecord
|
||||
private var recognizerThread: RecognizerThread? = null
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* Creates speech service. Service holds the AudioRecord object, so you
|
||||
* need to call [.shutdown] in order to properly finalize it.
|
||||
*
|
||||
* @throws IOException thrown if audio recorder can not be created for some reason.
|
||||
*/
|
||||
init {
|
||||
this.sampleRate = sampleRate.toInt()
|
||||
bufferSize = (this.sampleRate * BUFFER_SIZE_SECONDS).roundToInt()
|
||||
@SuppressLint("MissingPermission")
|
||||
recorder = AudioRecord(
|
||||
AudioSource.VOICE_RECOGNITION, this.sampleRate,
|
||||
AudioFormat.CHANNEL_IN_MONO,
|
||||
AudioFormat.ENCODING_PCM_16BIT, bufferSize * 2
|
||||
)
|
||||
if (recorder.state == AudioRecord.STATE_UNINITIALIZED) {
|
||||
recorder.release()
|
||||
throw IOException(
|
||||
"Failed to initialize recorder. Microphone might be already in use."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recognition. Does nothing if recognition is active.
|
||||
*
|
||||
* @return true if recognition was actually started
|
||||
*/
|
||||
fun startListening(listener: RecognitionListener): Boolean {
|
||||
if (null != recognizerThread) return false
|
||||
recognizerThread = RecognizerThread(listener)
|
||||
recognizerThread!!.start()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recognition. After specified timeout listening stops and the
|
||||
* endOfSpeech signals about that. Does nothing if recognition is active.
|
||||
*
|
||||
*
|
||||
* timeout - timeout in milliseconds to listen.
|
||||
*
|
||||
* @return true if recognition was actually started
|
||||
*/
|
||||
fun startListening(listener: RecognitionListener, timeout: Int): Boolean {
|
||||
if (null != recognizerThread) return false
|
||||
recognizerThread = RecognizerThread(listener, timeout)
|
||||
recognizerThread!!.start()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun stopRecognizerThread(): Boolean {
|
||||
if (null == recognizerThread) return false
|
||||
try {
|
||||
recognizerThread!!.interrupt()
|
||||
recognizerThread!!.join()
|
||||
} catch (e: InterruptedException) {
|
||||
// Restore the interrupted status.
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
recognizerThread = null
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops recognition. Listener should receive final result if there is
|
||||
* any. Does nothing if recognition is not active.
|
||||
*
|
||||
* @return true if recognition was actually stopped
|
||||
*/
|
||||
fun stop(): Boolean {
|
||||
return stopRecognizerThread()
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel recognition. Do not post any new events, simply cancel processing.
|
||||
* Does nothing if recognition is not active.
|
||||
*
|
||||
* @return true if recognition was actually stopped
|
||||
*/
|
||||
fun cancel(): Boolean {
|
||||
if (recognizerThread != null) {
|
||||
recognizerThread!!.setPause(true)
|
||||
}
|
||||
return stopRecognizerThread()
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown the recognizer and release the recorder
|
||||
*/
|
||||
fun shutdown() {
|
||||
recorder.release()
|
||||
}
|
||||
|
||||
fun setPause(paused: Boolean) {
|
||||
if (recognizerThread != null) {
|
||||
recognizerThread!!.setPause(paused)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets recognizer in a thread, starts recognition over again
|
||||
*/
|
||||
fun reset() {
|
||||
if (recognizerThread != null) {
|
||||
recognizerThread!!.reset()
|
||||
}
|
||||
}
|
||||
|
||||
private inner class RecognizerThread @JvmOverloads constructor(
|
||||
var listener: RecognitionListener,
|
||||
timeout: Int = Companion.NO_TIMEOUT
|
||||
) : Thread() {
|
||||
private var remainingSamples: Int
|
||||
private val timeoutSamples: Int
|
||||
|
||||
@Volatile
|
||||
private var paused = false
|
||||
|
||||
@Volatile
|
||||
private var reset = false
|
||||
|
||||
init {
|
||||
timeoutSamples = if (timeout != Companion.NO_TIMEOUT) {
|
||||
timeout * sampleRate / 1000
|
||||
} else {
|
||||
Companion.NO_TIMEOUT
|
||||
}
|
||||
remainingSamples = timeoutSamples
|
||||
}
|
||||
|
||||
/**
|
||||
* When we are paused, don't process audio by the recognizer and don't emit
|
||||
* any listener results
|
||||
*
|
||||
* @param paused the status of pause
|
||||
*/
|
||||
fun setPause(paused: Boolean) {
|
||||
this.paused = paused
|
||||
}
|
||||
|
||||
/**
|
||||
* Set reset state to signal reset of the recognizer and start over
|
||||
*/
|
||||
fun reset() {
|
||||
reset = true
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
recorder.startRecording()
|
||||
if (recorder.recordingState == AudioRecord.RECORDSTATE_STOPPED) {
|
||||
recorder.stop()
|
||||
val ioe = IOException(
|
||||
"Failed to start recording. Microphone might be already in use."
|
||||
)
|
||||
mainHandler.post { listener.onError(ioe) }
|
||||
}
|
||||
val buffer = ShortArray(bufferSize)
|
||||
while (!interrupted()
|
||||
&& (timeoutSamples == Companion.NO_TIMEOUT || remainingSamples > 0)
|
||||
) {
|
||||
val nread = recorder.read(buffer, 0, buffer.size)
|
||||
if (paused) {
|
||||
continue
|
||||
}
|
||||
if (reset) {
|
||||
recognizer.reset()
|
||||
reset = false
|
||||
}
|
||||
if (nread < 0) throw RuntimeException("error reading audio buffer")
|
||||
if (recognizer.acceptWaveform(buffer)) {
|
||||
val result = recognizer.result
|
||||
mainHandler.post { listener.onResult(result) }
|
||||
} else {
|
||||
val partialResult = recognizer.partialResult
|
||||
mainHandler.post { listener.onPartialResult(partialResult) }
|
||||
}
|
||||
if (timeoutSamples != NO_TIMEOUT) {
|
||||
remainingSamples -= nread
|
||||
}
|
||||
}
|
||||
recorder.stop()
|
||||
if (!paused) {
|
||||
// If we met timeout signal that speech ended
|
||||
if (timeoutSamples != NO_TIMEOUT && remainingSamples <= 0) {
|
||||
mainHandler.post { listener.onTimeout() }
|
||||
} else {
|
||||
val finalResult = recognizer.finalResult
|
||||
mainHandler.post { listener.onFinalResult(finalResult) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val NO_TIMEOUT = -1
|
||||
private const val BUFFER_SIZE_SECONDS = 0.2f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.vosk.android
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import org.vosk.Recognizer
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Service that recognizes stream audio in a thread, passes it to a recognizer and emits
|
||||
* recognition results. Recognition events are passed to a client using
|
||||
* [RecognitionListener]
|
||||
*/
|
||||
class SpeechStreamService(
|
||||
private val recognizer: Recognizer,
|
||||
inputStream: InputStream,
|
||||
sampleRate: Float
|
||||
) {
|
||||
private val inputStream: InputStream
|
||||
private val sampleRate: Int
|
||||
private val bufferSize: Int
|
||||
private var recognizerThread: Thread? = null
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* Creates speech service.
|
||||
*/
|
||||
init {
|
||||
this.sampleRate = sampleRate.toInt()
|
||||
this.inputStream = inputStream
|
||||
bufferSize = (this.sampleRate * BUFFER_SIZE_SECONDS * 2).roundToInt()
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recognition. Does nothing if recognition is active.
|
||||
*
|
||||
* @return true if recognition was actually started
|
||||
*/
|
||||
fun start(listener: RecognitionListener): Boolean {
|
||||
if (null != recognizerThread) return false
|
||||
recognizerThread = RecognizerThread(listener)
|
||||
recognizerThread!!.start()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recognition. After specified timeout listening stops and the
|
||||
* endOfSpeech signals about that. Does nothing if recognition is active.
|
||||
*
|
||||
*
|
||||
* timeout - timeout in milliseconds to listen.
|
||||
*
|
||||
* @return true if recognition was actually started
|
||||
*/
|
||||
fun start(listener: RecognitionListener, timeout: Int): Boolean {
|
||||
if (null != recognizerThread) return false
|
||||
recognizerThread = RecognizerThread(listener, timeout)
|
||||
recognizerThread!!.start()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops recognition. All listeners should receive final result if there is
|
||||
* any. Does nothing if recognition is not active.
|
||||
*
|
||||
* @return true if recognition was actually stopped
|
||||
*/
|
||||
fun stop(): Boolean {
|
||||
if (null == recognizerThread) return false
|
||||
try {
|
||||
recognizerThread!!.interrupt()
|
||||
recognizerThread!!.join()
|
||||
} catch (e: InterruptedException) {
|
||||
// Restore the interrupted status.
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
recognizerThread = null
|
||||
return true
|
||||
}
|
||||
|
||||
private inner class RecognizerThread @JvmOverloads constructor(
|
||||
var listener: RecognitionListener,
|
||||
timeout: Int = Companion.NO_TIMEOUT
|
||||
) : Thread() {
|
||||
private var remainingSamples: Int
|
||||
private val timeoutSamples: Int
|
||||
|
||||
init {
|
||||
if (timeout != Companion.NO_TIMEOUT) timeoutSamples =
|
||||
timeout * sampleRate / 1000 else timeoutSamples = Companion.NO_TIMEOUT
|
||||
remainingSamples = timeoutSamples
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
val buffer = ByteArray(bufferSize)
|
||||
while (!interrupted()
|
||||
&& (timeoutSamples == Companion.NO_TIMEOUT || remainingSamples > 0)
|
||||
) {
|
||||
try {
|
||||
val nread = inputStream.read(buffer, 0, buffer.size)
|
||||
if (nread < 0) {
|
||||
break
|
||||
} else {
|
||||
val isSilence: Boolean = recognizer.acceptWaveform(buffer)
|
||||
if (isSilence) {
|
||||
val result = recognizer.result
|
||||
mainHandler.post { listener.onResult(result) }
|
||||
} else {
|
||||
val partialResult = recognizer.partialResult
|
||||
mainHandler.post { listener.onPartialResult(partialResult) }
|
||||
}
|
||||
}
|
||||
if (timeoutSamples != NO_TIMEOUT) {
|
||||
remainingSamples -= nread
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
mainHandler.post { listener.onError(e) }
|
||||
}
|
||||
}
|
||||
|
||||
// If we met timeout signal that speech ended
|
||||
if (timeoutSamples != NO_TIMEOUT && remainingSamples <= 0) {
|
||||
mainHandler.post { listener.onTimeout() }
|
||||
} else {
|
||||
val finalResult = recognizer.finalResult
|
||||
mainHandler.post { listener.onFinalResult(finalResult) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val NO_TIMEOUT = -1
|
||||
private const val BUFFER_SIZE_SECONDS = 0.2f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.vosk.android
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.AssetManager
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import org.vosk.Model
|
||||
import java.io.*
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.function.Consumer
|
||||
|
||||
/**
|
||||
* Provides utility methods to sync model files to external storage to allow
|
||||
* C++ code access them. Relies on file named "uuid" to track updates.
|
||||
*/
|
||||
object StorageService {
|
||||
private val TAG = StorageService::class.simpleName
|
||||
|
||||
@JvmStatic
|
||||
fun unpack(
|
||||
context: Context,
|
||||
sourcePath: String,
|
||||
targetPath: String,
|
||||
completeCallback: Consumer<Model>,
|
||||
errorCallback: Consumer<IOException>
|
||||
) {
|
||||
val executor: Executor =
|
||||
Executors.newSingleThreadExecutor() // change according to your requirements
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
executor.execute {
|
||||
try {
|
||||
val outputPath = sync(context, sourcePath, targetPath)
|
||||
val model = Model(outputPath)
|
||||
handler.post { completeCallback.accept(model) }
|
||||
} catch (e: IOException) {
|
||||
handler.post { errorCallback.accept(e) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Throws(IOException::class)
|
||||
fun sync(context: Context, sourcePath: String, targetPath: String): String {
|
||||
val assetManager = context.assets
|
||||
val externalFilesDir = context.getExternalFilesDir(null)
|
||||
?: throw IOException(
|
||||
"cannot get external files dir, "
|
||||
+ "external storage state is " + Environment.getExternalStorageState()
|
||||
)
|
||||
val targetDir = File(externalFilesDir, targetPath)
|
||||
val resultPath = File(targetDir, sourcePath).absolutePath
|
||||
val sourceUUID = readLine(assetManager.open("$sourcePath/uuid"))
|
||||
try {
|
||||
val targetUUID = readLine(FileInputStream(File(targetDir, "$sourcePath/uuid")))
|
||||
if (targetUUID == sourceUUID) return resultPath
|
||||
} catch (e: FileNotFoundException) {
|
||||
// ignore
|
||||
}
|
||||
deleteContents(targetDir)
|
||||
copyAssets(assetManager, sourcePath, targetDir)
|
||||
|
||||
// Copy uuid
|
||||
copyFile(assetManager, "$sourcePath/uuid", targetDir)
|
||||
return resultPath
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun readLine(inputStream: InputStream): String {
|
||||
return BufferedReader(InputStreamReader(inputStream)).use { it.readLine() }
|
||||
}
|
||||
|
||||
private fun deleteContents(dir: File): Boolean {
|
||||
val files = dir.listFiles()
|
||||
var success = true
|
||||
if (files != null) {
|
||||
for (file in files) {
|
||||
if (file.isDirectory) {
|
||||
success = success and deleteContents(file)
|
||||
}
|
||||
if (!file.delete()) {
|
||||
success = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return success
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun copyAssets(assetManager: AssetManager, path: String, outPath: File) {
|
||||
val assets = assetManager.list(path) ?: return
|
||||
if (assets.isEmpty()) {
|
||||
if (!path.endsWith("uuid")) copyFile(assetManager, path, outPath)
|
||||
} else {
|
||||
val dir = File(outPath, path)
|
||||
if (!dir.exists()) {
|
||||
Log.v(TAG, "Making directory " + dir.absolutePath)
|
||||
if (!dir.mkdirs()) {
|
||||
Log.v(TAG, "Failed to create directory " + dir.absolutePath)
|
||||
}
|
||||
}
|
||||
for (asset in assets) {
|
||||
copyAssets(assetManager, "$path/$asset", outPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun copyFile(assetManager: AssetManager, fileName: String, outPath: File) {
|
||||
Log.v(TAG, "Copy $fileName to $outPath")
|
||||
assetManager.open(fileName).use { inputStream ->
|
||||
FileOutputStream("$outPath/$fileName").use { out ->
|
||||
val buffer = ByteArray(4000)
|
||||
var read: Int
|
||||
while (inputStream.read(buffer).also { read = it } != -1) {
|
||||
out.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* Thrown when a [Recognizer] cannot accept a given waveform
|
||||
*/
|
||||
class AcceptWaveformException(data: Any) : Exception("Could not accept waveform: $data")
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import org.vosk.exception.ModelException
|
||||
|
||||
/**
|
||||
* Batch model object
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Creates the batch recognizer object
|
||||
*/
|
||||
expect class BatchModel @Throws(ModelException::class) constructor(path: String) : Freeable {
|
||||
|
||||
/**
|
||||
* Releases batch model object
|
||||
*/
|
||||
override fun free()
|
||||
|
||||
/**
|
||||
* Wait for the processing
|
||||
*/
|
||||
fun await()
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* Batch recognizer object
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Creates batch recognizer object
|
||||
*/
|
||||
expect class BatchRecognizer constructor(model: BatchModel, sampleRate: Float) : Freeable {
|
||||
|
||||
/**
|
||||
* Releases batch recognizer object
|
||||
*/
|
||||
override fun free()
|
||||
|
||||
/**
|
||||
* Accept batch voice data
|
||||
*/
|
||||
fun acceptWaveform(data: ByteArray)
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
fun setNLSML(nlsml: Boolean)
|
||||
|
||||
/**
|
||||
* Closes the stream
|
||||
*/
|
||||
fun finishStream()
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*/
|
||||
val frontResult: String
|
||||
|
||||
/**
|
||||
* Release and free first retrieved result
|
||||
*/
|
||||
fun pop()
|
||||
|
||||
/**
|
||||
* Get amount of pending chunks for more intelligent waiting
|
||||
*/
|
||||
val pendingChunks: Int
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* Denotes an object that must be freed afterwards.
|
||||
*
|
||||
* On JVM, This is done via AutoClosable.
|
||||
*/
|
||||
@Suppress("SpellCheckingInspection")
|
||||
interface Freeable {
|
||||
|
||||
/**
|
||||
* Dereference the related object
|
||||
*/
|
||||
fun free()
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* Log level for Kaldi messages.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
enum class LogLevel(val value: Int) {
|
||||
|
||||
/**
|
||||
* Don't print info messages
|
||||
*/
|
||||
WARNINGS(-1),
|
||||
|
||||
/**
|
||||
* Default value to print info and error messages but no debug
|
||||
*/
|
||||
INFO(0),
|
||||
|
||||
/**
|
||||
* More verbose mode
|
||||
*/
|
||||
DEBUG(1);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import org.vosk.exception.IOException
|
||||
|
||||
|
||||
/**
|
||||
* Model stores all the data required for recognition
|
||||
*
|
||||
* It contains static data and can be shared across processing
|
||||
* threads.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Loads model data from the file and returns the model object
|
||||
* @param path the path of the model on the filesystem
|
||||
* @throws IOException if the path provided is invalid
|
||||
*/
|
||||
expect class Model @Throws(IOException::class) constructor(path: String) : Freeable {
|
||||
|
||||
/**
|
||||
* Check if a word can be recognized by the model
|
||||
* @param word: the word
|
||||
* @returns the word symbol if @param word exists inside the model
|
||||
* or -1 otherwise.
|
||||
* Reminding that word symbol 0 is for <epsilon>
|
||||
*/
|
||||
fun findWord(word: String): Int
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
override fun free()
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import org.vosk.exception.RecognizerException
|
||||
|
||||
/**
|
||||
* Recognizer object is the main object which processes data.
|
||||
*
|
||||
* Each recognizer usually runs in own thread and takes audio as input.
|
||||
* Once audio is processed recognizer returns JSON object as a string
|
||||
* which represent decoded information - words, confidences, times, n-best lists,
|
||||
* speaker information and so on
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
expect class Recognizer : Freeable {
|
||||
/**
|
||||
* Creates the recognizer object
|
||||
*
|
||||
* The recognizers process the speech and return text using shared model data
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
constructor(model: Model, sampleRate: Float)
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with speaker recognition
|
||||
*
|
||||
* With the speaker recognition mode the recognizer not just recognize
|
||||
* text but also return speaker vectors one can use for speaker identification
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param speakerModel speaker model for speaker identification
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
constructor(model: Model, sampleRate: Float, speakerModel: SpeakerModel)
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with the phrase list
|
||||
*
|
||||
* Sometimes when you want to improve recognition accuracy and when you don't need
|
||||
* to recognize large vocabulary you can specify a list of phrases to recognize. This
|
||||
* will improve recognizer speed and accuracy but might return [unk] if user said
|
||||
* something different.
|
||||
*
|
||||
* Only recognizers with lookahead models support this type of quick configuration.
|
||||
* Precompiled HCLG graph models are not supported.
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The valuesample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param grammar The string with the list of phrases to recognize as JSON array of strings,
|
||||
* for example "["one two three four five", "[unk]"]".
|
||||
*
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
constructor(model: Model, sampleRate: Float, grammar: String)
|
||||
|
||||
/**
|
||||
* Adds speaker model to already initialized recognizer
|
||||
*
|
||||
* Can add speaker recognition model to already created recognizer. Helps to initialize
|
||||
* speaker recognition for grammar-based recognizer.
|
||||
*
|
||||
* @param speakerModel Speaker recognition model
|
||||
*/
|
||||
fun setSpeakerModel(speakerModel: SpeakerModel)
|
||||
|
||||
|
||||
/**
|
||||
* Reconfigures recognizer to use grammar
|
||||
*
|
||||
* @param grammar Set of phrases in JSON array of strings or "[]" to use default model graph.
|
||||
* See also vosk_recognizer_new_grm
|
||||
*/
|
||||
fun setGrammar(grammar: String)
|
||||
|
||||
/**
|
||||
* Configures recognizer to output n-best results
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "alternatives": [
|
||||
* { "text": "one two three four five", "confidence": 0.97 },
|
||||
* { "text": "one two three for five", "confidence": 0.03 },
|
||||
* ]
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param maxAlternatives - maximum alternatives to return from recognition results
|
||||
*/
|
||||
fun setMaxAlternatives(maxAlternatives: Int)
|
||||
|
||||
/**
|
||||
* Enables words with times in the output
|
||||
*
|
||||
* <pre>
|
||||
* "result" : [{
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.110000,
|
||||
* "start" : 0.870000,
|
||||
* "word" : "what"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.530000,
|
||||
* "start" : 1.110000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.950000,
|
||||
* "start" : 1.530000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.340000,
|
||||
* "start" : 1.950000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.610000,
|
||||
* "start" : 2.340000,
|
||||
* "word" : "one"
|
||||
* }],
|
||||
* </pre>
|
||||
*
|
||||
* @param words - boolean value
|
||||
*/
|
||||
fun setOutputWordTimes(words: Boolean)
|
||||
|
||||
/**
|
||||
* Like [setOutputWordTimes] return words and confidences in partial results
|
||||
*
|
||||
* @param partialWords - boolean value
|
||||
*/
|
||||
fun setPartialWords(partialWords: Boolean)
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
fun setNLSML(nlsml: Boolean)
|
||||
|
||||
/**
|
||||
* Accept voice data
|
||||
*
|
||||
* accept and process new chunk of voice data
|
||||
*
|
||||
* @param data Audio data in PCM 16-bit mono format.
|
||||
* @param length Length of the audio data.
|
||||
* @returns
|
||||
* 1 - If silence is occurred and you can retrieve a new utterance with result method
|
||||
* 0 - If decoding continues
|
||||
* -1 - If exception occurred
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
fun acceptWaveform(data: ByteArray): Boolean
|
||||
|
||||
/**
|
||||
* Same as [acceptWaveform] but the version with the short data for language bindings where you have
|
||||
* audio as array of shorts
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
fun acceptWaveform(data: ShortArray): Boolean
|
||||
|
||||
/**
|
||||
* Same as [acceptWaveform] but the version with the float data for language bindings where you have
|
||||
* audio as array of floats
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
fun acceptWaveform(data: FloatArray): Boolean
|
||||
|
||||
/**
|
||||
* Returns speech recognition result
|
||||
*
|
||||
* @returns the result in JSON format which contains decoded line, decoded
|
||||
* words, times in seconds and confidences. You can parse this result
|
||||
* with any json parser
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "text" : "what zero zero zero one"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* If alternatives enabled it returns result with alternatives, see also [setMaxAlternatives].
|
||||
*
|
||||
* If word times enabled returns word time, see also [setOutputWordTimes].
|
||||
*/
|
||||
val result: String
|
||||
|
||||
/**
|
||||
* Returns partial speech recognition
|
||||
*
|
||||
* @returns partial speech recognition text which is not yet finalized.
|
||||
* result may change as recognizer process more data.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "partial" : "cyril one eight zero"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
val finalResult: String
|
||||
|
||||
/**
|
||||
* Returns speech recognition result. Same as result, but doesn't wait for silence
|
||||
* You usually call it in the end of the stream to get final bits of audio. It
|
||||
* flushes the feature pipeline, so all remaining audio chunks got processed.
|
||||
*
|
||||
* @returns speech result in JSON format.
|
||||
*/
|
||||
val partialResult: String
|
||||
|
||||
/**
|
||||
* Resets the recognizer
|
||||
*
|
||||
* Resets current results so the recognition can continue from scratch
|
||||
*/
|
||||
fun reset()
|
||||
|
||||
/**
|
||||
* Releases recognizer object
|
||||
*
|
||||
* Underlying model is also unreferenced and if needed released
|
||||
*/
|
||||
override fun free()
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import org.vosk.exception.ModelException
|
||||
|
||||
/**
|
||||
* Speaker model is the same as model but contains the data
|
||||
* for speaker identification.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Loads speaker model data from the file and returns the model object
|
||||
* @param path the path of the model on the filesystem
|
||||
* @throws ModelException if the path provided is invalid
|
||||
*/
|
||||
expect class SpeakerModel @Throws(ModelException::class) constructor(path: String) : Freeable {
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
override fun free()
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* 26 / 12 / 2022
|
||||
*
|
||||
* Control overarching features of libvosk.
|
||||
*/
|
||||
expect object Vosk {
|
||||
/**
|
||||
* Set log level for Kaldi messages
|
||||
*
|
||||
* @param logLevel the level
|
||||
*/
|
||||
fun setLogLevel(logLevel: LogLevel)
|
||||
|
||||
/**
|
||||
* Init, automatically select a CUDA device and allow multithreading.
|
||||
* Must be called once from the main thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
fun gpuInit()
|
||||
|
||||
|
||||
/**
|
||||
* Init CUDA device in a multi-threaded environment.
|
||||
* Must be called for each thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
fun gpuThreadInit()
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.exception
|
||||
|
||||
/**
|
||||
* Internal common IO exception. On JVM this is just a type alias.
|
||||
*/
|
||||
expect open class IOException(message: String? = null) : Exception
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.exception
|
||||
|
||||
/**
|
||||
* Thrown when there is an exception creating a model.
|
||||
*/
|
||||
class ModelException(path: String): IOException("Failed to find model: $path")
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.exception
|
||||
|
||||
/**
|
||||
* Thrown when the recognizer fails to be created
|
||||
*/
|
||||
class RecognizerException: IOException("Failed to create recognizer.")
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Represents an alternative result.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
@Serializable
|
||||
data class Alternative(
|
||||
val confidence: Double,
|
||||
val result: List<Result> = emptyList(),
|
||||
val text: String
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.encodeToJsonElement
|
||||
import org.vosk.Recognizer
|
||||
import org.vosk.Model
|
||||
import org.vosk.exception.RecognizerException
|
||||
|
||||
/*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
|
||||
/**
|
||||
* Vosk JSON encoder
|
||||
*/
|
||||
val voskJson = Json { encodeDefaults = true }
|
||||
|
||||
/**
|
||||
* Get the result as a JSON object
|
||||
*/
|
||||
fun Recognizer.resultAsJson(): ResultOutput =
|
||||
voskJson.decodeFromString(result)
|
||||
|
||||
/**
|
||||
* Get the final result as a JSON object
|
||||
*/
|
||||
fun Recognizer.finalResultAsJson(): ResultOutput =
|
||||
voskJson.decodeFromString(finalResult)
|
||||
|
||||
/**
|
||||
* Get the partial result as a JSON object
|
||||
*/
|
||||
fun Recognizer.partialResultAsJson(): PartialResultOutput =
|
||||
voskJson.decodeFromString(partialResult)
|
||||
|
||||
|
||||
/**
|
||||
* Create a [Recognizer], but using a list for grammar instead.
|
||||
*
|
||||
* The grammar list is converted into a JSON array
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
fun Recognizer(model: Model, sampleRate: Float, grammar: List<String>) =
|
||||
Recognizer(model, sampleRate, voskJson.encodeToJsonElement(grammar).toString())
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Represents a partial result
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
@Serializable
|
||||
data class PartialResultOutput(
|
||||
val partial: String,
|
||||
@SerialName("partial_result")
|
||||
val partialResult: List<Result> = emptyList(),
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Represents a result for any given word.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
@Serializable
|
||||
data class Result(
|
||||
val conf: Double? = null,
|
||||
val end: Double,
|
||||
val start: Double,
|
||||
val word: String,
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Result output
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
@Serializable
|
||||
data class ResultOutput(
|
||||
val alternatives: List<Alternative> = emptyList(),
|
||||
val result: List<Result> = emptyList(),
|
||||
val text: String? = null
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.json
|
||||
|
||||
/**
|
||||
* For extension functions transforming (input streams->recognizers) into flows.
|
||||
*/
|
||||
sealed interface WaveformResult {
|
||||
|
||||
/**
|
||||
* A result made after a period of silence.
|
||||
*/
|
||||
data class Result(val result: ResultOutput) : WaveformResult
|
||||
|
||||
/**
|
||||
* A partial result that is being made in progress.
|
||||
*/
|
||||
data class PartialResult(val result: PartialResultOutput) : WaveformResult
|
||||
|
||||
/**
|
||||
* A final result made after there is no more content to feed.
|
||||
*/
|
||||
data class FinalResult(val result: ResultOutput) : WaveformResult
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.PointerType
|
||||
import org.vosk.exception.ModelException
|
||||
import java.io.File
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.absolutePathString
|
||||
|
||||
|
||||
/**
|
||||
* Batch model object
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
actual class BatchModel : Freeable, PointerType, AutoCloseable {
|
||||
|
||||
/**
|
||||
* Empty constructor for JNA
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
* Creates the batch recognizer object
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
actual constructor(path: String) : super(
|
||||
LibVosk.vosk_batch_model_new(path) ?: throw ModelException(path)
|
||||
)
|
||||
|
||||
/**
|
||||
* Constructor using a Path, will retrieve absolutePath
|
||||
*
|
||||
* @param path to batch model
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
constructor(path: Path) : this(path.absolutePathString())
|
||||
|
||||
/**
|
||||
* Constructor using a File, will retrieve absolutePath
|
||||
*
|
||||
* @param file to batch model
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
constructor(file: File) : this(file.absolutePath)
|
||||
|
||||
/**
|
||||
* Releases batch model object
|
||||
*/
|
||||
actual override fun free() {
|
||||
LibVosk.vosk_batch_model_free(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the processing
|
||||
*/
|
||||
actual fun await() {
|
||||
LibVosk.vosk_batch_model_wait(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* @see free
|
||||
*/
|
||||
override fun close() {
|
||||
free()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.PointerType
|
||||
|
||||
|
||||
/**
|
||||
* Batch recognizer object
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Creates batch recognizer object
|
||||
*/
|
||||
actual class BatchRecognizer : Freeable, PointerType, AutoCloseable {
|
||||
|
||||
/**
|
||||
* Empty constructor for JNA
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
* Creates batch recognizer object
|
||||
*/
|
||||
actual constructor(model: BatchModel, sampleRate: Float) :
|
||||
super(LibVosk.vosk_batch_recognizer_new(model, sampleRate))
|
||||
|
||||
/**
|
||||
* Releases batch recognizer object
|
||||
*/
|
||||
actual override fun free() {
|
||||
LibVosk.vosk_batch_recognizer_free(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept batch voice data
|
||||
*/
|
||||
actual fun acceptWaveform(data: ByteArray) {
|
||||
LibVosk.vosk_batch_recognizer_accept_waveform(this, data, data.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
actual fun setNLSML(nlsml: Boolean) {
|
||||
LibVosk.vosk_batch_recognizer_set_nlsml(this, nlsml)
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the stream
|
||||
*/
|
||||
actual fun finishStream() {
|
||||
LibVosk.vosk_batch_recognizer_finish_stream(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*/
|
||||
actual val frontResult: String
|
||||
get() = LibVosk.vosk_batch_recognizer_front_result(this)
|
||||
|
||||
/**
|
||||
* Release and free first retrieved result
|
||||
*/
|
||||
actual fun pop() {
|
||||
LibVosk.vosk_batch_recognizer_pop(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get amount of pending chunks for more intelligent waiting
|
||||
*/
|
||||
actual val pendingChunks: Int
|
||||
get() = LibVosk.vosk_batch_recognizer_get_pending_chunks(this)
|
||||
|
||||
/**
|
||||
* @see free
|
||||
*/
|
||||
override fun close() {
|
||||
free()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.Native
|
||||
import com.sun.jna.Platform
|
||||
import com.sun.jna.Pointer
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
/**
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
@Suppress("FunctionName")
|
||||
internal object LibVosk {
|
||||
|
||||
@JvmStatic
|
||||
@Deprecated(
|
||||
"LibVosk is now for internal JNA, use Vosk instead",
|
||||
ReplaceWith("Vosk.setLogLevel(logLevel)", "org.vosk.Vosk")
|
||||
)
|
||||
fun setLogLevel(logLevel: LogLevel) {
|
||||
Vosk.setLogLevel(logLevel)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun unpackDll(targetDir: File, lib: String) {
|
||||
val source: InputStream =
|
||||
Vosk::class.java.getResourceAsStream("/win32-x86-64/$lib.dll")!!
|
||||
|
||||
Files.copy(
|
||||
source,
|
||||
File(targetDir, "$lib.dll").toPath(),
|
||||
StandardCopyOption.REPLACE_EXISTING
|
||||
)
|
||||
}
|
||||
|
||||
init {
|
||||
when {
|
||||
Platform.isAndroid() -> {
|
||||
Native.register(LibVosk::class.java, "vosk")
|
||||
}
|
||||
Platform.isWindows() -> {
|
||||
// We have to unpack dependencies
|
||||
try {
|
||||
// To get a tmp folder we unpack small library and mark it for deletion
|
||||
val tmpFile: File = Native.extractFromResourcePath(
|
||||
"/win32-x86-64/empty",
|
||||
LibVosk::class.java.classLoader
|
||||
)
|
||||
val tmpDir = tmpFile.parentFile!!
|
||||
File(tmpDir, tmpFile.name + ".x").createNewFile()
|
||||
|
||||
// Now unpack dependencies
|
||||
unpackDll(tmpDir, "libwinpthread-1");
|
||||
unpackDll(tmpDir, "libgcc_s_seh-1");
|
||||
unpackDll(tmpDir, "libstdc++-6");
|
||||
|
||||
} catch (e: IOException) {
|
||||
// Nothing for now, it will fail on next step
|
||||
} finally {
|
||||
Native.register(LibVosk::class.java, "libvosk");
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
Native.register(LibVosk::class.java, "vosk");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
external fun vosk_model_new(path: String): Pointer?
|
||||
|
||||
external fun vosk_model_free(model: Model)
|
||||
|
||||
external fun vosk_model_find_word(model: Model, word: String): Int
|
||||
|
||||
|
||||
external fun vosk_spk_model_new(path: String): Pointer?
|
||||
|
||||
external fun vosk_spk_model_free(model: SpeakerModel)
|
||||
|
||||
|
||||
external fun vosk_recognizer_new(model: Model, sampleRate: Float): Pointer?
|
||||
|
||||
external fun vosk_recognizer_new_spk(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
spkModel: SpeakerModel
|
||||
): Pointer?
|
||||
|
||||
external fun vosk_recognizer_new_grm(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
grammar: String?
|
||||
): Pointer?
|
||||
|
||||
external fun vosk_recognizer_set_spk_model(recognizer: Recognizer, spk_model: SpeakerModel)
|
||||
|
||||
external fun vosk_recognizer_set_grm(recognizer: Recognizer, grammar: String)
|
||||
|
||||
external fun vosk_recognizer_set_max_alternatives(recognizer: Recognizer, maxAlternatives: Int)
|
||||
|
||||
external fun vosk_recognizer_set_words(recognizer: Recognizer, words: Boolean)
|
||||
|
||||
external fun vosk_recognizer_set_partial_words(recognizer: Recognizer, partial_words: Boolean)
|
||||
|
||||
external fun vosk_recognizer_set_nlsml(recognizer: Recognizer, nlsml: Boolean)
|
||||
|
||||
|
||||
external fun vosk_recognizer_accept_waveform(
|
||||
recognizer: Recognizer,
|
||||
data: ByteArray?,
|
||||
len: Int
|
||||
): Int
|
||||
|
||||
external fun vosk_recognizer_accept_waveform_s(
|
||||
recognizer: Recognizer,
|
||||
data: ShortArray?,
|
||||
len: Int
|
||||
): Int
|
||||
|
||||
external fun vosk_recognizer_accept_waveform_f(
|
||||
recognizer: Recognizer,
|
||||
data: FloatArray?,
|
||||
len: Int
|
||||
): Int
|
||||
|
||||
|
||||
external fun vosk_recognizer_result(recognizer: Recognizer): String
|
||||
|
||||
external fun vosk_recognizer_final_result(recognizer: Recognizer): String
|
||||
|
||||
external fun vosk_recognizer_partial_result(recognizer: Recognizer): String
|
||||
|
||||
|
||||
external fun vosk_recognizer_reset(recognizer: Recognizer)
|
||||
|
||||
external fun vosk_recognizer_free(recognizer: Recognizer)
|
||||
|
||||
external fun vosk_set_log_level(level: Int)
|
||||
|
||||
external fun vosk_gpu_init()
|
||||
|
||||
external fun vosk_gpu_thread_init()
|
||||
|
||||
|
||||
external fun vosk_batch_model_new(path: String): Pointer?
|
||||
|
||||
external fun vosk_batch_model_free(model: BatchModel)
|
||||
|
||||
external fun vosk_batch_model_wait(model: BatchModel)
|
||||
|
||||
external fun vosk_batch_recognizer_new(batchModel: BatchModel, sampleRate: Float): Pointer
|
||||
|
||||
external fun vosk_batch_recognizer_free(recognizer: BatchRecognizer)
|
||||
|
||||
external fun vosk_batch_recognizer_accept_waveform(
|
||||
recognizer: BatchRecognizer,
|
||||
data: ByteArray?,
|
||||
length: Int
|
||||
)
|
||||
|
||||
external fun vosk_batch_recognizer_set_nlsml(
|
||||
recognizer: BatchRecognizer,
|
||||
nlsml: Boolean
|
||||
)
|
||||
|
||||
external fun vosk_batch_recognizer_finish_stream(
|
||||
recognizer: BatchRecognizer
|
||||
)
|
||||
|
||||
external fun vosk_batch_recognizer_front_result(
|
||||
recognizer: BatchRecognizer
|
||||
): String
|
||||
|
||||
external fun vosk_batch_recognizer_pop(recognizer: BatchRecognizer)
|
||||
|
||||
external fun vosk_batch_recognizer_get_pending_chunks(recognizer: BatchRecognizer): Int
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.PointerType
|
||||
import org.vosk.exception.IOException
|
||||
import org.vosk.exception.ModelException
|
||||
import java.io.File
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.absolutePathString
|
||||
|
||||
|
||||
/**
|
||||
* Model stores all the data required for recognition
|
||||
*
|
||||
* It contains static data and can be shared across processing
|
||||
* threads.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Loads model data from the file and returns the model object
|
||||
* @throws IOException if the path provided is invalid
|
||||
*/
|
||||
actual class Model : Freeable, PointerType, AutoCloseable {
|
||||
|
||||
/**
|
||||
* Empty constructor for JNA
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
* Loads model data from the file and returns the model object
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
actual constructor(path: String) : super(
|
||||
LibVosk.vosk_model_new(path) ?: throw ModelException(path)
|
||||
)
|
||||
|
||||
/**
|
||||
* Constructor using a Path, will retrieve absolutePath
|
||||
*
|
||||
* @param path to batch model
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
constructor(path: Path) : this(path.absolutePathString())
|
||||
|
||||
/**
|
||||
* Constructor using a File, will retrieve absolutePath
|
||||
*
|
||||
* @param file to batch model
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
constructor(file: File) : this(file.absolutePath)
|
||||
|
||||
/**
|
||||
* Check if a word can be recognized by the model
|
||||
* @param word: the word
|
||||
* @returns the word symbol if @param word exists inside the model
|
||||
* or -1 otherwise.
|
||||
* Reminding that word symbol 0 is for <epsilon>
|
||||
*/
|
||||
actual fun findWord(word: String): Int =
|
||||
LibVosk.vosk_model_find_word(this, word)
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
actual override fun free() {
|
||||
LibVosk.vosk_model_free(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* @see free
|
||||
*/
|
||||
override fun close() {
|
||||
free()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.PointerType
|
||||
import org.vosk.exception.RecognizerException
|
||||
|
||||
/**
|
||||
* Recognizer object is the main object which processes data.
|
||||
*
|
||||
* Each recognizer usually runs in own thread and takes audio as input.
|
||||
* Once audio is processed recognizer returns JSON object as a string
|
||||
* which represent decoded information - words, confidences, times, n-best lists,
|
||||
* speaker information and so on
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
*/
|
||||
actual class Recognizer : Freeable, PointerType, AutoCloseable {
|
||||
|
||||
/**
|
||||
* Empty constructor for JNA
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
* Creates the recognizer object
|
||||
*
|
||||
* The recognizers process the speech and return text using shared model data
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
actual constructor(model: Model, sampleRate: Float) :
|
||||
super(LibVosk.vosk_recognizer_new(model, sampleRate) ?: throw RecognizerException())
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with speaker recognition
|
||||
*
|
||||
* With the speaker recognition mode the recognizer not just recognize
|
||||
* text but also return speaker vectors one can use for speaker identification
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param speakerModel speaker model for speaker identification
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
actual constructor(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
speakerModel: SpeakerModel
|
||||
) : super(
|
||||
LibVosk.vosk_recognizer_new_spk(model, sampleRate, speakerModel)
|
||||
?: throw RecognizerException()
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with the phrase list
|
||||
*
|
||||
* Sometimes when you want to improve recognition accuracy and when you don't need
|
||||
* to recognize large vocabulary you can specify a list of phrases to recognize. This
|
||||
* will improve recognizer speed and accuracy but might return [unk] if user said
|
||||
* something different.
|
||||
*
|
||||
* Only recognizers with lookahead models support this type of quick configuration.
|
||||
* Precompiled HCLG graph models are not supported.
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The valuesample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param grammar The string with the list of phrases to recognize as JSON array of strings,
|
||||
* for example "["one two three four five", "[unk]"]".
|
||||
*
|
||||
* @throws RecognizerException if a problem occurred
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
actual constructor(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
grammar: String
|
||||
) : super(
|
||||
LibVosk.vosk_recognizer_new_grm(model, sampleRate, grammar) ?: throw RecognizerException()
|
||||
)
|
||||
|
||||
/**
|
||||
* JVM analog of Kotlin extension
|
||||
* @see [org.vosk.json.Recognizer]
|
||||
*/
|
||||
@Throws(RecognizerException::class)
|
||||
constructor(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
grammar: List<String>
|
||||
) : super(
|
||||
// We need the full qualifer to avoid any build issues
|
||||
@Suppress("RemoveRedundantQualifierName")
|
||||
org.vosk.json.Recognizer(model, sampleRate, grammar).pointer
|
||||
)
|
||||
|
||||
/**
|
||||
* Adds speaker model to already initialized recognizer
|
||||
*
|
||||
* Can add speaker recognition model to already created recognizer. Helps to initialize
|
||||
* speaker recognition for grammar-based recognizer.
|
||||
*
|
||||
* @param speakerModel Speaker recognition model
|
||||
*/
|
||||
actual fun setSpeakerModel(speakerModel: SpeakerModel) {
|
||||
LibVosk.vosk_recognizer_set_spk_model(this, speakerModel)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconfigures recognizer to use grammar
|
||||
*
|
||||
* @param grammar Set of phrases in JSON array of strings or "[]" to use default model graph.
|
||||
* See also vosk_recognizer_new_grm
|
||||
*/
|
||||
actual fun setGrammar(grammar: String) {
|
||||
LibVosk.vosk_recognizer_set_grm(this, grammar)
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures recognizer to output n-best results
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "alternatives": [
|
||||
* { "text": "one two three four five", "confidence": 0.97 },
|
||||
* { "text": "one two three for five", "confidence": 0.03 },
|
||||
* ]
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param maxAlternatives - maximum alternatives to return from recognition results
|
||||
*/
|
||||
actual fun setMaxAlternatives(maxAlternatives: Int) {
|
||||
LibVosk.vosk_recognizer_set_max_alternatives(this, maxAlternatives)
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables words with times in the output
|
||||
*
|
||||
* <pre>
|
||||
* "result" : [{
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.110000,
|
||||
* "start" : 0.870000,
|
||||
* "word" : "what"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.530000,
|
||||
* "start" : 1.110000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.950000,
|
||||
* "start" : 1.530000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.340000,
|
||||
* "start" : 1.950000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.610000,
|
||||
* "start" : 2.340000,
|
||||
* "word" : "one"
|
||||
* }],
|
||||
* </pre>
|
||||
*
|
||||
* @param words - boolean value
|
||||
*/
|
||||
actual fun setOutputWordTimes(words: Boolean) {
|
||||
LibVosk.vosk_recognizer_set_words(this, words)
|
||||
}
|
||||
|
||||
/**
|
||||
* Like [setOutputWordTimes] return words and confidences in partial results
|
||||
*
|
||||
* @param partialWords - boolean value
|
||||
*/
|
||||
actual fun setPartialWords(partialWords: Boolean) {
|
||||
LibVosk.vosk_recognizer_set_partial_words(this, partialWords)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
actual fun setNLSML(nlsml: Boolean) {
|
||||
LibVosk.vosk_recognizer_set_nlsml(this, nlsml)
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept voice data
|
||||
*
|
||||
* accept and process new chunk of voice data
|
||||
*
|
||||
* @param data Audio data in PCM 16-bit mono format.
|
||||
* @param length Length of the audio data.
|
||||
* @returns
|
||||
* 1 - If silence is occurred and you can retrieve a new utterance with result method
|
||||
* 0 - If decoding continues
|
||||
* -1 - If exception occurred
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: ByteArray): Boolean {
|
||||
val result = LibVosk.vosk_recognizer_accept_waveform(this, data, data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as [acceptWaveform] but the version with the short data for language bindings where you have
|
||||
* audio as array of shorts
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: ShortArray): Boolean {
|
||||
val result = LibVosk.vosk_recognizer_accept_waveform_s(this, data, data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as [acceptWaveform] but the version with the float data for language bindings where you have
|
||||
* audio as array of floats
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: FloatArray): Boolean {
|
||||
val result = LibVosk.vosk_recognizer_accept_waveform_f(this, data, data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns speech recognition result
|
||||
*
|
||||
* @returns the result in JSON format which contains decoded line, decoded
|
||||
* words, times in seconds and confidences. You can parse this result
|
||||
* with any json parser
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "text" : "what zero zero zero one"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* If alternatives enabled it returns result with alternatives, see also [setMaxAlternatives].
|
||||
*
|
||||
* If word times enabled returns word time, see also [setOutputWordTimes].
|
||||
*/
|
||||
actual val result: String
|
||||
get() = LibVosk.vosk_recognizer_result(this)
|
||||
|
||||
/**
|
||||
* Returns partial speech recognition
|
||||
*
|
||||
* @returns partial speech recognition text which is not yet finalized.
|
||||
* result may change as recognizer process more data.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "partial" : "cyril one eight zero"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
actual val finalResult: String
|
||||
get() = LibVosk.vosk_recognizer_final_result(this)
|
||||
|
||||
/**
|
||||
* Returns speech recognition result. Same as result, but doesn't wait for silence
|
||||
* You usually call it in the end of the stream to get final bits of audio. It
|
||||
* flushes the feature pipeline, so all remaining audio chunks got processed.
|
||||
*
|
||||
* @returns speech result in JSON format.
|
||||
*/
|
||||
actual val partialResult: String
|
||||
get() = LibVosk.vosk_recognizer_partial_result(this)
|
||||
|
||||
/**
|
||||
* Resets the recognizer
|
||||
*
|
||||
* Resets current results so the recognition can continue from scratch
|
||||
*/
|
||||
actual fun reset() {
|
||||
LibVosk.vosk_recognizer_reset(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases recognizer object
|
||||
*
|
||||
* Underlying model is also unreferenced and if needed released
|
||||
*/
|
||||
actual override fun free() {
|
||||
LibVosk.vosk_recognizer_free(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* @see free
|
||||
*/
|
||||
override fun close() {
|
||||
free()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import com.sun.jna.PointerType
|
||||
import org.vosk.exception.ModelException
|
||||
import java.io.File
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.absolutePathString
|
||||
|
||||
/**
|
||||
* Speaker model is the same as model but contains the data
|
||||
* for speaker identification.
|
||||
*
|
||||
* @since 26 / 12 / 2022
|
||||
* @constructor Loads speaker model data from the file and returns the model object
|
||||
* @throws ModelException if the path provided is invalid
|
||||
*/
|
||||
actual class SpeakerModel : Freeable, PointerType, AutoCloseable {
|
||||
|
||||
/**
|
||||
* Empty constructor for JNA
|
||||
*/
|
||||
constructor()
|
||||
|
||||
/**
|
||||
* Loads speaker model data from the file and returns the model object
|
||||
*
|
||||
* @param path the path of the model on the filesystem
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
actual constructor(path: String) : super(
|
||||
LibVosk.vosk_spk_model_new(path) ?: throw ModelException(path)
|
||||
)
|
||||
|
||||
/**
|
||||
* Constructor using a Path, will retrieve absolutePath
|
||||
*
|
||||
* @param path to batch model
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
constructor(path: Path) : this(path.absolutePathString())
|
||||
|
||||
/**
|
||||
* Constructor using a File, will retrieve absolutePath
|
||||
*
|
||||
* @param file to batch model
|
||||
*/
|
||||
@Throws(ModelException::class)
|
||||
constructor(file: File) : this(file.absolutePath)
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
actual override fun free() {
|
||||
LibVosk.vosk_spk_model_free(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* @see free
|
||||
*/
|
||||
override fun close() {
|
||||
free()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
|
||||
/**
|
||||
* 26 / 12 / 2022
|
||||
*
|
||||
* Control overarching features of libvosk.
|
||||
*/
|
||||
actual object Vosk {
|
||||
/**
|
||||
* Set log level for Kaldi messages
|
||||
*
|
||||
* @param logLevel the level
|
||||
*/
|
||||
@JvmStatic
|
||||
actual fun setLogLevel(logLevel: LogLevel) {
|
||||
LibVosk.vosk_set_log_level(logLevel.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Init, automatically select a CUDA device and allow multithreading.
|
||||
* Must be called once from the main thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
@JvmStatic
|
||||
actual fun gpuInit() {
|
||||
LibVosk.vosk_gpu_init()
|
||||
}
|
||||
|
||||
/**
|
||||
* Init CUDA device in a multi-threaded environment.
|
||||
* Must be called for each thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
@JvmStatic
|
||||
actual fun gpuThreadInit() {
|
||||
LibVosk.vosk_gpu_thread_init()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import org.vosk.json.WaveformResult
|
||||
import org.vosk.json.finalResultAsJson
|
||||
import org.vosk.json.partialResultAsJson
|
||||
import org.vosk.json.resultAsJson
|
||||
|
||||
/**
|
||||
* Feed an [Flow] of [ByteArray] into a [Recognizer].
|
||||
*
|
||||
* The returned flow will emit an [WaveformResult] for each result parsed.
|
||||
*
|
||||
* This expects a null terminator to signify the end of a stream.
|
||||
*
|
||||
* This will not close the [recognizer] at the end of reading.
|
||||
*
|
||||
* Any exceptions will be fed into the flow,
|
||||
* and should be collected via [kotlinx.coroutines.flow.catch].
|
||||
*
|
||||
* Flows on [Dispatchers.IO] to prevent blocking the main thread.
|
||||
*
|
||||
* @see [Recognizer.acceptWaveform]
|
||||
*/
|
||||
fun Flow<ByteArray?>.feed(recognizer: Recognizer): Flow<WaveformResult> =
|
||||
map {
|
||||
if (it != null) {
|
||||
if (recognizer.acceptWaveform(it)) {
|
||||
WaveformResult.Result(recognizer.resultAsJson())
|
||||
} else {
|
||||
WaveformResult.PartialResult(recognizer.partialResultAsJson())
|
||||
}
|
||||
} else {
|
||||
WaveformResult.FinalResult(recognizer.finalResultAsJson())
|
||||
}
|
||||
}.flowOn(Dispatchers.IO)
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk.exception
|
||||
|
||||
/**
|
||||
* Analog of [java.io.IOException]
|
||||
*/
|
||||
actual typealias IOException = java.io.IOException
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* Copyright 2023 Alpha Cephei Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.vosk.*
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.FileInputStream
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import javax.sound.sampled.AudioSystem
|
||||
import javax.sound.sampled.UnsupportedAudioFileException
|
||||
import kotlin.test.Test
|
||||
|
||||
class DecoderTest {
|
||||
val modelPath = System.getenv("MODEL")
|
||||
val testFile = System.getenv("AUDIO")
|
||||
|
||||
init {
|
||||
System.load(System.getenv("LIBRARY"))
|
||||
Vosk.setLogLevel(LogLevel.DEBUG)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun grammarList() {
|
||||
Model(modelPath).use { model ->
|
||||
Recognizer(model, 16000f, listOf("one")).apply {
|
||||
setMaxAlternatives(10)
|
||||
setOutputWordTimes(true)
|
||||
setPartialWords(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Throws(IOException::class, UnsupportedAudioFileException::class)
|
||||
fun decoderTest() {
|
||||
Model(modelPath).use { model ->
|
||||
AudioSystem.getAudioInputStream(BufferedInputStream(FileInputStream(testFile)))
|
||||
.use { ais ->
|
||||
Recognizer(model, 16000f).apply {
|
||||
setMaxAlternatives(10)
|
||||
setOutputWordTimes(true)
|
||||
setPartialWords(true)
|
||||
}.use { recognizer ->
|
||||
val b = ByteArray(4096)
|
||||
while (ais.read(b) >= 0) {
|
||||
if (recognizer.acceptWaveform(b)) {
|
||||
println(recognizer.result)
|
||||
} else {
|
||||
println(recognizer.partialResult)
|
||||
}
|
||||
}
|
||||
println(recognizer.finalResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@Test
|
||||
@Throws(IOException::class, UnsupportedAudioFileException::class)
|
||||
fun decoderTestFlow() = runTest {
|
||||
Model(modelPath).use { model ->
|
||||
Recognizer(model, 16000f).apply {
|
||||
setMaxAlternatives(10)
|
||||
setOutputWordTimes(true)
|
||||
setPartialWords(true)
|
||||
}.use { recognizer ->
|
||||
AudioSystem.getAudioInputStream(BufferedInputStream(FileInputStream(testFile)))
|
||||
.use { ais ->
|
||||
flow {
|
||||
val b = ByteArray(4096)
|
||||
while (ais.read(b) >= 0) {
|
||||
emit(b)
|
||||
}
|
||||
emit(null)
|
||||
}.flowOn(Dispatchers.IO)
|
||||
.feed(recognizer)
|
||||
.collect {
|
||||
println(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This test aims to simulate the situation for Dicio,
|
||||
* In which we can receive the audio input stream before the recognizer is setup.
|
||||
*
|
||||
* It is recommended to use a large model on desktop to properly see how long it takes to load up.
|
||||
*/
|
||||
@Test
|
||||
@Throws(IOException::class, UnsupportedAudioFileException::class)
|
||||
fun decoderTestFlowBuffered() {
|
||||
// Scope to buffer into
|
||||
val scope = CoroutineScope(Dispatchers.IO)
|
||||
|
||||
AudioSystem.getAudioInputStream(BufferedInputStream(FileInputStream(testFile))).use { ais ->
|
||||
val byteFlow = flow {
|
||||
val b = ByteArray(4096)
|
||||
while (ais.read(b) >= 0) {
|
||||
emit(b)
|
||||
}
|
||||
emit(null)
|
||||
}.flowOn(Dispatchers.IO)
|
||||
.shareIn(scope, SharingStarted.Eagerly, 100)
|
||||
|
||||
// Tell us the current buffer size
|
||||
println("Buffered size:" + byteFlow.replayCache.size)
|
||||
|
||||
var startTime = System.currentTimeMillis()
|
||||
|
||||
Model(modelPath).use { model ->
|
||||
var resultTime = System.currentTimeMillis() - startTime
|
||||
println("Model initialized in: $resultTime")
|
||||
startTime = System.currentTimeMillis()
|
||||
|
||||
Recognizer(model, 16000f).apply {
|
||||
setMaxAlternatives(10)
|
||||
setOutputWordTimes(true)
|
||||
setPartialWords(true)
|
||||
}.use { recognizer ->
|
||||
resultTime = System.currentTimeMillis() - startTime
|
||||
println("Recognizer initialized in: $resultTime")
|
||||
println("Buffered size:" + byteFlow.replayCache.size)
|
||||
|
||||
runBlocking {
|
||||
byteFlow
|
||||
.feed(recognizer)
|
||||
.take(byteFlow.replayCache.size)
|
||||
.collect {
|
||||
println(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Throws(IOException::class, UnsupportedAudioFileException::class)
|
||||
fun decoderTestShort() {
|
||||
Model(modelPath).use { model ->
|
||||
AudioSystem.getAudioInputStream(BufferedInputStream(FileInputStream(testFile)))
|
||||
.use { ais ->
|
||||
Recognizer(model, 16000f).use { recognizer ->
|
||||
val b = ByteArray(4096)
|
||||
val s = ShortArray(2048)
|
||||
while (ais.read(b) >= 0) {
|
||||
ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(s)
|
||||
if (recognizer.acceptWaveform(s)) {
|
||||
println(recognizer.result)
|
||||
} else {
|
||||
println(recognizer.partialResult)
|
||||
}
|
||||
}
|
||||
println(recognizer.finalResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Throws(IOException::class, UnsupportedAudioFileException::class)
|
||||
fun decoderTestGrammar() {
|
||||
Model(modelPath).use { model ->
|
||||
AudioSystem.getAudioInputStream(BufferedInputStream(FileInputStream(testFile)))
|
||||
.use { ais ->
|
||||
Recognizer(
|
||||
model, 16000f, "[\"one two three four five six seven eight nine zero oh\"]"
|
||||
).use { recognizer ->
|
||||
val b = ByteArray(4096)
|
||||
while (ais.read(b) >= 0) {
|
||||
if (recognizer.acceptWaveform(b)) {
|
||||
println(recognizer.result)
|
||||
} else {
|
||||
println(recognizer.partialResult)
|
||||
}
|
||||
}
|
||||
println(recognizer.finalResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun decoderTestException() {
|
||||
try {
|
||||
val model = Model("model_missing")
|
||||
assert(false)
|
||||
} catch (e: IOException) {
|
||||
assert(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
headers = libvosk/vosk_api.h
|
||||
package = libvosk
|
||||
|
||||
noStringConversion = \
|
||||
vosk_batch_recognizer_accept_waveform \
|
||||
vosk_recognizer_accept_waveform
|
||||
|
||||
compilerOpts.linux = \
|
||||
-I/usr/include/libvosk/ \
|
||||
-I/usr/local/include/libvosk/ \
|
||||
-I/usr/include/ \
|
||||
-I/usr/local/include/
|
||||
|
||||
compilerOpts.linux_x64 = \
|
||||
-I/usr/lib64/libvosk/ \
|
||||
-I/usr/local/lib64/libvosk/
|
||||
|
||||
linkerOpts.linux = \
|
||||
-L/usr/lib/ \
|
||||
-L/usr/local/lib/ \
|
||||
-llibvosk
|
||||
|
||||
linkerOpts.linux_x64 = \
|
||||
-L/usr/lib64/ \
|
||||
-L/usr/local/lib64/
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import cnames.structs.VoskBatchModel
|
||||
import kotlinx.cinterop.CPointer
|
||||
import libvosk.vosk_batch_model_free
|
||||
import libvosk.vosk_batch_model_new
|
||||
import libvosk.vosk_batch_model_wait
|
||||
|
||||
/**
|
||||
* Batch model object
|
||||
*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual class BatchModel(val pointer: CPointer<VoskBatchModel>) : Freeable {
|
||||
/**
|
||||
* Creates the batch recognizer object
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
actual constructor(path: String) : this(vosk_batch_model_new(path) ?: throw ioException(path))
|
||||
|
||||
/**
|
||||
* Releases batch model object
|
||||
*/
|
||||
actual override fun free() {
|
||||
vosk_batch_model_free(pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the processing
|
||||
*/
|
||||
actual fun await() {
|
||||
vosk_batch_model_wait(pointer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import cnames.structs.VoskBatchRecognizer
|
||||
import kotlinx.cinterop.CPointer
|
||||
import kotlinx.cinterop.toCValues
|
||||
import kotlinx.cinterop.toKString
|
||||
import libvosk.*
|
||||
|
||||
/**
|
||||
* Batch recognizer object
|
||||
*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual class BatchRecognizer(val pointer: CPointer<VoskBatchRecognizer>) : Freeable {
|
||||
/**
|
||||
* Creates batch recognizer object
|
||||
*/
|
||||
actual constructor(
|
||||
model: BatchModel,
|
||||
sampleRate: Float
|
||||
) : this(vosk_batch_recognizer_new(model.pointer, sampleRate)!!)
|
||||
|
||||
/**
|
||||
* Releases batch recognizer object
|
||||
*/
|
||||
actual override fun free() {
|
||||
vosk_batch_recognizer_free(pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept batch voice data
|
||||
*/
|
||||
actual fun acceptWaveform(data: ByteArray) {
|
||||
vosk_batch_recognizer_accept_waveform(pointer, data.toCValues(), data.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
actual fun setNLSML(nlsml: Boolean) {
|
||||
vosk_batch_recognizer_set_nlsml(pointer, nlsml.toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the stream
|
||||
*/
|
||||
actual fun finishStream() {
|
||||
vosk_batch_recognizer_finish_stream(pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*/
|
||||
actual val frontResult: String
|
||||
get() = vosk_batch_recognizer_front_result(pointer)!!.toKString()
|
||||
|
||||
/**
|
||||
* Release and free first retrieved result
|
||||
*/
|
||||
actual fun pop() {
|
||||
vosk_batch_recognizer_pop(pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get amount of pending chunks for more intelligent waiting
|
||||
*/
|
||||
actual val pendingChunks: Int
|
||||
get() = vosk_batch_recognizer_get_pending_chunks(pointer)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/**
|
||||
* Use a [Freeable], then immediately free it and return any values.
|
||||
*/
|
||||
fun <T : Freeable, R> T.use(block: (T) -> R): R =
|
||||
block(this).also { free() }
|
||||
@@ -0,0 +1,3 @@
|
||||
package org.vosk
|
||||
|
||||
actual class IOException actual constructor(message: String?) : Exception()
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import cnames.structs.VoskModel
|
||||
import kotlinx.cinterop.CPointer
|
||||
import libvosk.vosk_model_find_word
|
||||
import libvosk.vosk_model_free
|
||||
import libvosk.vosk_model_new
|
||||
|
||||
/**
|
||||
* Model stores all the data required for recognition
|
||||
*
|
||||
* It contains static data and can be shared across processing
|
||||
* threads.
|
||||
*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual class Model(val pointer: CPointer<VoskModel>) : Freeable {
|
||||
/**
|
||||
* Loads model data from the file and returns the model object
|
||||
*
|
||||
* @param path: the path of the model on the filesystem
|
||||
* @returns model object or NULL if problem occured
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
actual constructor(path: String) : this(vosk_model_new(path) ?: throw ioException(path))
|
||||
|
||||
/**
|
||||
* Check if a word can be recognized by the model
|
||||
* @param word: the word
|
||||
* @returns the word symbol if @param word exists inside the model
|
||||
* or -1 otherwise.
|
||||
* Reminding that word symbol 0 is for <epsilon>
|
||||
*/
|
||||
actual fun findWord(word: String): Int =
|
||||
vosk_model_find_word(pointer, word)
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
actual override fun free() {
|
||||
vosk_model_free(pointer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import kotlinx.cinterop.CPointer
|
||||
import kotlinx.cinterop.toCValues
|
||||
import kotlinx.cinterop.toKString
|
||||
import libvosk.*
|
||||
|
||||
/**
|
||||
* Recognizer object is the main object which processes data.
|
||||
*
|
||||
* Each recognizer usually runs in own thread and takes audio as input.
|
||||
* Once audio is processed recognizer returns JSON object as a string
|
||||
* which represent decoded information - words, confidences, times, n-best lists,
|
||||
* speaker information and so on
|
||||
*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual class Recognizer(val pointer: CPointer<VoskRecognizer>) : Freeable {
|
||||
/**
|
||||
* Creates the recognizer object
|
||||
*
|
||||
* The recognizers process the speech and return text using shared model data
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @returns recognizer object or NULL if problem occured
|
||||
*/
|
||||
actual constructor(
|
||||
model: Model,
|
||||
sampleRate: Float
|
||||
) : this(
|
||||
vosk_recognizer_new(
|
||||
model.pointer,
|
||||
sampleRate
|
||||
)!!
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with speaker recognition
|
||||
*
|
||||
* With the speaker recognition mode the recognizer not just recognize
|
||||
* text but also return speaker vectors one can use for speaker identification
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param speakerModel speaker model for speaker identification
|
||||
* @returns recognizer object or NULL if problem occured
|
||||
*/
|
||||
actual constructor(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
speakerModel: SpeakerModel
|
||||
) : this(
|
||||
vosk_recognizer_new_spk(
|
||||
model.pointer,
|
||||
sampleRate,
|
||||
speakerModel.pointer
|
||||
)!!
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates the recognizer object with the phrase list
|
||||
*
|
||||
* Sometimes when you want to improve recognition accuracy and when you don't need
|
||||
* to recognize large vocabulary you can specify a list of phrases to recognize. This
|
||||
* will improve recognizer speed and accuracy but might return [unk] if user said
|
||||
* something different.
|
||||
*
|
||||
* Only recognizers with lookahead models support this type of quick configuration.
|
||||
* Precompiled HCLG graph models are not supported.
|
||||
*
|
||||
* @param model VoskModel containing static data for recognizer. Model can be
|
||||
* shared across recognizers, even running in different threads.
|
||||
* @param sampleRate The sample rate of the audio you going to feed into the recognizer.
|
||||
* Make sure this rate matches the audio content, it is a common
|
||||
* issue causing accuracy problems.
|
||||
* @param grammar The string with the list of phrases to recognize as JSON array of strings,
|
||||
* for example "["one two three four five", "[unk]"]".
|
||||
*
|
||||
* @returns recognizer object or NULL if problem occured
|
||||
*/
|
||||
actual constructor(
|
||||
model: Model,
|
||||
sampleRate: Float,
|
||||
grammar: String
|
||||
) : this(
|
||||
vosk_recognizer_new_grm(
|
||||
model.pointer,
|
||||
sampleRate,
|
||||
grammar
|
||||
)!!
|
||||
)
|
||||
|
||||
/**
|
||||
* Adds speaker model to already initialized recognizer
|
||||
*
|
||||
* Can add speaker recognition model to already created recognizer. Helps to initialize
|
||||
* speaker recognition for grammar-based recognizer.
|
||||
*
|
||||
* @param speakerModel Speaker recognition model
|
||||
*/
|
||||
actual fun setSpeakerModel(speakerModel: SpeakerModel) {
|
||||
vosk_recognizer_set_spk_model(pointer, speakerModel.pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconfigures recognizer to use grammar
|
||||
*
|
||||
* @param grammar Set of phrases in JSON array of strings or "[]" to use default model graph.
|
||||
* See also vosk_recognizer_new_grm
|
||||
*/
|
||||
actual fun setGrammar(grammar: String) {
|
||||
vosk_recognizer_set_grm(pointer, grammar)
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures recognizer to output n-best results
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "alternatives": [
|
||||
* { "text": "one two three four five", "confidence": 0.97 },
|
||||
* { "text": "one two three for five", "confidence": 0.03 },
|
||||
* ]
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param maxAlternatives - maximum alternatives to return from recognition results
|
||||
*/
|
||||
actual fun setMaxAlternatives(maxAlternatives: Int) {
|
||||
vosk_recognizer_set_max_alternatives(pointer, maxAlternatives)
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables words with times in the output
|
||||
*
|
||||
* <pre>
|
||||
* "result" : [{
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.110000,
|
||||
* "start" : 0.870000,
|
||||
* "word" : "what"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.530000,
|
||||
* "start" : 1.110000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 1.950000,
|
||||
* "start" : 1.530000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.340000,
|
||||
* "start" : 1.950000,
|
||||
* "word" : "zero"
|
||||
* }, {
|
||||
* "conf" : 1.000000,
|
||||
* "end" : 2.610000,
|
||||
* "start" : 2.340000,
|
||||
* "word" : "one"
|
||||
* }],
|
||||
* </pre>
|
||||
*
|
||||
* @param words - boolean value
|
||||
*/
|
||||
actual fun setWords(words: Boolean) {
|
||||
vosk_recognizer_set_words(pointer, words.toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Like above return words and confidences in partial results
|
||||
*
|
||||
* @param partialWords - boolean value
|
||||
*/
|
||||
actual fun setPartialWords(partialWords: Boolean) {
|
||||
vosk_recognizer_set_partial_words(pointer, partialWords.toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Set NLSML output
|
||||
* @param nlsml - boolean value
|
||||
*/
|
||||
actual fun setNLSML(nlsml: Boolean) {
|
||||
vosk_recognizer_set_nlsml(pointer, nlsml.toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept voice data
|
||||
*
|
||||
* accept and process new chunk of voice data
|
||||
*
|
||||
* @param data - audio data in PCM 16-bit mono format
|
||||
* @param length - length of the audio data
|
||||
* @returns 1 if silence is occured and you can retrieve a new utterance with result method
|
||||
* 0 if decoding continues
|
||||
* -1 if exception occured
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: ByteArray): Boolean {
|
||||
val result = vosk_recognizer_accept_waveform(pointer, data.toCValues(), data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as above but the version with the short data for language bindings where you have
|
||||
* audio as array of shorts
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: ShortArray): Boolean {
|
||||
val result = vosk_recognizer_accept_waveform_s(pointer, data.toCValues(), data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as above but the version with the float data for language bindings where you have
|
||||
* audio as array of floats
|
||||
*/
|
||||
@Throws(AcceptWaveformException::class)
|
||||
actual fun acceptWaveform(data: FloatArray): Boolean {
|
||||
val result = vosk_recognizer_accept_waveform_f(pointer, data.toCValues(), data.size)
|
||||
if (result == -1) throw AcceptWaveformException(data)
|
||||
return result == 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns speech recognition result
|
||||
*
|
||||
* @returns the result in JSON format which contains decoded line, decoded
|
||||
* words, times in seconds and confidences. You can parse this result
|
||||
* with any json parser
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "text" : "what zero zero zero one"
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* If alternatives enabled it returns result with alternatives, see also vosk_recognizer_set_max_alternatives().
|
||||
*
|
||||
* If word times enabled returns word time, see also vosk_recognizer_set_word_times().
|
||||
*/
|
||||
actual val result: String
|
||||
get() = vosk_recognizer_result(pointer)!!.toKString()
|
||||
|
||||
/**
|
||||
* Returns partial speech recognition
|
||||
*
|
||||
* @returns partial speech recognition text which is not yet finalized.
|
||||
* result may change as recognizer process more data.
|
||||
*
|
||||
* <pre>
|
||||
* {
|
||||
* "partial" : "cyril one eight zero"
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
actual val finalResult: String
|
||||
get() = vosk_recognizer_result(pointer)!!.toKString()
|
||||
|
||||
/**
|
||||
* Returns speech recognition result. Same as result, but doesn't wait for silence
|
||||
* You usually call it in the end of the stream to get final bits of audio. It
|
||||
* flushes the feature pipeline, so all remaining audio chunks got processed.
|
||||
*
|
||||
* @returns speech result in JSON format.
|
||||
*/
|
||||
actual val partialResult: String
|
||||
get() = vosk_recognizer_partial_result(pointer)!!.toKString()
|
||||
|
||||
/**
|
||||
* Resets the recognizer
|
||||
*
|
||||
* Resets current results so the recognition can continue from scratch */
|
||||
actual fun reset() {
|
||||
vosk_recognizer_reset(pointer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases recognizer object
|
||||
*
|
||||
* Underlying model is also unreferenced and if needed released */
|
||||
actual override fun free() {
|
||||
vosk_recognizer_free(pointer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import cnames.structs.VoskSpkModel
|
||||
import kotlinx.cinterop.CPointer
|
||||
import libvosk.vosk_spk_model_free
|
||||
import libvosk.vosk_spk_model_new
|
||||
|
||||
/**
|
||||
* Speaker model is the same as model but contains the data
|
||||
* for speaker identification.
|
||||
*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual class SpeakerModel(val pointer: CPointer<VoskSpkModel>) : Freeable {
|
||||
/**
|
||||
* Loads speaker model data from the file and returns the model object
|
||||
*
|
||||
* @param path: the path of the model on the filesystem
|
||||
* @returns model object or NULL if problem occurred
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
actual constructor(path: String) : this(vosk_spk_model_new(path) ?: throw ioException(path))
|
||||
|
||||
/**
|
||||
* Releases the model memory
|
||||
*
|
||||
* The model object is reference-counted so if some recognizer
|
||||
* depends on this model, model might still stay alive. When
|
||||
* last recognizer is released, model will be released too.
|
||||
*/
|
||||
actual override fun free() {
|
||||
vosk_spk_model_free(pointer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
/*
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
|
||||
/**
|
||||
* Converts a boolean to an int
|
||||
*/
|
||||
internal inline fun Boolean.toInt() = if (this) 1 else 0
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2020 Alpha Cephei Inc. & Doomsdayrs
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.vosk
|
||||
|
||||
import libvosk.vosk_set_log_level
|
||||
import libvosk.vosk_gpu_init
|
||||
import libvosk.vosk_gpu_thread_init
|
||||
|
||||
/**
|
||||
* 26 / 12 / 2022
|
||||
*/
|
||||
actual object Vosk {
|
||||
/** Set log level for Kaldi messages
|
||||
*
|
||||
* @param logLevel the level
|
||||
*/
|
||||
actual fun setLogLevel(logLevel: LogLevel) {
|
||||
vosk_set_log_level(logLevel.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Init, automatically select a CUDA device and allow multithreading.
|
||||
* Must be called once from the main thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
actual fun gpuInit() {
|
||||
vosk_gpu_init()
|
||||
}
|
||||
|
||||
/**
|
||||
* Init CUDA device in a multi-threaded environment.
|
||||
* Must be called for each thread.
|
||||
* Has no effect if HAVE_CUDA flag is not set.
|
||||
*/
|
||||
actual fun gpuThreadInit() {
|
||||
vosk_gpu_thread_init()
|
||||
}
|
||||
}
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import wave
|
||||
import sys
|
||||
|
||||
from vosk import Model, KaldiRecognizer, SetLogLevel, EndpointerMode
|
||||
|
||||
# You can set log level to -1 to disable debug messages
|
||||
SetLogLevel(0)
|
||||
|
||||
wf = wave.open(sys.argv[1], "rb")
|
||||
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
|
||||
print("Audio file must be WAV format mono PCM.")
|
||||
sys.exit(1)
|
||||
|
||||
model = Model(lang="en-us")
|
||||
|
||||
# You can also init model by name or with a folder path
|
||||
# model = Model(model_name="vosk-model-en-us-0.21")
|
||||
# model = Model("models/en")
|
||||
|
||||
rec = KaldiRecognizer(model, wf.getframerate())
|
||||
rec.SetWords(True)
|
||||
rec.SetPartialWords(True)
|
||||
rec.SetEndpointerMode(EndpointerMode.VERY_LONG)
|
||||
|
||||
while True:
|
||||
data = wf.readframes(4000)
|
||||
if len(data) == 0:
|
||||
break
|
||||
if rec.AcceptWaveform(data):
|
||||
print(rec.Result())
|
||||
else:
|
||||
print(rec.PartialResult())
|
||||
|
||||
print(rec.FinalResult())
|
||||
|
||||
|
||||
wf = wave.open(sys.argv[1], "rb")
|
||||
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
|
||||
print("Audio file must be WAV format mono PCM.")
|
||||
sys.exit(1)
|
||||
|
||||
rec.SetEndpointerDelays(300, 500, 2000)
|
||||
|
||||
while True:
|
||||
data = wf.readframes(4000)
|
||||
if len(data) == 0:
|
||||
break
|
||||
if rec.AcceptWaveform(data):
|
||||
print(rec.Result())
|
||||
else:
|
||||
print(rec.PartialResult())
|
||||
|
||||
print(rec.FinalResult())
|
||||
+1
-1
@@ -45,7 +45,7 @@ with open("README.md", "rb") as fh:
|
||||
|
||||
setuptools.setup(
|
||||
name="vosk",
|
||||
version="0.3.45",
|
||||
version="0.3.46",
|
||||
author="Alpha Cephei Inc",
|
||||
author_email="contact@alphacephei.com",
|
||||
description="Offline open source speech recognition API based on Kaldi and Vosk",
|
||||
|
||||
+21
-1
@@ -3,6 +3,7 @@ import sys
|
||||
import srt
|
||||
import datetime
|
||||
import json
|
||||
import enum
|
||||
|
||||
import requests
|
||||
from urllib.request import urlretrieve
|
||||
@@ -57,7 +58,8 @@ class Model:
|
||||
raise Exception("Failed to create a model")
|
||||
|
||||
def __del__(self):
|
||||
_c.vosk_model_free(self._handle)
|
||||
if _c is not None:
|
||||
_c.vosk_model_free(self._handle)
|
||||
|
||||
def vosk_model_find_word(self, word):
|
||||
return _c.vosk_model_find_word(self._handle, word.encode("utf-8"))
|
||||
@@ -140,6 +142,18 @@ class SpkModel:
|
||||
def __del__(self):
|
||||
_c.vosk_spk_model_free(self._handle)
|
||||
|
||||
class EndpointerMode(enum.Enum):
|
||||
DEFAULT = 0
|
||||
SINGLE_WORD = 1
|
||||
VERY_SHORT = 2
|
||||
SHORT = 3
|
||||
STANDARD = 4
|
||||
STANDARD_5 = 5
|
||||
STANDARD_180 = 6
|
||||
LONG = 7
|
||||
VERY_LONG = 8
|
||||
VERY_LONG_180 = 9
|
||||
|
||||
class KaldiRecognizer:
|
||||
|
||||
def __init__(self, *args):
|
||||
@@ -172,6 +186,12 @@ class KaldiRecognizer:
|
||||
def SetNLSML(self, enable_nlsml):
|
||||
_c.vosk_recognizer_set_nlsml(self._handle, 1 if enable_nlsml else 0)
|
||||
|
||||
def SetEndpointerMode(self, mode):
|
||||
_c.vosk_recognizer_set_endpointer_mode(self._handle, mode.value)
|
||||
|
||||
def SetEndpointerDelays(self, sct, nit, t):
|
||||
_c.vosk_recognizer_set_endpointer_delays(self._handle, sct, nit, t)
|
||||
|
||||
def SetSpkModel(self, spk_model):
|
||||
_c.vosk_recognizer_set_spk_model(self._handle, spk_model._handle)
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ class Transcriber:
|
||||
monologues = {"schemaVersion":"2.0", "monologues":[], "text":[]}
|
||||
for part in result:
|
||||
if part["text"] != "":
|
||||
monologue["text"] += part["text"]
|
||||
monologues["text"] += part["text"]
|
||||
for _, res in enumerate(result):
|
||||
if not "result" in res:
|
||||
continue
|
||||
@@ -133,6 +133,12 @@ class Transcriber:
|
||||
start_time = timer()
|
||||
proc = await self.resample_ffmpeg_async(input_file)
|
||||
result, tot_samples = await self.recognize_stream_server(proc)
|
||||
await proc.wait()
|
||||
|
||||
# Bad input, continue
|
||||
if tot_samples == 0:
|
||||
self.queue.task_done()
|
||||
continue
|
||||
|
||||
processed_result = self.format_result(result)
|
||||
if output_file != "":
|
||||
@@ -142,8 +148,6 @@ class Transcriber:
|
||||
else:
|
||||
print(processed_result)
|
||||
|
||||
await proc.wait()
|
||||
|
||||
elapsed = timer() - start_time
|
||||
logging.info("Execution time: {:.3f} sec; "\
|
||||
"xRT {:.3f}".format(elapsed, float(elapsed) * (2 * SAMPLE_RATE) / tot_samples))
|
||||
@@ -165,8 +169,10 @@ class Transcriber:
|
||||
rec = KaldiRecognizer(self.model, SAMPLE_RATE)
|
||||
rec.SetWords(True)
|
||||
result, tot_samples = self.recognize_stream(rec, stream)
|
||||
processed_result = self.format_result(result)
|
||||
if tot_samples == 0:
|
||||
return
|
||||
|
||||
processed_result = self.format_result(result)
|
||||
if inputdata[1] != "":
|
||||
logging.info("File {} processing complete".format(inputdata[1]))
|
||||
with open(inputdata[1], "w", encoding="utf-8") as fh:
|
||||
|
||||
@@ -24,6 +24,12 @@
|
||||
#include <fst/matcher-fst.h>
|
||||
#include <fst/extensions/ngram/ngram-fst.h>
|
||||
|
||||
|
||||
#ifdef HAVE_MKL
|
||||
// We need to set num threads
|
||||
#include <mkl.h>
|
||||
#endif
|
||||
|
||||
namespace fst {
|
||||
|
||||
static FstRegisterer<StdOLabelLookAheadFst> OLabelLookAheadFst_StdArc_registerer;
|
||||
@@ -107,6 +113,10 @@ Model::Model(const char *model_path) : model_path_str_(model_path) {
|
||||
|
||||
SetLogHandler(KaldiLogHandler);
|
||||
|
||||
#ifdef HAVE_MKL
|
||||
mkl_set_num_threads(1);
|
||||
#endif
|
||||
|
||||
struct stat buffer;
|
||||
string am_v2_path = model_path_str_ + "/am/final.mdl";
|
||||
string model_conf_v2_path = model_path_str_ + "/conf/model.conf";
|
||||
@@ -244,6 +254,7 @@ void Model::ReadDataFiles()
|
||||
|
||||
decodable_info_ = new nnet3::DecodableNnetSimpleLoopedInfo(decodable_opts_,
|
||||
nnet_);
|
||||
|
||||
if (stat(final_ie_rxfilename_.c_str(), &buffer) == 0) {
|
||||
KALDI_LOG << "Loading i-vector extractor from " << final_ie_rxfilename_;
|
||||
|
||||
@@ -258,6 +269,8 @@ void Model::ReadDataFiles()
|
||||
|
||||
feature_info_.use_ivectors = true;
|
||||
feature_info_.ivector_extractor_info.Init(ivector_extraction_opts);
|
||||
} else if (nnet_->IvectorDim() > 0) {
|
||||
KALDI_ERR << "Can't find required ivector extractor";
|
||||
} else {
|
||||
feature_info_.use_ivectors = false;
|
||||
}
|
||||
|
||||
+118
-1
@@ -119,6 +119,8 @@ Recognizer::~Recognizer() {
|
||||
|
||||
void Recognizer::InitState()
|
||||
{
|
||||
endpoint_config_ = model_->endpoint_config_;
|
||||
|
||||
frame_offset_ = 0;
|
||||
samples_processed_ = 0;
|
||||
samples_round_start_ = 0;
|
||||
@@ -218,6 +220,121 @@ void Recognizer::SetNLSML(bool nlsml)
|
||||
nlsml_ = nlsml;
|
||||
}
|
||||
|
||||
void Recognizer::SetEndpointerMode(int mode)
|
||||
{
|
||||
float rule1, rule2, rule3, rule4, rule5;
|
||||
if (mode == 0) {
|
||||
endpoint_config_ = model_->endpoint_config_;
|
||||
return;
|
||||
}
|
||||
|
||||
float scale = 1.0;
|
||||
switch(mode) {
|
||||
case 1: // SINGLE_WORD
|
||||
rule2 = 0.1;
|
||||
rule3 = 0.15;
|
||||
rule4 = 0.2;
|
||||
rule1 = 4.0;
|
||||
rule5 = 7.0;
|
||||
break;
|
||||
case 2: // VERY_SHORT
|
||||
rule2 = 0.3;
|
||||
rule3 = 0.3;
|
||||
rule4 = 0.6;
|
||||
rule1 = 3.0;
|
||||
rule5 = 5.0;
|
||||
break;
|
||||
case 3: // SHORT
|
||||
rule2 = 0.3;
|
||||
rule3 = 0.4;
|
||||
rule4 = 0.6;
|
||||
rule1 = 3.0;
|
||||
rule5 = 5.0;
|
||||
break;
|
||||
case 4: // STANDARD
|
||||
rule2 = 0.8;
|
||||
rule3 = 0.9;
|
||||
rule4 = 1.0;
|
||||
rule1 = 3.0;
|
||||
rule5 = 7.0;
|
||||
break;
|
||||
case 5: // STANDARD_5
|
||||
rule2 = 0.8;
|
||||
rule3 = 0.9;
|
||||
rule4 = 1.5;
|
||||
rule1 = 5.0;
|
||||
rule5 = 7.0;
|
||||
break;
|
||||
case 6: // STANDARD_180
|
||||
rule2 = 0.8;
|
||||
rule3 = 0.9;
|
||||
rule4 = 1.5;
|
||||
rule1 = 3.0;
|
||||
rule5 = 180.0;
|
||||
break;
|
||||
case 7: // LONG
|
||||
rule2 = 1.0;
|
||||
rule3 = 1.2;
|
||||
rule4 = 2.0;
|
||||
rule1 = 4.0;
|
||||
rule5 = 10.0;
|
||||
break;
|
||||
case 8: // VERY_LONG
|
||||
rule2 = 2.0;
|
||||
rule3 = 2.5;
|
||||
rule4 = 3.0;
|
||||
rule1 = 4.0;
|
||||
rule5 = 15.0;
|
||||
break;
|
||||
case 9: // VERY_LONG_180
|
||||
rule2 = 2.0;
|
||||
rule3 = 2.5;
|
||||
rule4 = 3.0;
|
||||
rule1 = 4.0;
|
||||
rule5 = 180.0;
|
||||
break;
|
||||
default: // STANDARD
|
||||
rule2 = 0.8;
|
||||
rule3 = 0.9;
|
||||
rule4 = 1.0;
|
||||
rule1 = 5.0;
|
||||
rule5 = 7.0;
|
||||
break;
|
||||
}
|
||||
KALDI_LOG << "Updating endpointer timeouts to " << rule1 << "," << rule2 << "," << rule3 << "," << rule4 << "," << rule5;
|
||||
endpoint_config_ = model_->endpoint_config_;
|
||||
endpoint_config_.rule1.min_trailing_silence = rule1;
|
||||
endpoint_config_.rule2.min_trailing_silence = rule2;
|
||||
endpoint_config_.rule3.min_trailing_silence = rule3;
|
||||
endpoint_config_.rule4.min_trailing_silence = rule4;
|
||||
endpoint_config_.rule5.min_utterance_length = rule5;
|
||||
}
|
||||
|
||||
void Recognizer::SetEndpointerDelays(int sct, int nit, int t)
|
||||
{
|
||||
float rule1, rule2, rule3, rule4, rule5;
|
||||
|
||||
rule2 = sct / 1000.0;
|
||||
if (sct < 500) {
|
||||
rule3 = sct / 1000.0 * 1.5;
|
||||
rule4 = sct / 1000.0 * 2;
|
||||
} else {
|
||||
rule3 = sct / 1000.0 + 0.5;
|
||||
rule4 = sct / 1000.0 + 1.0;
|
||||
}
|
||||
rule1 = nit / 1000.0;
|
||||
rule5 = t / 1000.0;
|
||||
|
||||
KALDI_LOG << "Updating endpointer timeouts to " << rule1 << "," << rule2 << "," << rule3 << "," << rule4 << "," << rule5;
|
||||
endpoint_config_ = model_->endpoint_config_;
|
||||
endpoint_config_.rule1.min_trailing_silence = rule1;
|
||||
endpoint_config_.rule2.min_trailing_silence = rule2;
|
||||
endpoint_config_.rule3.min_trailing_silence = rule3;
|
||||
endpoint_config_.rule4.min_trailing_silence = rule4;
|
||||
endpoint_config_.rule5.min_utterance_length = rule5;
|
||||
}
|
||||
|
||||
|
||||
void Recognizer::SetSpkModel(SpkModel *spk_model)
|
||||
{
|
||||
if (state_ == RECOGNIZER_RUNNING) {
|
||||
@@ -367,7 +484,7 @@ bool Recognizer::AcceptWaveform(Vector<BaseFloat> &wdata)
|
||||
spk_feature_->AcceptWaveform(sample_frequency_, wdata);
|
||||
}
|
||||
|
||||
if (decoder_->EndpointDetected(model_->endpoint_config_)) {
|
||||
if (decoder_->EndpointDetected(endpoint_config_)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ class Recognizer {
|
||||
void SetWords(bool words);
|
||||
void SetPartialWords(bool partial_words);
|
||||
void SetNLSML(bool nlsml);
|
||||
void SetEndpointerMode(int mode);
|
||||
void SetEndpointerDelays(int sct, int nit, int t);
|
||||
bool AcceptWaveform(const char *data, int len);
|
||||
bool AcceptWaveform(const short *sdata, int len);
|
||||
bool AcceptWaveform(const float *fdata, int len);
|
||||
@@ -81,6 +83,8 @@ class Recognizer {
|
||||
fst::StdVectorFst *g_fst_ = nullptr; // dynamically constructed grammar
|
||||
OnlineNnet2FeaturePipeline *feature_pipeline_ = nullptr;
|
||||
OnlineSilenceWeighting *silence_weighting_ = nullptr;
|
||||
// Endpointer
|
||||
kaldi::OnlineEndpointConfig endpoint_config_;
|
||||
|
||||
// Speaker identification
|
||||
SpkModel *spk_model_ = nullptr;
|
||||
|
||||
@@ -129,6 +129,22 @@ void vosk_recognizer_set_grm(VoskRecognizer *recognizer, char const *grammar)
|
||||
((Recognizer *)recognizer)->SetGrm(grammar);
|
||||
}
|
||||
|
||||
void vosk_recognizer_set_endpointer_mode(VoskRecognizer *recognizer, VoskEndpointerMode mode)
|
||||
{
|
||||
if (recognizer == nullptr) {
|
||||
return;
|
||||
}
|
||||
((Recognizer *)recognizer)->SetEndpointerMode(mode);
|
||||
}
|
||||
|
||||
void vosk_recognizer_set_endpointer_delays(VoskRecognizer *recognizer, int sct, int nit, int t)
|
||||
{
|
||||
if (recognizer == nullptr) {
|
||||
return;
|
||||
}
|
||||
((Recognizer *)recognizer)->SetEndpointerDelays(sct, nit, t);
|
||||
}
|
||||
|
||||
int vosk_recognizer_accept_waveform(VoskRecognizer *recognizer, const char *data, int length)
|
||||
{
|
||||
try {
|
||||
|
||||
+31
-2
@@ -77,7 +77,7 @@ int vosk_model_find_word(VoskModel *model, const char *word);
|
||||
/** Loads speaker model data from the file and returns the model object
|
||||
*
|
||||
* @param model_path: the path of the model on the filesystem
|
||||
* @returns model object or NULL if problem occured */
|
||||
* @returns model object or NULL if problem occurred */
|
||||
VoskSpkModel *vosk_spk_model_new(const char *model_path);
|
||||
|
||||
|
||||
@@ -217,6 +217,35 @@ void vosk_recognizer_set_partial_words(VoskRecognizer *recognizer, int partial_w
|
||||
*/
|
||||
void vosk_recognizer_set_nlsml(VoskRecognizer *recognizer, int nlsml);
|
||||
|
||||
typedef enum VoskEndpointerMode {
|
||||
VOSK_EP_DEFAULT = 0,
|
||||
VOSK_EP_SINGLE_WORD = 1,
|
||||
VOSK_EP_VERY_SHORT = 2,
|
||||
VOSK_EP_SHORT = 3,
|
||||
VOSK_EP_STANDARD = 4,
|
||||
VOSK_EP_STANDARD_5 = 5,
|
||||
VOSK_EP_STANDARD_180 = 6,
|
||||
VOSK_EP_LONG = 7,
|
||||
VOSK_EP_VERY_LONG = 8,
|
||||
VOSK_EP_VERY_LONG_180 = 9
|
||||
} VoskEndpointerMode;
|
||||
|
||||
/**
|
||||
* Set endpointer scaling factor
|
||||
*
|
||||
* @param mode - Endpointer mode
|
||||
**/
|
||||
void vosk_recognizer_set_endpointer_mode(VoskRecognizer *recognizer, VoskEndpointerMode mode);
|
||||
|
||||
/**
|
||||
* Set endpointer delays
|
||||
*
|
||||
* @param sct speech complete timeout
|
||||
* @param sint speech incomplete timeout
|
||||
* @param nit no input timeout
|
||||
* @param t recognition timeout
|
||||
**/
|
||||
void vosk_recognizer_set_endpointer_delays(VoskRecognizer *recognizer, int sct, int nit, int t);
|
||||
|
||||
/** Accept voice data
|
||||
*
|
||||
@@ -298,7 +327,7 @@ void vosk_recognizer_free(VoskRecognizer *recognizer);
|
||||
* @param log_level the level
|
||||
* 0 - default value to print info and error messages but no debug
|
||||
* less than 0 - don't print info messages
|
||||
* greather than 0 - more verbose mode
|
||||
* greater than 0 - more verbose mode
|
||||
*/
|
||||
void vosk_set_log_level(int log_level);
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
FROM quay.io/pypa/manylinux2010_x86_64
|
||||
|
||||
LABEL description="A docker image for building portable Python linux binary wheels and Kaldi"
|
||||
LABEL maintainer="contact@alphacephei.com"
|
||||
|
||||
RUN yum -y update && yum -y install \
|
||||
devtoolset-8-libatomic-devel \
|
||||
automake \
|
||||
autoconf \
|
||||
libtool \
|
||||
cmake \
|
||||
libffi-devel \
|
||||
gperftools-devel \
|
||||
&& yum clean all
|
||||
|
||||
RUN cd /opt \
|
||||
&& git clone -b vosk --single-branch https://github.com/alphacep/kaldi \
|
||||
&& cd /opt/kaldi/tools \
|
||||
&& ./extras/install_mkl.sh \
|
||||
&& cd /opt/kaldi/tools \
|
||||
&& git clone --single-branch https://github.com/alphacep/openfst openfst \
|
||||
&& cd openfst \
|
||||
&& autoreconf -i \
|
||||
&& CFLAGS="-g -O3" ./configure --prefix=/opt/kaldi/tools/openfst --enable-static --enable-shared --enable-far --enable-ngram-fsts --enable-lookahead-fsts --with-pic --disable-bin \
|
||||
&& make -j 10 && make install \
|
||||
&& cd /opt/kaldi/src \
|
||||
&& ./configure --mathlib=MKL --shared --use-cuda=no \
|
||||
&& sed -i 's:-msse -msse2:-msse -msse2 -mavx -mavx2:g' kaldi.mk \
|
||||
&& sed -i 's: -O1 : -O3 :g' kaldi.mk \
|
||||
&& make -j $(nproc) online2 lm rnnlm \
|
||||
&& find /opt/kaldi -name "*.o" -exec rm {} \;
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e -x
|
||||
docker build --file Dockerfile.manylinux-mkl --tag alphacep/kaldi-manylinux-mkl:latest .
|
||||
docker run --rm -v `realpath ..`:/io alphacep/kaldi-manylinux-mkl /io/travis/build-wheels-mkl.sh
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/bash
|
||||
set -e -x
|
||||
|
||||
# Build libvosk
|
||||
cd /opt
|
||||
git clone https://github.com/alphacep/vosk-api
|
||||
cd vosk-api/src
|
||||
EXTRA_LDFLAGS="-ltcmalloc_minimal" KALDI_ROOT=/opt/kaldi OPENFST_ROOT=/opt/kaldi/tools/openfst HAVE_MKL=1 HAVE_OPENBLAS_CLAPACK=0 make -j $(nproc)
|
||||
|
||||
# Copy dlls to output folder
|
||||
mkdir -p /io/wheelhouse/vosk-linux-x86_64-mkl
|
||||
cp /opt/vosk-api/src/*.so /opt/vosk-api/src/vosk_api.h /io/wheelhouse/vosk-linux-x86_64-mkl
|
||||
|
||||
# Build wheel and put to the output folder
|
||||
mkdir -p /opt/wheelhouse
|
||||
export VOSK_SOURCE=/opt/vosk-api
|
||||
/opt/python/cp37*/bin/pip -v wheel /opt/vosk-api/python --no-deps -w /opt/wheelhouse
|
||||
|
||||
# Fix manylinux
|
||||
for whl in /opt/wheelhouse/*.whl; do
|
||||
cp $whl /io/wheelhouse
|
||||
auditwheel repair "$whl" --plat manylinux2010_x86_64 -w /io/wheelhouse
|
||||
done
|
||||
Reference in New Issue
Block a user