index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/OrcaNative.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
class OrcaNative {
static native String getVersion();
static native void setSdk(String sdk);
static native long init(String accessKey, String modelPath) throws OrcaException;
static native void delete(long object);
static native int getSampleRate(long object) throws OrcaException;
static native String[] getValidCharacters(long object) throws OrcaException;
static native int getMaxCharacterLimit(long object) throws OrcaException;
static native OrcaAudio synthesize(
long object,
String text,
float speechRate,
long randomState) throws OrcaException;
static native OrcaAudio synthesizeToFile(
long object,
String text,
String outputPath,
float speechRate,
long randomState) throws OrcaException;
static native long streamOpen(
long object,
float speechRate,
long randomState) throws OrcaException;
static native short[] streamSynthesize(
long object,
String text) throws OrcaException;
static native short[] streamFlush(long object) throws OrcaException;
static native void streamClose(long object);
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/OrcaPhoneme.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaPhoneme {
private final String phoneme;
private final float startSec;
private final float endSec;
/**
* Constructor.
*
* @param phoneme Synthesized phoneme.
* @param startSec Start time of the phoneme in seconds.
* @param endSec End time of the phoneme in seconds.
*/
public OrcaPhoneme(String phoneme, float startSec, float endSec) {
this.phoneme = phoneme;
this.startSec = startSec;
this.endSec = endSec;
}
/**
* Getter for the synthesized phoneme.
*
* @return Synthesized phoneme.
*/
public String getPhoneme() {
return phoneme;
}
/**
* Getter for the start time of the phoneme in seconds.
*
* @return Start time of the phoneme in seconds.
*/
public float getStartSec() {
return startSec;
}
/**
* Getter for the end time of the phoneme in seconds.
*
* @return End time of the phoneme in seconds.
*/
public float getEndSec() {
return endSec;
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/OrcaSynthesizeParams.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
/**
* A class that exposes several properties that can control the audio synthesized by Orca.
*/
public class OrcaSynthesizeParams {
private final float speechRate;
private final long randomState;
/**
* Constructor.
*/
private OrcaSynthesizeParams(float speechRate, long randomState) {
this.speechRate = speechRate;
this.randomState = randomState;
}
/**
* Getter for the speech rate (i.e. the pace of the synthesized speech).
*
* @return Speech Rate.
*/
public float getSpeechRate() {
return this.speechRate;
}
/**
* Getter for the random state (i.e. the random state for the synthesized speech).
*
* @return Random State.
*/
public long getRandomState() {
return this.randomState;
}
/**
* Builder for creating instance of OrcaSynthesizeParams.
*/
public static class Builder {
private float speechRate = 1.0f;
private long randomState = -1;
/**
* Sets the speech rate.
*
* @param speechRate The pace of the synthesized speech. Valid values are within [0.7, 1.3].
* @return Modified builder object.
*/
public Builder setSpeechRate(float speechRate) {
this.speechRate = speechRate;
return this;
}
/**
* Sets the random state.
*
* @param randomState The random state for the synthesized speech.
* @return Modified builder object.
*/
public Builder setRandomState(long randomState) {
this.randomState = randomState;
return this;
}
/**
* Validates properties and creates an instance of OrcaSynthesizeParams.
*
* @return An instance of OrcaSynthesizeParams
* @throws OrcaInvalidArgumentException if there is an invalid parameter.
*/
public OrcaSynthesizeParams build() throws OrcaInvalidArgumentException {
if (speechRate < 0.7f || speechRate > 1.3f) {
throw new OrcaInvalidArgumentException(
"Speech rate must be within [0.7, 1.3]"
);
}
return new OrcaSynthesizeParams(speechRate, randomState);
}
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/OrcaWord.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaWord {
private final String word;
private final float startSec;
private final float endSec;
private final OrcaPhoneme[] phonemeArray;
/**
* Constructor.
*
* @param word Synthesized word.
* @param startSec Start time of the word in seconds.
* @param endSec End time of the word in seconds.
* @param phonemeArray Synthesized phonemes and their associated metadata.
*/
public OrcaWord(String word, float startSec, float endSec, OrcaPhoneme[] phonemeArray) {
this.word = word;
this.startSec = startSec;
this.endSec = endSec;
this.phonemeArray = phonemeArray;
}
/**
* Getter for the synthesized word.
*
* @return Synthesized word.
*/
public String getWord() {
return word;
}
/**
* Getter for the start time of the word in seconds.
*
* @return Start time of the word in seconds.
*/
public float getStartSec() {
return startSec;
}
/**
* Getter for the end time of the word in seconds.
*
* @return End time of the word in seconds.
*/
public float getEndSec() {
return endSec;
}
/**
* Getter for synthesized phonemes and their associated metadata.
*
* @return Synthesized phonemes and their associated metadata.
*/
public OrcaPhoneme[] getPhonemeArray() {
return phonemeArray;
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaActivationException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaActivationException extends OrcaException {
public OrcaActivationException(Throwable cause) {
super(cause);
}
public OrcaActivationException(String message) {
super(message);
}
public OrcaActivationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaActivationLimitException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaActivationLimitException extends OrcaException {
public OrcaActivationLimitException(Throwable cause) {
super(cause);
}
public OrcaActivationLimitException(String message) {
super(message);
}
public OrcaActivationLimitException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaActivationRefusedException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaActivationRefusedException extends OrcaException {
public OrcaActivationRefusedException(Throwable cause) {
super(cause);
}
public OrcaActivationRefusedException(String message) {
super(message);
}
public OrcaActivationRefusedException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaActivationThrottledException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaActivationThrottledException extends OrcaException {
public OrcaActivationThrottledException(Throwable cause) {
super(cause);
}
public OrcaActivationThrottledException(String message) {
super(message);
}
public OrcaActivationThrottledException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaException extends Exception {
private final String message;
private final String[] messageStack;
public OrcaException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public OrcaException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public OrcaException(String message, String[] messageStack) {
super(message);
this.message = message;
this.messageStack = messageStack;
}
public String[] getMessageStack() {
return this.messageStack;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(message);
if (messageStack != null) {
if (messageStack.length > 0) {
sb.append(":");
for (int i = 0; i < messageStack.length; i++) {
sb.append(String.format("\n [%d] %s", i, messageStack[i]));
}
}
}
return sb.toString();
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaIOException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaIOException extends OrcaException {
public OrcaIOException(Throwable cause) {
super(cause);
}
public OrcaIOException(String message) {
super(message);
}
public OrcaIOException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaInvalidArgumentException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaInvalidArgumentException extends OrcaException {
public OrcaInvalidArgumentException(Throwable cause) {
super(cause);
}
public OrcaInvalidArgumentException(String message) {
super(message);
}
public OrcaInvalidArgumentException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaInvalidStateException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaInvalidStateException extends OrcaException {
public OrcaInvalidStateException(Throwable cause) {
super(cause);
}
public OrcaInvalidStateException(String message) {
super(message);
}
public OrcaInvalidStateException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaKeyException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaKeyException extends OrcaException {
public OrcaKeyException(Throwable cause) {
super(cause);
}
public OrcaKeyException(String message) {
super(message);
}
public OrcaKeyException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaMemoryException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaMemoryException extends OrcaException {
public OrcaMemoryException(Throwable cause) {
super(cause);
}
public OrcaMemoryException(String message) {
super(message);
}
public OrcaMemoryException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaRuntimeException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaRuntimeException extends OrcaException {
public OrcaRuntimeException(Throwable cause) {
super(cause);
}
public OrcaRuntimeException(String message) {
super(message);
}
public OrcaRuntimeException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca
|
java-sources/ai/picovoice/orca-android/1.2.0/ai/picovoice/orca/exception/OrcaStopIterationException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.orca;
public class OrcaStopIterationException extends OrcaException {
public OrcaStopIterationException(Throwable cause) {
super(cause);
}
public OrcaStopIterationException(String message) {
super(message);
}
public OrcaStopIterationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/PicoLLM.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.HashMap;
import java.util.Map;
import android.text.TextUtils;
/**
* Android binding for picoLLM.
*/
public class PicoLLM {
static {
System.loadLibrary("pv_picollm");
}
private static final Map<String, Object> DIALOGS = new HashMap<>();
private static String _sdk = "android";
static {
DIALOGS.put("gemma-2b-it", GemmaChatDialog.class);
DIALOGS.put("gemma-7b-it", GemmaChatDialog.class);
DIALOGS.put("llama-2-7b-chat", Llama2ChatDialog.class);
DIALOGS.put("llama-2-13b-chat", Llama2ChatDialog.class);
DIALOGS.put("llama-2-70b-chat", Llama2ChatDialog.class);
DIALOGS.put("llama-3-8b-instruct", Llama3ChatDialog.class);
DIALOGS.put("llama-3-70b-instruct", Llama3ChatDialog.class);
DIALOGS.put("llama-3.2-1b-instruct", Llama32ChatDialog.class);
DIALOGS.put("llama-3.2-3b-instruct", Llama32ChatDialog.class);
DIALOGS.put("mistral-7b-instruct-v0.1", MistralChatDialog.class);
DIALOGS.put("mistral-7b-instruct-v0.2", MistralChatDialog.class);
DIALOGS.put("mixtral-8x7b-instruct-v0.1", MixtralChatDialog.class);
Map<String, Class<? extends PicoLLMDialog>> phi2Map = new HashMap<>();
phi2Map.put("default", Phi2QADialog.class);
phi2Map.put("qa", Phi2QADialog.class);
phi2Map.put("chat", Phi2ChatDialog.class);
DIALOGS.put("phi2", phi2Map);
DIALOGS.put("phi3", Phi3ChatDialog.class);
DIALOGS.put("phi3.5", Phi35ChatDialog.class);
}
public static void setSdk(String sdk) {
PicoLLM._sdk = sdk;
}
private long handle;
private final String model;
private final int contextLength;
/**
* Retrieves the version of the picoLLM library.
*
* @return Version of the picoLLM library.
* @throws PicoLLMException if getting the version fails.
*/
public static String getVersion() throws PicoLLMException {
return PicoLLMNative.getVersion();
}
/**
* Retrieves the maximum number of top choices allowed during generation.
*
* @return Maximum number of top choices allowed during generation.
*/
public static int getMaxTopChoices() {
return PicoLLMNative.getMaxTopChoices();
}
/**
* Lists all available devices that picoLLM can use for inference.
* Each entry in the list can be the `device` when initializing picoLLM.
*
* @return Array of all available devices that picoLLM can be used for inference.
* @throws PicoLLMException if getting available devices fails.
*/
public static String[] getAvailableDevices() throws PicoLLMException {
return PicoLLMNative.listHardwareDevices();
}
/**
* Constructs a new PicoLLM instance.
*
* @param accessKey AccessKey obtained from <a href="https://console.picovoice.ai/">Picovoice Console</a>
* @param modelPath Absolute path to the file containing LLM parameters.
* @param device String representation of the device (e.g., CPU or GPU) to use for inference. If set to `best`,
* picoLLM picks the most suitable device. If set to `gpu`, the engine uses the first available
* GPU device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where
* `${GPU_INDEX}` is the index of the target GPU. If set to `cpu`, the engine will run on the
* CPU with the default number of threads. To specify the number of threads, set this argument
* to `cpu:${NUM_THREADS}`, where `${NUM_THREADS}` is the desired number of threads.
* @throws PicoLLMException if initialization fails.
*/
private PicoLLM(
String accessKey,
String modelPath,
String device) throws PicoLLMException {
PicoLLMNative.setSdk(PicoLLM._sdk);
handle = PicoLLMNative.init(
accessKey,
modelPath,
device);
model = PicoLLMNative.getModel(handle);
contextLength = PicoLLMNative.getContextLength(handle);
}
/**
* Deletes the resources acquired by picoLLM.
*/
public void delete() {
if (handle != 0) {
PicoLLMNative.delete(handle);
handle = 0;
}
}
/**
* Generates completion text and relevant metadata given a text prompt and a
* set of generation parameters.
*
* @param prompt Text prompt.
* @param generateParams Generation parameters.
* @return Completion result.
* @throws PicoLLMException if generation fails.
*/
public PicoLLMCompletion generate(
String prompt,
PicoLLMGenerateParams generateParams) throws PicoLLMException {
return PicoLLMNative.generate(
handle,
prompt,
generateParams.getCompletionTokenLimit(),
generateParams.getStopPhrases(),
generateParams.getSeed(),
generateParams.getPresencePenalty(),
generateParams.getFrequencyPenalty(),
generateParams.getTemperature(),
generateParams.getTopP(),
generateParams.getNumTopChoices(),
generateParams.getStreamCallback());
}
/**
* Interrupts `.generate()` if generation is in progress. Otherwise, it has no effect.
*
* @throws PicoLLMException if interrupt fails.
*/
public void interrupt() throws PicoLLMException {
PicoLLMNative.interrupt(handle);
}
/**
* Tokenizes a given text using the model's tokenizer. This is a low-level function meant for
* benchmarking and advanced usage. `.generate()` should be used when possible.
*
* @param text Text.
* @param bos If set to `true`, the tokenizer prepends the beginning of the sentence token to the result.
* @param eos If set to `true`, the tokenizer appends the end of the sentence token to the result.
* @return Tokens representing the input text.
* @throws PicoLLMException if tokenization fails.
*/
public int[] tokenize(
String text,
boolean bos,
boolean eos) throws PicoLLMException {
return PicoLLMNative.tokenize(
handle,
text,
bos,
eos);
}
/**
* Performs a single forward pass given a token and returns the logits. This is a low-level
* function for benchmarking and advanced usage. `.generate()` should be used when possible.
*
* @param token Input token.
* @return Logits.
* @throws PicoLLMException if the forward pass fails.
*/
public float[] forward(int token) throws PicoLLMException {
return PicoLLMNative.forward(handle, token);
}
/**
* Resets the internal state of LLM. It should be called in conjunction with `.forward()` when
* processing a new sequence of tokens. This is a low-level function for benchmarking and
* advanced usage. `.generate()` should be used when possible.
*
* @throws PicoLLMException if resetting fails.
*/
public void reset() throws PicoLLMException {
PicoLLMNative.reset(handle);
}
/**
* Getter for model's name.
*
* @return Model's name.
*/
public String getModel() {
return this.model;
}
/**
* Getter for model's context length.
*
* @return Model's context length.
*/
public int getContextLength() {
return this.contextLength;
}
/**
* Retrieves a new instance of DialogBuilder for constructing dialog objects from the
* currently loaded picoLLM model.
*
* @return A new instance of DialogBuilder.
*/
public DialogBuilder getDialogBuilder() {
return new DialogBuilder();
}
/**
* Builder class for creating a `PicoLLMDialog` instance.
*/
public class DialogBuilder {
private String mode = null;
private int history = 0;
private String system = null;
/**
* Sets the mode for the dialog builder.
*
* @param mode The mode to set. Some models (e.g., `phi-2`) define multiple chat
* template modes. For example, `phi-2` allows both `qa` and `chat` modes.
* @return DialogBuilder instance.
*/
public DialogBuilder setMode(String mode) {
this.mode = mode;
return this;
}
/**
* Sets the history length for the dialog builder.
*
* @param history The history length to set. History refers to the number of latest
* back-and-forths to include in the prompt. Setting history to `null` will embed the
* entire dialog in the prompt.
* @return DialogBuilder instance.
*/
public DialogBuilder setHistory(int history) {
this.history = history;
return this;
}
/**
* Sets the system instruction for the dialog builder.
*
* @param system The system instruction to set. System instruction to embed in the
* prompt for configuring the model's responses.
* @return DialogBuilder instance.
*/
public DialogBuilder setSystem(String system) {
this.system = system;
return this;
}
private PicoLLMDialog instantiateDialog(
Class<? extends PicoLLMDialog> dialogClass,
Integer history,
String system) throws PicoLLMException {
try {
return dialogClass
.getDeclaredConstructor(Integer.class, String.class)
.newInstance(history, system);
} catch (Exception e) {
throw new PicoLLMRuntimeException(e);
}
}
/**
* Constructs a PicoLLMDialog instance based on the configured settings.
*
* @return A new instance of PicoLLMDialog.
* @throws PicoLLMException If there's an issue constructing the dialog.
*/
@SuppressWarnings(value = "unchecked")
public PicoLLMDialog build() throws PicoLLMException {
String modelKey = model.split(" ")[0].toLowerCase();
if (!DIALOGS.containsKey(modelKey)) {
throw new PicoLLMInvalidArgumentException(
String.format(
"`%s` does not have a corresponding dialog implementation or is not instruction-tuned",
model));
}
Object dialog = DIALOGS.get(modelKey);
if (dialog instanceof Map) {
Map<String, Class<? extends PicoLLMDialog>> dialogModeMap =
(Map<String, Class<? extends PicoLLMDialog>>) dialog;
if (mode == null) {
if (!dialogModeMap.containsKey("default")) {
throw new PicoLLMInvalidArgumentException(
String.format(
"`%s` requires a mode. Available modes are: %s",
model,
TextUtils.join(", ", dialogModeMap.keySet())));
}
return instantiateDialog(dialogModeMap.get("default"), history, system);
} else {
if (!dialogModeMap.containsKey(mode)) {
throw new PicoLLMInvalidArgumentException(
String.format(
"`%s` doesn't have a `%s` mode. Available modes are: %s",
model,
mode,
TextUtils.join(", ", dialogModeMap.keySet())));
}
return instantiateDialog(dialogModeMap.get(mode), history, system);
}
} else {
if (mode != null) {
throw new PicoLLMInvalidArgumentException(
String.format(
"`%s` doesn't accept a mode parameter, set it to `null`",
model));
}
return instantiateDialog((Class<? extends PicoLLMDialog>) dialog, history, system);
}
}
}
/**
* Builder class for creating a `PicoLLM` instance.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private String device = null;
/**
* Sets the AccessKey.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
* @return Builder instance.
*/
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
/**
* Sets the model path.
*
* @param modelPath Absolute path to the file containing LLM parameters (`.pllm`).
* @return Builder instance.
*/
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
/**
* Sets the device to use for inference.
*
* @param device String representation of the device (e.g., CPU or GPU) to use for inference.
* If set to `best`, picoLLM picks the most suitable device. If set to `gpu`, the engine uses
* the first available GPU device. To select a specific GPU device, set this argument to
* `gpu:${GPU_INDEX}`, where `${GPU_INDEX}` is the index of the target GPU. If set to `cpu`,
* the engine will run on the CPU with the default number of threads. To specify the number
* of threads, set this argument to `cpu:${NUM_THREADS}`, where `${NUM_THREADS}` is the desired
* number of threads.
* @return Builder instance.
*/
public Builder setDevice(String device) {
this.device = device;
return this;
}
/**
* Builds a new PicoLLM instance using values defined by the builder.
*
* @return Constructed PicoLLM instance.
* @throws PicoLLMException if initialization fails.
*/
public PicoLLM build() throws PicoLLMException {
if (accessKey == null || accessKey.equals("")) {
throw new PicoLLMInvalidArgumentException("No AccessKey provided to picoLLM.");
}
if (modelPath == null || modelPath.equals("")) {
throw new PicoLLMInvalidArgumentException("No model path provided to picoLLM.");
}
if (device == null || device.equals("")) {
device = "cpu:2";
} else {
String[] deviceSplit = device.split(":");
if (deviceSplit.length >= 1) {
if (deviceSplit[0].equals("cpu") || deviceSplit[0].equals("best")) {
if (deviceSplit.length == 1) {
device = deviceSplit[0] + ":2";
}
} else {
throw new PicoLLMInvalidArgumentException(
String.format(
"`%s` is not a valid device string. Only `cpu` and " +
"`best` are currently available for Android.",
deviceSplit[0]
));
}
}
}
return new PicoLLM(accessKey, modelPath, device);
}
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/PicoLLMCompletion.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a picoLLM completion result.
*/
public class PicoLLMCompletion {
private final Usage usage;
private final Endpoint endpoint;
private final CompletionToken[] completionTokens;
private final String completion;
/**
* Constructor for the PicoLLMCompletion class.
*
* @param usage Usage information.
* @param endpoint Reason for ending the generation process.
* @param completionTokens Generated tokens within completion and top alternative tokens.
* @param completion Completion string.
*/
public PicoLLMCompletion(
Usage usage,
Endpoint endpoint,
CompletionToken[] completionTokens,
String completion) {
this.usage = usage;
this.endpoint = endpoint;
this.completionTokens = completionTokens;
this.completion = completion;
}
/**
* Getter for usage information.
*
* @return The usage information.
*/
public Usage getUsage() {
return usage;
}
/**
* Getter for the reason for ending the generation process.
*
* @return The reason for ending the generation process.
*/
public Endpoint getEndpoint() {
return endpoint;
}
/**
* Getter for the generated tokens within completion and top alternative tokens.
*
* @return The generated tokens within completion and top alternative tokens.
*/
public CompletionToken[] getCompletionTokens() {
return completionTokens;
}
/**
* Getter for the completion string.
*
* @return The completion string.
*/
public String getCompletion() {
return completion;
}
/**
* Represents usage information.
*/
public static class Usage {
private final int promptTokens;
private final int completionTokens;
/**
* Constructor for the Usage class.
*
* @param promptTokens Number of tokens in the prompt.
* @param completionTokens Number of tokens in the completion.
*/
public Usage(int promptTokens, int completionTokens) {
this.promptTokens = promptTokens;
this.completionTokens = completionTokens;
}
/**
* Getter for the number of tokens in the prompt.
*
* @return The number of tokens in the prompt.
*/
public int getPromptTokens() {
return promptTokens;
}
/**
* Getter for the number of tokens in the completion.
*
* @return The number of tokens in the completion.
*/
public int getCompletionTokens() {
return completionTokens;
}
}
/**
* Represents reasons for ending the generation process.
*/
public enum Endpoint {
END_OF_SENTENCE,
COMPLETION_TOKEN_LIMIT_REACHED,
STOP_PHRASE_ENCOUNTERED,
INTERRUPTED
}
/**
* Represents a generated token.
*/
public static class Token {
private final String token;
private final float logProb;
/**
* Constructor for the Token class.
*
* @param token The token.
* @param logProb The log probability.
*/
public Token(String token, float logProb) {
this.token = token;
this.logProb = logProb;
}
/**
* Getter for the token.
*
* @return The token.
*/
public String getToken() {
return token;
}
/**
* Getter for the log probability.
*
* @return The log probability.
*/
public float getLogProb() {
return logProb;
}
}
/**
* Represents a generated token within completion and top alternative tokens.
*/
public static class CompletionToken {
private final Token token;
private final Token[] topChoices;
/**
* Constructor for the CompletionToken class.
*
* @param token The token.
* @param topChoices Top alternative tokens.
*/
public CompletionToken(Token token, Token[] topChoices) {
this.token = token;
this.topChoices = topChoices;
}
/**
* Getter for the token.
*
* @return The token.
*/
public Token getToken() {
return token;
}
/**
* Getter for the top alternative tokens.
*
* @return The top alternative tokens.
*/
public Token[] getTopChoices() {
return topChoices;
}
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/PicoLLMGenerateParams.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Class for configuring generation parameters when calling `PicoLLM.generate()`.
*/
public class PicoLLMGenerateParams {
private int completionTokenLimit;
private String[] stopPhrases;
private int seed;
private float presencePenalty;
private float frequencyPenalty;
private float temperature;
private float topP;
private int numTopChoices;
private PicoLLMStreamCallback streamCallback;
/**
* Constructor.
*
* @param completionTokenLimit The maximum number of tokens allowed in the completion.
* If the generation process stops due to reaching this limit,
* the endpoint output argument will indicate a completion token
* limit reached condition. Set to `-1` to impose no limit.
* @param stopPhrases Phrases that trigger early completion termination.
* The generation process stops when it encounters any of
* these phrases in the completion. The already generated
* completion, including the encountered stop phrase, will be
* returned. Set to `null` to turn off this feature.
* @param seed The seed value for the internal random number generator.
* Seeding enforces deterministic outputs.
* Set to -1 for randomized outputs for a given prompt.
* @param presencePenalty Penalty for presence of tokens in the generated completion.
* It penalizes logits already appearing in the partial completion
* if set to a positive value. If set to `0.0`, it has no effect.
* @param frequencyPenalty Penalty for the frequency of tokens in the generated completion.
* If set to a positive floating-point value, it penalizes logits
* proportional to the frequency of their appearance in the partial
* completion. If set to `0.0`, it has no effect.
* @param temperature Sampling temperature.
* A higher temperature smoothens the sampler's output, increasing
* the randomness. In contrast, a lower temperature creates a
* narrower distribution and reduces variability. Setting it to
* `0` selects the maximum logit during sampling.
* @param topP A positive floating-point number within (0, 1].
* It restricts the sampler's choices to high-probability logits
* that form the `topP` portion of the probability mass. Hence, it
* avoids randomly selecting unlikely logits. A value of `1.0`
* enables the sampler to pick any token with non-zero probability,
* turning off the feature.
* @param numTopChoices If set to a positive value, picoLLM returns the list of the
* highest probability tokens for any generated token.
* Set to `0` to turn off the feature.
* The maximum number of top choices is determined by
* `PicoLLM.getMaxTopChoices()`.
* @param streamCallback If not set to `null`, picoLLM executes this callback every time
* a new piece of completion string becomes available.
*/
public PicoLLMGenerateParams(
int completionTokenLimit,
String[] stopPhrases,
int seed,
float presencePenalty,
float frequencyPenalty,
float temperature,
float topP,
int numTopChoices,
PicoLLMStreamCallback streamCallback) {
this.completionTokenLimit = completionTokenLimit;
this.stopPhrases = stopPhrases;
this.seed = seed;
this.presencePenalty = presencePenalty;
this.frequencyPenalty = frequencyPenalty;
this.temperature = temperature;
this.topP = topP;
this.numTopChoices = numTopChoices;
this.streamCallback = streamCallback;
}
/**
* Gets the maximum number of tokens allowed in the completion.
*
* @return The completion token limit.
*/
public Integer getCompletionTokenLimit() {
return completionTokenLimit;
}
/**
* Sets the maximum number of tokens allowed in the completion.
*
* @param completionTokenLimit The completion token limit to set.
* If the generation process stops due to reaching this limit,
* the endpoint output argument will indicate a completion token
* limit reached condition. Set to `null` to impose no limit.
*/
public void setCompletionTokenLimit(Integer completionTokenLimit) {
this.completionTokenLimit = completionTokenLimit;
}
/**
* Gets the phrases that trigger early completion termination.
*
* @return Phrases that trigger early completion termination.
*/
public String[] getStopPhrases() {
return stopPhrases;
}
/**
* Sets the phrases that trigger early completion termination.
*
* @param stopPhrases Phrases that trigger early completion termination.
* The generation process stops when it encounters any of these phrases
* in the completion. The already generated completion, including the
* encountered stop phrase, will be returned. Set to `null` to turn off
* this feature.
*/
public void setStopPhrases(String[] stopPhrases) {
this.stopPhrases = stopPhrases;
}
/**
* Gets the seed value for the internal random number generator.
*
* @return The seed value for the internal random number generator.
* Seeding enforces deterministic outputs.
* Set to `null` for randomized outputs for a given prompt.
*/
public Integer getSeed() {
return seed;
}
/**
* Sets the seed value for the internal random number generator.
*
* @param seed The seed value for the internal random number generator.
* Seeding enforces deterministic outputs.
* Set to `-1` for randomized outputs for a given prompt.
*/
public void setSeed(Integer seed) {
this.seed = seed;
}
/**
* Gets the presence penalty.
*
* @return The presence penalty.
* It penalizes logits already appearing in the partial completion if set to a positive value.
* If set to `0.0`, it has no effect.
*/
public float getPresencePenalty() {
return presencePenalty;
}
/**
* Sets the presence penalty.
*
* @param presencePenalty The presence penalty.
* It penalizes logits already appearing in the partial completion if
* set to a positive value. If set to `0.0`, it has no effect.
*/
public void setPresencePenalty(float presencePenalty) {
this.presencePenalty = presencePenalty;
}
/**
* Gets the frequency penalty.
*
* @return The frequency penalty.
* If set to a positive floating-point value, it penalizes logits proportional to the
* frequency of their appearance in the partial completion. If set to `0.0`, it has no
* effect.
*/
public float getFrequencyPenalty() {
return frequencyPenalty;
}
/**
* Sets the frequency penalty.
*
* @param frequencyPenalty The frequency penalty.
* If set to a positive floating-point value, it penalizes logits
* proportional to the frequency of their appearance in the partial
* completion. If set to `0.0`, it has no effect.
*/
public void setFrequencyPenalty(float frequencyPenalty) {
this.frequencyPenalty = frequencyPenalty;
}
/**
* Gets the temperature parameter.
*
* @return The temperature parameter.
* A higher temperature smoothens the sampler's output, increasing the randomness.
* In contrast, a lower temperature creates a narrower distribution and reduces variability.
* Setting it to `0` selects the maximum logit during sampling.
*/
public float getTemperature() {
return temperature;
}
/**
* Sets the temperature parameter.
*
* @param temperature The temperature parameter.
* A higher temperature smoothens the sampler's output, increasing the
* randomness. In contrast, a lower temperature creates a narrower
* distribution and reduces variability. Setting it to `0` selects the
* maximum logit during sampling.
*/
public void setTemperature(float temperature) {
this.temperature = temperature;
}
/**
* Gets the top-p parameter.
*
* @return The top-p parameter.
* A positive floating-point number within (0, 1].
* It restricts the sampler's choices to high-probability logits that form the top_p portion
* of the probability mass. Hence, it avoids randomly selecting unlikely logits.
* A value of 1.0 enables the sampler to pick any token with non-zero probability, turning
* off the feature.
*/
public float getTopP() {
return topP;
}
/**
* Sets the top-p parameter.
*
* @param topP The top-p parameter.
* A positive floating-point number within (0, 1].
* It restricts the sampler's choices to high-probability logits that form the top_p
* portion of the probability mass. Hence, it avoids randomly selecting unlikely
* logits. A value of `1.0` enables the sampler to pick any token with non-zero
* probability, turning off the feature.
*/
public void setTopP(float topP) {
this.topP = topP;
}
/**
* Gets the number of top choices.
*
* @return The number of top choices.
* If set to a positive value, picoLLM returns the list of the highest probability tokens
* for any generated token. Set to `0` to turn off the feature.
* The maximum number of top choices is determined by `PicoLLM.getMaxTopChoices()`.
*/
public int getNumTopChoices() {
return numTopChoices;
}
/**
* Sets the number of top choices.
*
* @param numTopChoices The number of top choices.
* If set to a positive value, picoLLM returns the list of the highest
* probability tokens for any generated token. Set to 0 to turn off the
* feature. The maximum number of top choices is determined by
* `PicoLLM.getMaxTopChoices()`.
*/
public void setNumTopChoices(int numTopChoices) {
this.numTopChoices = numTopChoices;
}
/**
* Gets the completion stream callback.
*
* @return The stream callback.
* If not set to null, picoLLM executes this callback every time a new piece of completion
* string becomes available.
*/
public PicoLLMStreamCallback getStreamCallback() {
return streamCallback;
}
/**
* Sets the completion stream callback.
*
* @param streamCallback The stream callback.
* If not set to null, picoLLM executes this callback every time a new
* piece of completion string becomes available.
*/
public void setStreamCallback(PicoLLMStreamCallback streamCallback) {
this.streamCallback = streamCallback;
}
/**
* Builder class for creating a `PicoLLMGenerateParams` instance.
*/
public static class Builder {
private Integer completionTokenLimit = null;
private String[] stopPhrases = null;
private Integer seed = null;
private float presencePenalty = 0;
private float frequencyPenalty = 0;
private float temperature = 0;
private float topP = 1;
private int numTopChoices = 0;
private PicoLLMStreamCallback streamCallback = null;
/**
* Sets the maximum number of tokens allowed in the completion.
*
* @param completionTokenLimit The maximum number of tokens allowed in the completion.
* If the generation process stops due to reaching this limit,
* the endpoint output argument will indicate a completion token
* limit reached condition.If not set, there will be no limit
* imposed.
* @return {@code Builder} instance.
*/
public Builder setCompletionTokenLimit(Integer completionTokenLimit) {
this.completionTokenLimit = completionTokenLimit;
return this;
}
/**
* Sets the phrases that trigger early completion termination.
*
* @param stopPhrases Phrases that trigger early completion termination.
* The generation process stops when it encounters any of these phrases
* in the completion. The already generated completion, including the
* encountered stop phrase, will be returned. Set to {@code null} to turn off this feature.
* @return {@code Builder} instance.
*/
public Builder setStopPhrases(String[] stopPhrases) {
this.stopPhrases = stopPhrases;
return this;
}
/**
* Sets the seed value for the internal random number generator.
*
* @param seed The seed value for the internal random number generator.
* Seeding enforces deterministic outputs.
* If not set, randomized outputs will be generated for a given prompt.
* @return {@code Builder} instance.
*/
public Builder setSeed(Integer seed) {
this.seed = seed;
return this;
}
/**
* Sets the presence penalty.
*
* @param presencePenalty The presence penalty.
* It penalizes logits already appearing in the partial completion if
* set to a positive value. If set to 0.0, it has no effect.
* @return {@code Builder} instance.
*/
public Builder setPresencePenalty(float presencePenalty) {
this.presencePenalty = presencePenalty;
return this;
}
/**
* Sets the frequency penalty.
*
* @param frequencyPenalty The frequency penalty.
* If set to a positive floating-point value, it penalizes logits
* proportional to the frequency of their appearance in the partial
* completion. If set to 0.0, it has no effect.
* @return {@code Builder} instance.
*/
public Builder setFrequencyPenalty(float frequencyPenalty) {
this.frequencyPenalty = frequencyPenalty;
return this;
}
/**
* Sets the temperature parameter.
*
* @param temperature The temperature parameter.
* A higher temperature smoothens the sampler's output, increasing the
* randomness. In contrast, a lower temperature creates a narrower
* distribution and reduces variability. Setting it to 0 selects the
* maximum logit during sampling.
* @return {@code Builder} instance.
*/
public Builder setTemperature(float temperature) {
this.temperature = temperature;
return this;
}
/**
* Sets the top-p parameter.
*
* @param topP The top-p parameter.
* A positive floating-point number within (0, 1].
* It restricts the sampler's choices to high-probability logits that form the
* top_p portion of the probability mass. Hence, it avoids randomly selecting
* unlikely logits. A value of 1.0 enables the sampler to pick any token with
* non-zero probability, turning off the feature.
* @return {@code Builder} instance.
*/
public Builder setTopP(float topP) {
this.topP = topP;
return this;
}
/**
* Sets the number of top choices.
*
* @param numTopChoices The number of top choices.
* If set to a positive value, picoLLM returns the list of the highest
* probability tokens for any generated token.
* Set to 0 to turn off the feature. The maximum number of top choices
* is determined by pv_picollm_max_top_choices().
* @return {@code Builder} instance.
*/
public Builder setNumTopChoices(int numTopChoices) {
this.numTopChoices = numTopChoices;
return this;
}
/**
* Sets the completion stream callback.
*
* @param streamCallback The stream callback.
* If not set to null, picoLLM executes this callback every time a new
* piece of completion string becomes available.
* @return {@code Builder} instance.
*/
public Builder setStreamCallback(PicoLLMStreamCallback streamCallback) {
this.streamCallback = streamCallback;
return this;
}
/**
* Constructs a new {@code PicoLLMGenerateParams} object.
*
* @return A new {@code PicoLLMGenerateParams} object with the parameters set in the builder.
*/
public PicoLLMGenerateParams build() {
return new PicoLLMGenerateParams(
completionTokenLimit == null ? -1 : completionTokenLimit,
stopPhrases,
seed == null ? -1 : seed,
presencePenalty,
frequencyPenalty,
temperature,
topP,
numTopChoices,
streamCallback);
}
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/PicoLLMNative.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
class PicoLLMNative {
static native String getVersion() throws PicoLLMException;
static native int getMaxTopChoices();
static native String[] listHardwareDevices() throws PicoLLMException;
static native void setSdk(String sdk) throws PicoLLMException;
static native long init(
String accessKey,
String modelPath,
String device) throws PicoLLMException;
static native void delete(long object);
static native PicoLLMCompletion generate(
long object,
String prompt,
int completionTokenLimit,
String[] stopPhrases,
int seed,
float presencePenalty,
float frequencyPenalty,
float temperature,
float topP,
int numTopChoices,
PicoLLMStreamCallback streamCallback) throws PicoLLMException;
static native void interrupt(long object) throws PicoLLMException;
static native int[] tokenize(
long object,
String text,
boolean bos,
boolean eos) throws PicoLLMException;
static native float[] forward(long object, int token) throws PicoLLMException;
static native void reset(long object) throws PicoLLMException;
static native String getModel(long object) throws PicoLLMException;
static native int getContextLength(long object) throws PicoLLMException;
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/PicoLLMStreamCallback.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Interface for receiving streaming result callbacks picoLLM's `.generate()` method.
*/
public interface PicoLLMStreamCallback {
/**
* Callback method invoked when a token has been generated by picoLLM.
*
* @param token The generated token.
*/
void callback(String token);
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/GemmaChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a dialog helper specific for `gemma-2b-it` and `gemma-7b-it` models.
*/
public class GemmaChatDialog extends PicoLLMDialog {
/**
* Builder class for constructing GemmaChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of GemmaChatDialog based on the configured settings.
*
* @return A new instance of GemmaChatDialog.
*/
public GemmaChatDialog build() {
return new GemmaChatDialog(this.history, this.system);
}
}
/**
* Constructs a GemmaChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
GemmaChatDialog(Integer history, String system) {
super(history, system);
}
/**
* Generates a formatted prompt string based on the dialog's content and configured settings.
*
* @return A formatted prompt string.
* @throws PicoLLMException If there's an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder();
for (int i = 0; i < llm.size(); i++) {
res.append(String.format(
"<start_of_turn>user\n%s<end_of_turn>\n",
human.get(i).trim()));
res.append(String.format(
"<start_of_turn>model\n%s<end_of_turn>\n",
llm.get(i).trim()));
}
res.append(String.format(
"<start_of_turn>user\n%s<end_of_turn>\n<start_of_turn>model",
human.get(human.size() - 1).trim()));
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Llama2ChatDialog.java
|
/*
Copyright 2024-2025 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a dialog helper specific for `llama-2-7b-chat`, `llama-2-13b-chat`, and `llama-2-70b-chat` models.
*/
public class Llama2ChatDialog extends PicoLLMDialog {
/**
* Builder class for constructing Llama2ChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Llama2ChatDialog based on the configured settings.
*
* @return A new instance of Llama2ChatDialog.
*/
public Llama2ChatDialog build() {
return new Llama2ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Llama2ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Llama2ChatDialog(Integer history, String system) {
super(history, system);
}
/**
* Generates a formatted prompt string based on the dialog's content and configured settings.
*
* @return A formatted prompt string.
* @throws PicoLLMException If there's an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder();
for (int i = 0; i < llm.size(); i++) {
String instruction = human.get(i).trim();
if (this.system != null && i == 0) {
instruction = String.format(
"<<SYS>>\n%s\n<</SYS>>\n\n%s",
this.system.trim(),
instruction);
}
res.append(String.format(
"<s>[INST] %s [/INST] %s </s>",
instruction,
llm.get(i).trim()));
}
String instruction = human.get(human.size() - 1).trim();
if (this.system != null && human.size() == 1) {
instruction = String.format(
"<<SYS>>\n%s\n<</SYS>>\n\n%s",
this.system.trim(),
instruction);
}
res.append(String.format("<s>[INST] %s [/INST]", instruction));
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Llama32ChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a dialog helper specific for the `phi3.5` model.
*/
public class Llama32ChatDialog extends Llama3ChatDialog {
/**
* Builder class for constructing Llama32ChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Llama32ChatDialog based on the configured settings.
*
* @return A new instance of Llama32ChatDialog.
*/
public Llama32ChatDialog build() {
return new Llama32ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Llama32ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Llama32ChatDialog(Integer history, String system) {
super(history, system);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Llama3ChatDialog.java
|
/*
Copyright 2024-2025 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a dialog helper specific for `llama-3-8b-instruct` and `llama-3-70b-instruct` models.
*/
public class Llama3ChatDialog extends PicoLLMDialog {
/**
* Builder class for constructing Llama3ChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Llama3ChatDialog based on the configured settings.
*
* @return A new instance of Llama3ChatDialog.
*/
public Llama3ChatDialog build() {
return new Llama3ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Llama3ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Llama3ChatDialog(Integer history, String system) {
super(history, system);
}
/**
* Generates a formatted prompt string based on the dialog's content and configured settings.
*
* @return A formatted prompt string.
* @throws PicoLLMException If there's an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder("<|begin_of_text|>");
if (this.system != null) {
res.append(String.format(
"<|start_header_id|>system<|end_header_id|>\n\n%s<|eot_id|>",
this.system.trim()));
}
for (int i = 0; i < llm.size(); i++) {
res.append(String.format(
"<|start_header_id|>user<|end_header_id|>\n\n%s<|eot_id|>",
human.get(i).trim()));
res.append(String.format("<|start_header_id|>assistant<|end_header_id|>\n\n%s<|eot_id|>",
llm.get(i).trim()));
}
res.append(String.format(
"<|start_header_id|>user<|end_header_id|>\n\n%s<|eot_id|>",
human.get(human.size() - 1).trim()));
res.append("<|start_header_id|>assistant<|end_header_id|>\n\n");
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/MistralChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a dialog helper specific for `mistral-7b-instruct-v0.1` and `mistral-7b-instruct-v0.2` models.
*/
public class MistralChatDialog extends PicoLLMDialog {
/**
* Builder class for constructing MistralChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of MistralChatDialog based on the configured settings.
*
* @return A new instance of MistralChatDialog.
*/
public MistralChatDialog build() {
return new MistralChatDialog(this.history, this.system);
}
}
/**
* Constructs a MistralChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
MistralChatDialog(Integer history, String system) {
super(history, system);
}
/**
* Generates a formatted prompt string based on the dialog's content and configured settings.
*
* @return A formatted prompt string.
* @throws PicoLLMException If there's an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder();
for (int i = 0; i < llm.size(); i++) {
res.append(String.format(
"[INST] %s [/INST] %s</s>",
human.get(i).trim(),
llm.get(i).trim()));
}
res.append(String.format(
"[INST] %s [/INST]",
human.get(human.size() - 1).trim()));
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/MixtralChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a dialog helper specific for the `mixtral-8x7b-instruct-v0.1` model.
*/
public class MixtralChatDialog extends MistralChatDialog {
/**
* Builder class for constructing MixtralChatDialog instances.
*/
public static class Builder extends MistralChatDialog.Builder {
/**
* Builds a new instance of MixtralChatDialog based on the configured settings.
*
* @return A new instance of MixtralChatDialog.
*/
public MixtralChatDialog build() {
return new MixtralChatDialog(this.history, this.system);
}
}
/**
* Constructs a MixtralChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
MixtralChatDialog(Integer history, String system) {
super(history, system);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Phi2ChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a dialog helper specific for `phi-2` models in `chat` mode.
*/
public class Phi2ChatDialog extends Phi2Dialog {
/**
* Builder class for constructing Phi2ChatDialog instances.
*/
public static class Builder extends Phi2Dialog.Builder {
/**
* Builds a new instance of Phi2ChatDialog based on the configured settings.
*
* @return A new instance of Phi2ChatDialog.
*/
public Phi2ChatDialog build() {
return new Phi2ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Phi2ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Phi2ChatDialog(Integer history, String system) {
super("Human", "AI", history, system);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Phi2Dialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a dialog helper for the 'phi-2' model within PicoLLM.
* This is a base class that provides functionalities common to both 'chat' and 'qa' modes
*/
public class Phi2Dialog extends PicoLLMDialog {
private final String humanTag;
private final String llmTag;
/**
* Builder class for constructing Phi2Dialog instances.
*/
protected static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Phi2Dialog based on the configured settings.
*
* @param humanTag The tag representing human input.
* @param llmTag The tag representing LLM output.
* @return A new instance of Phi2Dialog.
*/
protected Phi2Dialog build(String humanTag, String llmTag) {
return new Phi2Dialog(humanTag, llmTag, this.history, this.system);
}
}
/**
* Constructs a Phi2Dialog instance with the specified history, system, human tag, and LLM tag.
*
* @param humanTag The tag representing human input.
* @param llmTag The tag representing LLM output.
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
protected Phi2Dialog(String humanTag, String llmTag, Integer history, String system) {
super(history, system);
this.humanTag = humanTag;
this.llmTag = llmTag;
}
/**
* Generates a prompt string based on the human requests and LLM responses.
*
* @return The formatted prompt string.
* @throws PicoLLMException If there is an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder();
for (int i = 0; i < llm.size(); i++) {
res.append(String.format(
"%s: %s\n%s: %s\n",
this.humanTag,
human.get(i).trim(),
this.llmTag,
llm.get(i).trim()));
}
res.append(String.format(
"%s: %s\n%s:",
this.humanTag,
human.get(human.size() - 1).trim(),
this.llmTag));
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Phi2QADialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a dialog helper specific for `phi-2` models in `qa` mode.
*/
public class Phi2QADialog extends Phi2Dialog {
/**
* Builder class for constructing Phi2QADialog instances.
*/
public static class Builder extends Phi2Dialog.Builder {
/**
* Builds a new instance of Phi2QADialog based on the configured settings.
*
* @return A new instance of Phi2QADialog.
*/
public Phi2QADialog build() {
return new Phi2QADialog(this.history, this.system);
}
}
/**
* Constructs a Phi2QADialog instance with the specified history, system, human tag, and LLM tag.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Phi2QADialog(Integer history, String system) {
super("Instruct", "Output", history, system);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Phi35ChatDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
/**
* Represents a dialog helper specific for the `phi3.5` model.
*/
public class Phi35ChatDialog extends Phi3ChatDialog {
/**
* Builder class for constructing Phi35ChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Phi35ChatDialog based on the configured settings.
*
* @return A new instance of Phi35ChatDialog.
*/
public Phi35ChatDialog build() {
return new Phi35ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Phi35ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Phi35ChatDialog(Integer history, String system) {
super(history, system);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/Phi3ChatDialog.java
|
/*
Copyright 2024-2025 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
import java.util.List;
import ai.picovoice.picollm.PicoLLMDialog;
import ai.picovoice.picollm.PicoLLMException;
import ai.picovoice.picollm.PicoLLMInvalidStateException;
/**
* Represents a dialog helper specific for the `phi3` model.
*/
public class Phi3ChatDialog extends PicoLLMDialog {
/**
* Builder class for constructing Phi3ChatDialog instances.
*/
public static class Builder extends PicoLLMDialog.Builder {
/**
* Builds a new instance of Phi3ChatDialog based on the configured settings.
*
* @return A new instance of Phi3ChatDialog.
*/
public Phi3ChatDialog build() {
return new Phi3ChatDialog(this.history, this.system);
}
}
/**
* Constructs a Phi3ChatDialog instance with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
Phi3ChatDialog(Integer history, String system) {
super(history, system);
}
/**
* Generates a formatted prompt string based on the dialog's content and configured settings.
*
* @return A formatted prompt string.
* @throws PicoLLMException If there's an issue generating the prompt.
*/
@Override
public String getPrompt() throws PicoLLMException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Cannot create a prompt without an outstanding human request"
);
}
List<String> human = (this.history == null) ? this.humanRequests :
this.humanRequests.subList(
this.humanRequests.size() - (this.history + 1),
this.humanRequests.size());
List<String> llm = (this.history == null) ? this.llmResponses :
(this.history == 0) ? new ArrayList<>() :
this.llmResponses.subList(
this.llmResponses.size() - this.history,
this.llmResponses.size());
StringBuilder res = new StringBuilder();
if (this.system != null) {
res.append(String.format("<|system|>\n%s<|end|>\n", this.system.trim()));
}
for (int i = 0; i < llm.size(); i++) {
res.append(String.format(
"<|user|>\n%s<|end|>\n",
human.get(i).trim()));
res.append(String.format("<|assistant|>\n%s<|end|>\n",
llm.get(i).trim()));
}
res.append(String.format(
"<|user|>\n%s<|end|>\n",
human.get(human.size() - 1).trim()));
res.append("<|assistant|>\n");
return res.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/dialog/PicoLLMDialog.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import java.util.ArrayList;
/**
* `PicoLLMDialog` is a helper class that stores a chat dialog and formats it according
* to an instruction-tuned LLM's chat template. `PicoLLMDialog` is the base class.
* Each supported instruction-tuned LLM has an accompanying concrete subclass.
*/
public class PicoLLMDialog {
protected final Integer history;
protected final String system;
protected final ArrayList<String> humanRequests;
protected final ArrayList<String> llmResponses;
/**
* Builder class for constructing instances of PicoLLMDialog.
*/
public static class Builder {
protected Integer history = null;
protected String system = null;
/**
* Sets the history length for the builder.
*
* @param history The history length to set. History refers to the number of latest
* back-and-forths to include in the prompt. Setting history to `null` will embed the
* entire dialog in the prompt.
* @return Builder instance.
*/
public Builder setHistory(Integer history) {
if (history != null && history < 0) {
throw new IllegalArgumentException("History should be a non-negative integer.");
}
this.history = history;
return this;
}
/**
* Sets the system instruction for the builder.
*
* @param system The system instruction to set. System instruction to embed in the
* prompt for configuring the model's responses.
* @return Builder instance.
*/
public Builder setSystem(String system) {
this.system = system;
return this;
}
/**
* Builds a new instance of PicoLLMDialog based on the configured settings.
*
* @return A new instance of PicoLLMDialog.
*/
public PicoLLMDialog build() {
return new PicoLLMDialog(history, system);
}
}
/**
* Constructs a new instance of PicoLLMDialog with the specified history and system settings.
*
* @param history The history length for the dialog.
* @param system The system instruction for configuring the model's responses.
*/
protected PicoLLMDialog(Integer history, String system) {
this.history = history;
this.system = system;
this.humanRequests = new ArrayList<>();
this.llmResponses = new ArrayList<>();
}
/**
* Adds a human request to the dialog.
*
* @param content The human request to add.
* @throws PicoLLMInvalidStateException if adding a human request without a corresponding LLM response.
*/
public void addHumanRequest(String content) throws PicoLLMInvalidStateException {
if (this.humanRequests.size() > this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Entering a human request without entering the last LLM response is invalid."
);
}
this.humanRequests.add(content);
}
/**
* Adds an LLM response to the dialog.
*
* @param content The LLM response to add.
* @throws PicoLLMInvalidStateException if adding an LLM response without a corresponding human request.
*/
public void addLLMResponse(String content) throws PicoLLMInvalidStateException {
if (this.humanRequests.size() == this.llmResponses.size()) {
throw new PicoLLMInvalidStateException(
"Entering an LLM response without entering the human request is invalid."
);
}
this.llmResponses.add(content);
}
/**
* Creates a prompt string given parameters passed the constructor and dialog's content.
*
* @return Formatted prompt.
* @throws PicoLLMException if called from the base PicoLLMDialog class.
*/
public String getPrompt() throws PicoLLMException {
throw new PicoLLMException("Only base classes of PicoLLMDialog can return create prompts");
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMActivationException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMActivationException extends PicoLLMException {
public PicoLLMActivationException(Throwable cause) {
super(cause);
}
public PicoLLMActivationException(String message) {
super(message);
}
public PicoLLMActivationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMActivationLimitException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMActivationLimitException extends PicoLLMException {
public PicoLLMActivationLimitException(Throwable cause) {
super(cause);
}
public PicoLLMActivationLimitException(String message) {
super(message);
}
public PicoLLMActivationLimitException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMActivationRefusedException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMActivationRefusedException extends PicoLLMException {
public PicoLLMActivationRefusedException(Throwable cause) {
super(cause);
}
public PicoLLMActivationRefusedException(String message) {
super(message);
}
public PicoLLMActivationRefusedException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMActivationThrottledException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMActivationThrottledException extends PicoLLMException {
public PicoLLMActivationThrottledException(Throwable cause) {
super(cause);
}
public PicoLLMActivationThrottledException(String message) {
super(message);
}
public PicoLLMActivationThrottledException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
import android.annotation.SuppressLint;
public class PicoLLMException extends Exception {
private final String message;
private final String[] messageStack;
public PicoLLMException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public PicoLLMException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public PicoLLMException(String message, String[] messageStack) {
super(message);
this.message = message;
this.messageStack = messageStack;
}
public String[] getMessageStack() {
return this.messageStack;
}
@SuppressLint("DefaultLocale")
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(message);
if (messageStack != null) {
if (messageStack.length > 0) {
sb.append(":");
for (int i = 0; i < messageStack.length; i++) {
sb.append(String.format("\n [%d] %s", i, messageStack[i]));
}
}
}
return sb.toString();
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMIOException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMIOException extends PicoLLMException {
public PicoLLMIOException(Throwable cause) {
super(cause);
}
public PicoLLMIOException(String message) {
super(message);
}
public PicoLLMIOException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMInvalidArgumentException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMInvalidArgumentException extends PicoLLMException {
public PicoLLMInvalidArgumentException(Throwable cause) {
super(cause);
}
public PicoLLMInvalidArgumentException(String message) {
super(message);
}
public PicoLLMInvalidArgumentException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMInvalidStateException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMInvalidStateException extends PicoLLMException {
public PicoLLMInvalidStateException(Throwable cause) {
super(cause);
}
public PicoLLMInvalidStateException(String message) {
super(message);
}
public PicoLLMInvalidStateException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMKeyException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMKeyException extends PicoLLMException {
public PicoLLMKeyException(Throwable cause) {
super(cause);
}
public PicoLLMKeyException(String message) {
super(message);
}
public PicoLLMKeyException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMMemoryException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMMemoryException extends PicoLLMException {
public PicoLLMMemoryException(Throwable cause) {
super(cause);
}
public PicoLLMMemoryException(String message) {
super(message);
}
public PicoLLMMemoryException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMRuntimeException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMRuntimeException extends PicoLLMException {
public PicoLLMRuntimeException(Throwable cause) {
super(cause);
}
public PicoLLMRuntimeException(String message) {
super(message);
}
public PicoLLMRuntimeException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm
|
java-sources/ai/picovoice/picollm-android/1.3.2/ai/picovoice/picollm/exception/PicoLLMStopIterationException.java
|
/*
Copyright 2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picollm;
public class PicoLLMStopIterationException extends PicoLLMException {
public PicoLLMStopIterationException(Throwable cause) {
super(cause);
}
public PicoLLMStopIterationException(String message) {
super(message);
}
public PicoLLMStopIterationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/Picovoice.java
|
/*
Copyright 2020-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import ai.picovoice.porcupine.*;
import ai.picovoice.rhino.*;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class Picovoice {
private final PicovoiceWakeWordCallback wakeWordCallback;
private final PicovoiceInferenceCallback inferenceCallback;
private Porcupine porcupine;
private Rhino rhino;
private boolean isWakeWordDetected = false;
private final Handler callbackHandler = new Handler(Looper.getMainLooper());
/**
* Private Constructor.
*
* @param porcupine An instance of Porcupine wake word engine
* @param wakeWordCallback User-defined callback invoked upon detection of the wake phrase.
* ${@link PicovoiceWakeWordCallback} defines the interface of the
* callback.
* @param rhino An instance of Rhino Speech-to-Intent engine
* @param inferenceCallback User-defined callback invoked upon completion of intent inference.
* #{@link PicovoiceInferenceCallback} defines the interface of the
* callback.
*/
private Picovoice(
Porcupine porcupine,
PicovoiceWakeWordCallback wakeWordCallback,
Rhino rhino,
PicovoiceInferenceCallback inferenceCallback) {
this.porcupine = porcupine;
this.wakeWordCallback = wakeWordCallback;
this.rhino = rhino;
this.inferenceCallback = inferenceCallback;
}
/**
* Releases resources acquired by Picovoice.
*/
public void delete() {
if (porcupine != null) {
porcupine.delete();
porcupine = null;
}
if (rhino != null) {
rhino.delete();
rhino = null;
}
}
/**
* Processes a frame of the incoming audio stream. Upon detection of wake word and completion
* of follow-on command inference invokes user-defined callbacks.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by calling
* ${@link #getFrameLength()}. The incoming audio needs to have a sample rate equal
* to ${@link #getSampleRate()} and be 16-bit linearly-encoded. Picovoice operates on
* single-channel audio.
* @throws PicovoiceException if there is an error while processing the audio frame.
*/
public void process(short[] pcm) throws PicovoiceException {
if (porcupine == null || rhino == null) {
throw new PicovoiceInvalidStateException("Cannot process frame - resources have been released");
}
if (pcm == null) {
throw new PicovoiceInvalidArgumentException("Passed null frame to Picovoice process.");
}
if (pcm.length != getFrameLength()) {
throw new PicovoiceInvalidArgumentException(
String.format("Picovoice process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
try {
if (!isWakeWordDetected) {
isWakeWordDetected = (porcupine.process(pcm) == 0);
if (isWakeWordDetected && wakeWordCallback != null) {
callbackHandler.post(new Runnable() {
@Override
public void run() {
wakeWordCallback.invoke();
}
});
}
} else {
if (rhino.process(pcm)) {
if (inferenceCallback != null) {
final RhinoInference inference = rhino.getInference();
callbackHandler.post(new Runnable() {
@Override
public void run() {
inferenceCallback.invoke(inference);
}
});
}
isWakeWordDetected = false;
}
}
} catch (PorcupineException | RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Resets the internal state of Picovoice. It should be called before processing a new stream of audio
* or when process was stopped while processing a stream of audio.
*
* @throws PicovoiceException if reset fails.
*/
public void reset() throws PicovoiceException {
try {
this.isWakeWordDetected = false;
this.rhino.reset();
} catch (RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return "3.0.0";
}
/**
* Getter for number of audio samples per frame.
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return porcupine != null ? porcupine.getFrameLength() : 0;
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return porcupine != null ? porcupine.getSampleRate() : 0;
}
/**
* Getter for the Rhino context.
*
* @return Rhino context
*/
public String getContextInformation() throws PicovoiceException {
try {
return rhino != null ? rhino.getContextInformation() : "";
} catch (RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Getter for the version of Porcupine.
*
* @return Porcupine version
*/
public String getPorcupineVersion() {
return porcupine != null ? porcupine.getVersion() : "";
}
/**
* Getter for the version of Rhino.
*
* @return Rhino version
*/
public String getRhinoVersion() {
return rhino != null ? rhino.getVersion() : "";
}
/**
* Maps Porcupine/Rhino Exception to Picovoice Exception.
*/
private static PicovoiceException mapToPicovoiceException(Exception e) {
if (e instanceof PorcupineActivationException || e instanceof RhinoActivationException) {
return new PicovoiceActivationException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationLimitException || e instanceof RhinoActivationLimitException) {
return new PicovoiceActivationLimitException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationRefusedException || e instanceof RhinoActivationRefusedException) {
return new PicovoiceActivationRefusedException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationThrottledException ||
e instanceof RhinoActivationThrottledException) {
return new PicovoiceActivationThrottledException(e.getMessage(), e);
} else if (e instanceof PorcupineInvalidArgumentException || e instanceof RhinoInvalidArgumentException) {
return new PicovoiceInvalidArgumentException(e.getMessage(), e);
} else if (e instanceof PorcupineInvalidStateException || e instanceof RhinoInvalidStateException) {
return new PicovoiceInvalidStateException(e.getMessage(), e);
} else if (e instanceof PorcupineIOException || e instanceof RhinoIOException) {
return new PicovoiceIOException(e.getMessage(), e);
} else if (e instanceof PorcupineKeyException || e instanceof RhinoKeyException) {
return new PicovoiceKeyException(e.getMessage(), e);
} else if (e instanceof PorcupineMemoryException || e instanceof RhinoMemoryException) {
return new PicovoiceMemoryException(e.getMessage(), e);
} else if (e instanceof PorcupineRuntimeException || e instanceof RhinoRuntimeException) {
return new PicovoiceRuntimeException(e.getMessage(), e);
} else if (e instanceof PorcupineStopIterationException || e instanceof RhinoStopIterationException) {
return new PicovoiceStopIterationException(e.getMessage(), e);
} else if (e instanceof PorcupineException || e instanceof RhinoException) {
return new PicovoiceException(e.getMessage(), e);
} else {
return new PicovoiceException(
String.format("Unknown exception: '%s', message: '%s'",
e.getClass().getSimpleName(),
e.getMessage()), e);
}
}
/**
* Builder for creating an instance of Picovoice with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String porcupineModelPath = null;
private String keywordPath = null;
private float porcupineSensitivity = 0.5f;
private PicovoiceWakeWordCallback wakeWordCallback = null;
private String rhinoModelPath = null;
private String contextPath = null;
private float rhinoSensitivity = 0.5f;
private float endpointDurationSec = 1.0f;
private boolean requireEndpoint = true;
private PicovoiceInferenceCallback inferenceCallback = null;
/**
* Setter for AccessKey.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
*/
public Picovoice.Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
/**
* Setter for path to Porcupine model file.
*
* @param porcupineModelPath Absolute path to the file containing Porcupine's model parameters.
*/
public Picovoice.Builder setPorcupineModelPath(String porcupineModelPath) {
this.porcupineModelPath = porcupineModelPath;
return this;
}
/**
* Setter for path to Porcupine keyword file.
*
* @param keywordPath Absolute path to Porcupine's keyword model file.
*/
public Picovoice.Builder setKeywordPath(String keywordPath) {
this.keywordPath = keywordPath;
return this;
}
/**
* Setter for wake word engine sensitivity.
*
* @param porcupineSensitivity Wake word detection sensitivity. It should be a number within
* [0, 1]. A higher sensitivity results in fewer misses at the cost
* of increasing the false alarm rate.
*/
public Picovoice.Builder setPorcupineSensitivity(float porcupineSensitivity) {
this.porcupineSensitivity = porcupineSensitivity;
return this;
}
/**
* Setter for wake word detection callback.
*
* @param wakeWordCallback User-defined callback invoked upon detection of the wake phrase.
* ${@link PicovoiceWakeWordCallback} defines the interface of the
* callback.
*/
public Picovoice.Builder setWakeWordCallback(PicovoiceWakeWordCallback wakeWordCallback) {
this.wakeWordCallback = wakeWordCallback;
return this;
}
/**
* Setter for path to Rhino model file.
*
* @param rhinoModelPath Absolute path to the file containing Rhino's model parameters.
*/
public Picovoice.Builder setRhinoModelPath(String rhinoModelPath) {
this.rhinoModelPath = rhinoModelPath;
return this;
}
/**
* Setter for path to Rhino context file.
*
* @param contextPath Absolute path to file containing context parameters. A context
* represents the set of expressions (spoken commands), intents, and
* intent arguments (slots) within a domain of interest.
*/
public Picovoice.Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
/**
* Setter for inference engine sensitivity.
*
* @param rhinoSensitivity Inference sensitivity. It should be a number within [0, 1]. A
* higher sensitivity value results in fewer misses at the cost of
* (potentially) increasing the erroneous inference rate.
*/
public Picovoice.Builder setRhinoSensitivity(float rhinoSensitivity) {
this.rhinoSensitivity = rhinoSensitivity;
return this;
}
/**
* Setter for endpointDurationSec.
*
* @param endpointDurationSec Endpoint duration in seconds. An endpoint is a chunk of silence at the end of an
* utterance that marks the end of spoken command. It should be a positive number
* within [0.5, 5]. A lower endpoint duration reduces delay and improves
* responsiveness. A higher endpoint duration assures Rhino doesn't return inference
* pre-emptively in case the user pauses before finishing the request.
*/
public Picovoice.Builder setEndpointDurationSec(float endpointDurationSec) {
this.endpointDurationSec = endpointDurationSec;
return this;
}
/**
* Setter for requireEndpoint.
*
* @param requireEndpoint Boolean variable to indicate if Rhino should wait for a chunk of
* silence before finishing inference.
*/
public Picovoice.Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
/**
* Setter for intent inference callback.
*
* @param inferenceCallback User-defined callback invoked upon completion of intent inference.
* #{@link PicovoiceInferenceCallback} defines the interface of the
* callback.
*/
public Picovoice.Builder setInferenceCallback(PicovoiceInferenceCallback inferenceCallback) {
this.inferenceCallback = inferenceCallback;
return this;
}
/**
* Validates properties and creates an instance of the Porcupine wake word engine.
*
* @param appContext Android app context (for extracting Porcupine resources)
* @return An instance of Porcupine wake word engine
* @throws PicovoiceException if there is an error while initializing Porcupine.
*/
public Picovoice build(Context appContext) throws PicovoiceException {
try {
Porcupine porcupine = new Porcupine.Builder()
.setAccessKey(accessKey)
.setModelPath(porcupineModelPath)
.setKeywordPath(keywordPath)
.setSensitivity(porcupineSensitivity)
.build(appContext);
if (!porcupine.getVersion().startsWith("3.0.")) {
final String message = String.format(
"Expected Porcupine library with version '3.0.x' but received %s",
porcupine.getVersion());
throw new PicovoiceRuntimeException(message);
}
Rhino rhino = new Rhino.Builder()
.setAccessKey(accessKey)
.setModelPath(rhinoModelPath)
.setContextPath(contextPath)
.setSensitivity(rhinoSensitivity)
.setEndpointDurationSec(endpointDurationSec)
.setRequireEndpoint(requireEndpoint)
.build(appContext);
if (!rhino.getVersion().startsWith("3.0.")) {
final String message = String.format(
"Expected Rhino library with version '3.0.x' but received %s",
rhino.getVersion());
throw new PicovoiceRuntimeException(message);
}
return new Picovoice(
porcupine,
wakeWordCallback,
rhino,
inferenceCallback);
} catch (PorcupineException | RhinoException e) {
throw mapToPicovoiceException(e);
}
}
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/PicovoiceInferenceCallback.java
|
/*
Copyright 2020-2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
import ai.picovoice.rhino.RhinoInference;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public interface PicovoiceInferenceCallback {
void invoke(RhinoInference inference);
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/PicovoiceManager.java
|
/*
Copyright 2020-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
import android.content.Context;
import android.util.Log;
import ai.picovoice.android.voiceprocessor.VoiceProcessor;
import ai.picovoice.android.voiceprocessor.VoiceProcessorErrorListener;
import ai.picovoice.android.voiceprocessor.VoiceProcessorException;
import ai.picovoice.android.voiceprocessor.VoiceProcessorFrameListener;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceManager {
private final VoiceProcessor voiceProcessor;
private final VoiceProcessorFrameListener vpFrameListener;
private final VoiceProcessorErrorListener vpErrorListener;
private boolean isListening;
private Picovoice picovoice = null;
/**
* Private constructor.
*
* @param picovoice An instance of the Picovoice engine.
* @param processErrorCallback A callback that reports errors encountered while processing audio.
*/
private PicovoiceManager(
final Picovoice picovoice,
final PicovoiceManagerErrorCallback processErrorCallback) {
this.picovoice = picovoice;
this.voiceProcessor = VoiceProcessor.getInstance();
this.vpFrameListener = new VoiceProcessorFrameListener() {
@Override
public void onFrame(short[] frame) {
synchronized (voiceProcessor) {
if (picovoice == null || !isListening) {
return;
}
try {
picovoice.process(frame);
} catch (PicovoiceException e) {
if (processErrorCallback != null) {
processErrorCallback.invoke(new PicovoiceException(e));
} else {
Log.e("PicovoiceManager", e.toString());
}
}
}
}
};
this.vpErrorListener = new VoiceProcessorErrorListener() {
@Override
public void onError(VoiceProcessorException error) {
if (processErrorCallback != null) {
processErrorCallback.invoke(new PicovoiceException(error));
} else {
Log.e("PicovoiceManager", error.toString());
}
}
};
}
/**
* Releases resources acquired by Picovoice.
*/
public void delete() {
if (picovoice != null) {
picovoice.delete();
picovoice = null;
}
}
/**
* Resets the internal state of PicovoiceManager. It can be called to
* return to the wake word detection state before an inference has completed.
*
* @throws PicovoiceException if an error is encountered while attempting to stop.
*/
public void reset() throws PicovoiceException {
if (picovoice == null) {
throw new PicovoiceInvalidStateException("Cannot reset - resources have been released");
}
picovoice.reset();
}
/**
* Starts recording audio from the microphone and processes it using ${@link Picovoice}.
*
* @throws PicovoiceException if an error is encountered while attempting to start.
*/
public void start() throws PicovoiceException {
if (picovoice == null) {
throw new PicovoiceInvalidStateException("Cannot start - resources have been released");
}
if (!isListening) {
this.voiceProcessor.addFrameListener(vpFrameListener);
this.voiceProcessor.addErrorListener(vpErrorListener);
try {
voiceProcessor.start(picovoice.getFrameLength(), picovoice.getSampleRate());
isListening = true;
} catch (VoiceProcessorException e) {
throw new PicovoiceException(e);
}
}
}
/**
* Stops recording audio from the microphone.
*
* @throws PicovoiceException if an error is encountered while attempting to stop.
*/
public void stop() throws PicovoiceException {
if (picovoice == null) {
throw new PicovoiceInvalidStateException("Cannot stop - resources have been released");
}
if (isListening) {
voiceProcessor.removeErrorListener(vpErrorListener);
voiceProcessor.removeFrameListener(vpFrameListener);
if (voiceProcessor.getNumFrameListeners() == 0) {
try {
voiceProcessor.stop();
} catch (VoiceProcessorException e) {
throw new PicovoiceException(e);
}
}
isListening = false;
}
this.picovoice.reset();
}
/**
* Getter for the Rhino context.
*
* @return Rhino context
*/
public String getContextInformation() throws PicovoiceException {
return picovoice != null ? picovoice.getContextInformation() : "";
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return picovoice != null ? picovoice.getVersion() : "";
}
/**
* Getter for the version of Porcupine.
*
* @return Porcupine version
*/
public String getPorcupineVersion() {
return picovoice != null ? picovoice.getPorcupineVersion() : "";
}
/**
* Getter for the version of Rhino.
*
* @return Rhino version
*/
public String getRhinoVersion() {
return picovoice != null ? picovoice.getRhinoVersion() : "";
}
/**
* Builder for creating an instance of PicovoiceManager with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String porcupineModelPath = null;
private String keywordPath = null;
private float porcupineSensitivity = 0.5f;
private PicovoiceWakeWordCallback wakeWordCallback = null;
private String rhinoModelPath = null;
private String contextPath = null;
private float rhinoSensitivity = 0.5f;
private float endpointDurationSec = 1.0f;
private boolean requireEndpoint = true;
private PicovoiceInferenceCallback inferenceCallback = null;
private PicovoiceManagerErrorCallback processErrorCallback = null;
/**
* Setter for AccessKey.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
*/
public PicovoiceManager.Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
/**
* Setter for path to Porcupine model file.
*
* @param porcupineModelPath Absolute path to the file containing Porcupine's model parameters.
*/
public PicovoiceManager.Builder setPorcupineModelPath(String porcupineModelPath) {
this.porcupineModelPath = porcupineModelPath;
return this;
}
/**
* Setter for path to Porcupine keyword file.
*
* @param keywordPath Absolute path to Porcupine's keyword model file.
*/
public PicovoiceManager.Builder setKeywordPath(String keywordPath) {
this.keywordPath = keywordPath;
return this;
}
/**
* Setter for wake word engine sensitivity.
*
* @param porcupineSensitivity Wake word detection sensitivity. It should be a number within
* [0, 1]. A higher sensitivity results in fewer misses at the cost
* of increasing the false alarm rate.
*/
public PicovoiceManager.Builder setPorcupineSensitivity(float porcupineSensitivity) {
this.porcupineSensitivity = porcupineSensitivity;
return this;
}
/**
* Setter for wake word detection callback.
*
* @param wakeWordCallback User-defined callback invoked upon detection of the wake phrase.
* ${@link PicovoiceWakeWordCallback} defines the interface of the
* callback.
*/
public PicovoiceManager.Builder setWakeWordCallback(PicovoiceWakeWordCallback wakeWordCallback) {
this.wakeWordCallback = wakeWordCallback;
return this;
}
/**
* Setter for path to Rhino model file.
*
* @param rhinoModelPath Absolute path to the file containing Rhino's model parameters.
*/
public PicovoiceManager.Builder setRhinoModelPath(String rhinoModelPath) {
this.rhinoModelPath = rhinoModelPath;
return this;
}
/**
* Setter for path to Rhino context file.
*
* @param contextPath Absolute path to file containing context parameters. A context
* represents the set of expressions (spoken commands), intents, and
* intent arguments (slots) within a domain of interest.
*/
public PicovoiceManager.Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
/**
* Setter for inference engine sensitivity.
*
* @param rhinoSensitivity Inference sensitivity. It should be a number within [0, 1]. A
* higher sensitivity value results in fewer misses at the cost of
* (potentially) increasing the erroneous inference rate.
*/
public PicovoiceManager.Builder setRhinoSensitivity(float rhinoSensitivity) {
this.rhinoSensitivity = rhinoSensitivity;
return this;
}
/**
* Setter for endpointDurationSec.
*
* @param endpointDurationSec Endpoint duration in seconds. An endpoint is a chunk of silence at the end of an
* utterance that marks the end of spoken command. It should be a positive number
* within [0.5, 5]. A lower endpoint duration reduces delay and improves
* responsiveness. A higher endpoint duration assures Rhino doesn't return inference
* pre-emptively in case the user pauses before finishing the request.
*/
public PicovoiceManager.Builder setEndpointDurationSec(float endpointDurationSec) {
this.endpointDurationSec = endpointDurationSec;
return this;
}
/**
* Setter for requireEndpoint.
*
* @param requireEndpoint Boolean variable to indicate if Rhino should wait for a chunk of
* silence before finishing inference.
*/
public PicovoiceManager.Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
/**
* Setter for intent inference callback.
*
* @param inferenceCallback User-defined callback invoked upon completion of intent inference.
* #{@link PicovoiceInferenceCallback} defines the interface of the
* callback.
*/
public PicovoiceManager.Builder setInferenceCallback(PicovoiceInferenceCallback inferenceCallback) {
this.inferenceCallback = inferenceCallback;
return this;
}
/**
* Setter for error callback.
*
* @param processErrorCallback User-defined callback invoked when an error is encountered while
* processing audio. #{@link PicovoiceManagerErrorCallback} defines
* the interface of the callback.
*/
public PicovoiceManager.Builder setProcessErrorCallback(PicovoiceManagerErrorCallback processErrorCallback) {
this.processErrorCallback = processErrorCallback;
return this;
}
/**
* Validates properties and creates an instance of the PicovoiceManager.
*
* @param appContext Android app context (for extracting Picovoice resources)
* @return An instance of PicovoiceManager
*/
public PicovoiceManager build(Context appContext) throws PicovoiceException {
Picovoice picovoice = new Picovoice.Builder()
.setAccessKey(accessKey)
.setPorcupineModelPath(porcupineModelPath)
.setKeywordPath(keywordPath)
.setPorcupineSensitivity(porcupineSensitivity)
.setWakeWordCallback(wakeWordCallback)
.setRhinoModelPath(rhinoModelPath)
.setContextPath(contextPath)
.setRhinoSensitivity(rhinoSensitivity)
.setEndpointDurationSec(endpointDurationSec)
.setRequireEndpoint(requireEndpoint)
.setInferenceCallback(inferenceCallback)
.build(appContext);
return new PicovoiceManager(
picovoice,
processErrorCallback);
}
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/PicovoiceManagerErrorCallback.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public interface PicovoiceManagerErrorCallback {
void invoke(PicovoiceException e);
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/PicovoiceWakeWordCallback.java
|
/*
Copyright 2020-2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public interface PicovoiceWakeWordCallback {
void invoke();
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceActivationException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceActivationException extends PicovoiceException {
PicovoiceActivationException(Throwable cause) {
super(cause);
}
PicovoiceActivationException(String message) {
super(message);
}
PicovoiceActivationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceActivationLimitException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceActivationLimitException extends PicovoiceException {
PicovoiceActivationLimitException(Throwable cause) {
super(cause);
}
PicovoiceActivationLimitException(String message) {
super(message);
}
PicovoiceActivationLimitException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceActivationRefusedException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceActivationRefusedException extends PicovoiceException {
PicovoiceActivationRefusedException(Throwable cause) {
super(cause);
}
PicovoiceActivationRefusedException(String message) {
super(message);
}
PicovoiceActivationRefusedException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceActivationThrottledException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceActivationThrottledException extends PicovoiceException {
PicovoiceActivationThrottledException(Throwable cause) {
super(cause);
}
PicovoiceActivationThrottledException(String message) {
super(message);
}
PicovoiceActivationThrottledException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceException.java
|
/*
Copyright 2020-2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceException extends Exception {
PicovoiceException(Throwable cause) {
super(cause);
}
PicovoiceException(String message) {
super(message);
}
PicovoiceException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceIOException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceIOException extends PicovoiceException {
PicovoiceIOException(Throwable cause) {
super(cause);
}
PicovoiceIOException(String message) {
super(message);
}
PicovoiceIOException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceInvalidArgumentException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceInvalidArgumentException extends PicovoiceException {
PicovoiceInvalidArgumentException(Throwable cause) {
super(cause);
}
PicovoiceInvalidArgumentException(String message) {
super(message);
}
PicovoiceInvalidArgumentException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceInvalidStateException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceInvalidStateException extends PicovoiceException {
PicovoiceInvalidStateException(Throwable cause) {
super(cause);
}
PicovoiceInvalidStateException(String message) {
super(message);
}
PicovoiceInvalidStateException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceKeyException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceKeyException extends PicovoiceException {
PicovoiceKeyException(Throwable cause) {
super(cause);
}
PicovoiceKeyException(String message) {
super(message);
}
PicovoiceKeyException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceMemoryException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceMemoryException extends PicovoiceException {
PicovoiceMemoryException(Throwable cause) {
super(cause);
}
PicovoiceMemoryException(String message) {
super(message);
}
PicovoiceMemoryException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceRuntimeException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceRuntimeException extends PicovoiceException {
PicovoiceRuntimeException(Throwable cause) {
super(cause);
}
PicovoiceRuntimeException(String message) {
super(message);
}
PicovoiceRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-android/3.0.2/ai/picovoice/picovoice/exception/PicovoiceStopIterationException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
/**
* @deprecated This package is deprecated and will no longer be maintained. Use Porcupine and Rhino
* instead.
*/
@Deprecated
public class PicovoiceStopIterationException extends PicovoiceException {
PicovoiceStopIterationException(Throwable cause) {
super(cause);
}
PicovoiceStopIterationException(String message) {
super(message);
}
PicovoiceStopIterationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/Picovoice.java
|
/*
Copyright 2020-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
import ai.picovoice.porcupine.*;
import ai.picovoice.rhino.*;
/**
* Java binding for Picovoice end-to-end platform. Picovoice enables building voice experiences
* similar to Alexa but runs entirely on-device (offline).
*
* <p>Picovoice detects utterances of a customizable wake word (phrase) within an incoming stream of
* audio in real-time. After detection of wake word, it begins to infer the user's intent from the
* follow-on spoken command. Upon detection of wake word and completion of voice command, it invokes
* user-provided callbacks to signal these events.
*
* <p>Picovoice processes incoming audio in consecutive frames. The number of samples per frame is
* ${@link #getFrameLength()}. The incoming audio needs to have a sample rate equal to
* ${@link #getSampleRate()} and be 16-bit linearly-encoded. Picovoice operates on single-channel
* audio. It uses Porcupine wake word engine for wake word detection and Rhino Speech-to-Intent
* engine for intent inference.
*/
public class Picovoice {
private Porcupine porcupine;
private final PicovoiceWakeWordCallback wakeWordCallback;
private boolean isWakeWordDetected = false;
private Rhino rhino;
private final PicovoiceInferenceCallback inferenceCallback;
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
* @param porcupineModelPath Absolute path to the file containing Porcupine's model parameters.
* @param keywordPath Absolute path to Porcupine's keyword model file.
* @param porcupineSensitivity Wake word detection sensitivity. It should be a number within
* [0, 1]. A higher sensitivity results in fewer misses at the cost
* of increasing the false alarm rate.
* @param wakeWordCallback User-defined callback invoked upon detection of the wake phrase.
* ${@link PicovoiceWakeWordCallback} defines the interface of the
* callback.
* @param rhinoModelPath Absolute path to the file containing Rhino's model parameters.
* @param contextPath Absolute path to file containing context parameters. A context
* represents the set of expressions (spoken commands), intents, and
* intent arguments (slots) within a domain of interest.
* @param rhinoSensitivity Inference sensitivity. It should be a number within [0, 1]. A
* higher sensitivity value results in fewer misses at the cost of
* (potentially) increasing the erroneous inference rate.
* @param endpointDurationSec Endpoint duration in seconds. An endpoint is a chunk of silence at the end of an
* utterance that marks the end of spoken command. It should be a positive number
* within [0.5, 5]. A lower endpoint duration reduces delay and improves
* responsiveness. A higher endpoint duration assures Rhino doesn't return inference
* pre-emptively in case the user pauses before finishing the request.
* @param requireEndpoint If set to `true`, Rhino requires an endpoint (a chunk of silence) after the
* spoken command. If set to `false`, Rhino tries to detect silence, but if it cannot,
* it still will provide inference regardless. Set to `false` only if operating in
* an environment with overlapping speech (e.g. people talking in the background).
* @param inferenceCallback User-defined callback invoked upon completion of intent inference.
* #{@link PicovoiceInferenceCallback} defines the interface of the
* callback.
* @throws PicovoiceException if there is an error while initializing.
*/
public Picovoice(
String accessKey,
String porcupineLibraryPath,
String porcupineModelPath,
String keywordPath,
float porcupineSensitivity,
PicovoiceWakeWordCallback wakeWordCallback,
String rhinoLibraryPath,
String rhinoModelPath,
String contextPath,
float rhinoSensitivity,
float endpointDurationSec,
boolean requireEndpoint,
PicovoiceInferenceCallback inferenceCallback) throws PicovoiceException {
if (wakeWordCallback == null) {
final String message = String.format("Wake word callback is required");
throw new PicovoiceInvalidArgumentException(message);
}
if (inferenceCallback == null) {
final String message = String.format("Inference callback is required");
throw new PicovoiceInvalidArgumentException(message);
}
try {
porcupine = new Porcupine.Builder()
.setAccessKey(accessKey)
.setLibraryPath(porcupineLibraryPath)
.setModelPath(porcupineModelPath)
.setSensitivity(porcupineSensitivity)
.setKeywordPath(keywordPath)
.build();
if (!porcupine.getVersion().startsWith("3.0.")) {
final String message = String.format(
"Expected Porcupine library with version '3.0.x' but received %s",
porcupine.getVersion());
throw new PicovoiceException(message);
}
this.wakeWordCallback = wakeWordCallback;
rhino = new Rhino.Builder()
.setAccessKey(accessKey)
.setLibraryPath(rhinoLibraryPath)
.setModelPath(rhinoModelPath)
.setContextPath(contextPath)
.setSensitivity(rhinoSensitivity)
.setEndpointDuration(endpointDurationSec)
.setRequireEndpoint(requireEndpoint)
.build();
if (!rhino.getVersion().startsWith("3.0.")) {
final String message = String.format(
"Expected Rhino library with version '3.0.x' but received %s",
rhino.getVersion());
throw new PicovoiceException(message);
}
if (rhino.getFrameLength() != porcupine.getFrameLength()) {
final String message = String.format(
"Incompatible frame lengths for Porcupine and Rhino engines: '%d' and '%d' samples",
porcupine.getFrameLength(),
rhino.getFrameLength());
throw new PicovoiceException(message);
}
if (rhino.getSampleRate() != porcupine.getSampleRate()) {
final String message = String.format(
"Incompatible sample rates for Porcupine and Rhino engines: '%d' and '%d' Hz",
porcupine.getSampleRate(),
rhino.getSampleRate());
throw new PicovoiceException(message);
}
this.inferenceCallback = inferenceCallback;
} catch (PorcupineException | RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Releases resources acquired.
*/
public void delete() {
if (porcupine != null) {
porcupine.delete();
porcupine = null;
}
if (rhino != null) {
rhino.delete();
rhino = null;
}
}
/**
* Processes a frame of the incoming audio stream. Upon detection of wake word and completion
* of follow-on command inference invokes user-defined callbacks.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by calling
* ${@link #getFrameLength()}. The incoming audio needs to have a sample rate equal
* to ${@link #getSampleRate()} and be 16-bit linearly-encoded. Picovoice operates on
* single-channel audio.
* @throws PicovoiceException if there is an error while processing the audio frame.
*/
public void process(short[] pcm) throws PicovoiceException {
if (porcupine == null || rhino == null) {
throw new PicovoiceInvalidStateException("Cannot process frame - resources have been released");
}
if (pcm == null) {
throw new PicovoiceInvalidArgumentException("Passed null frame to Picovoice process.");
}
if (pcm.length != getFrameLength()) {
throw new PicovoiceInvalidArgumentException(
String.format("Picovoice process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
try {
if (!isWakeWordDetected) {
isWakeWordDetected = (porcupine.process(pcm) == 0);
if (isWakeWordDetected) {
wakeWordCallback.invoke();
}
} else {
if (rhino.process(pcm)) {
inferenceCallback.invoke(rhino.getInference());
isWakeWordDetected = false;
}
}
} catch (PorcupineException | RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Resets the internal state of Picovoice. It should be called before processing a new stream of audio
* or when Picovoice was stopped while processing a stream of audio.
*
* @throws PicovoiceException if reset fails.
*/
public void reset() throws PicovoiceException {
try {
this.isWakeWordDetected = false;
this.rhino.reset();
} catch (RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return "3.0.0";
}
/**
* Getter for Porcupine version.
*
* @return Porcupine version.
*/
public String getPorcupineVersion() {
return porcupine != null ? porcupine.getVersion() : "";
}
/**
* Getter for Rhino version.
*
* @return Rhino version.
*/
public String getRhinoVersion() {
return rhino != null ? rhino.getVersion() : "";
}
/**
* Getter for number of audio samples per frame.
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return porcupine != null ? porcupine.getFrameLength() : 0;
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return porcupine != null ? porcupine.getSampleRate() : 0;
}
/**
* Getter for the Rhino context.
*
* @return Rhino context
*/
public String getContextInformation() throws PicovoiceException {
try {
return rhino != null ? rhino.getContextInformation() : "";
} catch (RhinoException e) {
throw mapToPicovoiceException(e);
}
}
/**
* Maps Porcupine/Rhino Exception to Picovoice Exception.
*/
private static PicovoiceException mapToPicovoiceException(Exception e) {
if (e instanceof PorcupineActivationException || e instanceof RhinoActivationException) {
return new PicovoiceActivationException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationLimitException || e instanceof RhinoActivationLimitException) {
return new PicovoiceActivationLimitException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationRefusedException || e instanceof RhinoActivationRefusedException) {
return new PicovoiceActivationRefusedException(e.getMessage(), e);
} else if (e instanceof PorcupineActivationThrottledException ||
e instanceof RhinoActivationThrottledException) {
return new PicovoiceActivationThrottledException(e.getMessage(), e);
} else if (e instanceof PorcupineInvalidArgumentException || e instanceof RhinoInvalidArgumentException) {
return new PicovoiceInvalidArgumentException(e.getMessage(), e);
} else if (e instanceof PorcupineInvalidStateException || e instanceof RhinoInvalidStateException) {
return new PicovoiceInvalidStateException(e.getMessage(), e);
} else if (e instanceof PorcupineIOException || e instanceof RhinoIOException) {
return new PicovoiceIOException(e.getMessage(), e);
} else if (e instanceof PorcupineKeyException || e instanceof RhinoKeyException) {
return new PicovoiceKeyException(e.getMessage(), e);
} else if (e instanceof PorcupineMemoryException || e instanceof RhinoMemoryException) {
return new PicovoiceMemoryException(e.getMessage(), e);
} else if (e instanceof PorcupineRuntimeException || e instanceof RhinoRuntimeException) {
return new PicovoiceRuntimeException(e.getMessage(), e);
} else if (e instanceof PorcupineStopIterationException || e instanceof RhinoStopIterationException) {
return new PicovoiceStopIterationException(e.getMessage(), e);
} else if (e instanceof PorcupineException || e instanceof RhinoException) {
return new PicovoiceException(e.getMessage(), e);
} else {
return new PicovoiceException(
String.format("Unknown exception: '%s', message: '%s'",
e.getClass().getSimpleName(),
e.getMessage()), e);
}
}
/**
* Builder for creating an instance of Picovoice with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String porcupineLibraryPath = null;
private String porcupineModelPath = null;
private String keywordPath = null;
private float porcupineSensitivity = 0.5f;
private PicovoiceWakeWordCallback wakeWordCallback = null;
private String rhinoLibraryPath = null;
private String rhinoModelPath = null;
private String contextPath = null;
private float rhinoSensitivity = 0.5f;
private float rhinoEndpointDuration = 1.0f;
private boolean requireEndpoint = true;
private PicovoiceInferenceCallback inferenceCallback = null;
public Picovoice.Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Picovoice.Builder setPorcupineLibraryPath(String porcupineLibraryPath) {
this.porcupineLibraryPath = porcupineLibraryPath;
return this;
}
public Picovoice.Builder setPorcupineModelPath(String porcupineModelPath) {
this.porcupineModelPath = porcupineModelPath;
return this;
}
public Picovoice.Builder setKeywordPath(String keywordPath) {
this.keywordPath = keywordPath;
return this;
}
public Picovoice.Builder setPorcupineSensitivity(float porcupineSensitivity) {
this.porcupineSensitivity = porcupineSensitivity;
return this;
}
public Picovoice.Builder setWakeWordCallback(PicovoiceWakeWordCallback wakeWordCallback) {
this.wakeWordCallback = wakeWordCallback;
return this;
}
public Picovoice.Builder setRhinoLibraryPath(String rhinoLibraryPath) {
this.rhinoLibraryPath = rhinoLibraryPath;
return this;
}
public Picovoice.Builder setRhinoModelPath(String rhinoModelPath) {
this.rhinoModelPath = rhinoModelPath;
return this;
}
public Picovoice.Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
public Picovoice.Builder setRhinoSensitivity(float rhinoSensitivity) {
this.rhinoSensitivity = rhinoSensitivity;
return this;
}
public Picovoice.Builder setRhinoEndpointDuration(float rhinoEndpointDuration) {
this.rhinoEndpointDuration = rhinoEndpointDuration;
return this;
}
public Picovoice.Builder setInferenceCallback(PicovoiceInferenceCallback inferenceCallback) {
this.inferenceCallback = inferenceCallback;
return this;
}
public Picovoice.Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
/**
* Validates properties and creates an instance of the Picovoice end-to-end platform.
*
* @return An instance of Picovoice
* @throws PicovoiceException if there is an error while initializing Picovoice.
*/
public Picovoice build() throws PicovoiceException {
return new Picovoice(
accessKey,
porcupineLibraryPath,
porcupineModelPath,
keywordPath,
porcupineSensitivity,
wakeWordCallback,
rhinoLibraryPath,
rhinoModelPath,
contextPath,
rhinoSensitivity,
rhinoEndpointDuration,
requireEndpoint,
inferenceCallback);
}
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/PicovoiceInferenceCallback.java
|
/*
Copyright 2020 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
import ai.picovoice.rhino.RhinoInference;
public interface PicovoiceInferenceCallback {
void invoke(RhinoInference inference);
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/PicovoiceWakeWordCallback.java
|
/*
Copyright 2020 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public interface PicovoiceWakeWordCallback {
void invoke();
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceActivationException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceActivationException extends PicovoiceException {
PicovoiceActivationException(Throwable cause) {
super(cause);
}
PicovoiceActivationException(String message) {
super(message);
}
PicovoiceActivationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceActivationLimitException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceActivationLimitException extends PicovoiceException {
PicovoiceActivationLimitException(Throwable cause) {
super(cause);
}
PicovoiceActivationLimitException(String message) {
super(message);
}
PicovoiceActivationLimitException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceActivationRefusedException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceActivationRefusedException extends PicovoiceException {
PicovoiceActivationRefusedException(Throwable cause) {
super(cause);
}
PicovoiceActivationRefusedException(String message) {
super(message);
}
PicovoiceActivationRefusedException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceActivationThrottledException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceActivationThrottledException extends PicovoiceException {
PicovoiceActivationThrottledException(Throwable cause) {
super(cause);
}
PicovoiceActivationThrottledException(String message) {
super(message);
}
PicovoiceActivationThrottledException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceException.java
|
/*
Copyright 2020-2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceException extends Exception {
PicovoiceException(Throwable cause) {
super(cause);
}
PicovoiceException(String message) {
super(message);
}
PicovoiceException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceIOException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceIOException extends PicovoiceException {
PicovoiceIOException(Throwable cause) {
super(cause);
}
PicovoiceIOException(String message) {
super(message);
}
PicovoiceIOException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceInvalidArgumentException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceInvalidArgumentException extends PicovoiceException {
PicovoiceInvalidArgumentException(Throwable cause) {
super(cause);
}
PicovoiceInvalidArgumentException(String message) {
super(message);
}
PicovoiceInvalidArgumentException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceInvalidStateException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceInvalidStateException extends PicovoiceException {
PicovoiceInvalidStateException(Throwable cause) {
super(cause);
}
PicovoiceInvalidStateException(String message) {
super(message);
}
PicovoiceInvalidStateException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceKeyException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceKeyException extends PicovoiceException {
PicovoiceKeyException(Throwable cause) {
super(cause);
}
PicovoiceKeyException(String message) {
super(message);
}
PicovoiceKeyException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceMemoryException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceMemoryException extends PicovoiceException {
PicovoiceMemoryException(Throwable cause) {
super(cause);
}
PicovoiceMemoryException(String message) {
super(message);
}
PicovoiceMemoryException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceRuntimeException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceRuntimeException extends PicovoiceException {
PicovoiceRuntimeException(Throwable cause) {
super(cause);
}
PicovoiceRuntimeException(String message) {
super(message);
}
PicovoiceRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice
|
java-sources/ai/picovoice/picovoice-java/3.0.5/ai/picovoice/picovoice/exception/PicovoiceStopIterationException.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.picovoice;
public class PicovoiceStopIterationException extends PicovoiceException {
PicovoiceStopIterationException(Throwable cause) {
super(cause);
}
PicovoiceStopIterationException(String message) {
super(message);
}
PicovoiceStopIterationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/Porcupine.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
import android.content.Context;
import android.content.res.Resources;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
/**
* Android binding for Porcupine wake word engine. It detects utterances of given keywords within an
* incoming stream of audio in real-time. It processes incoming audio in consecutive frames and for
* each frame emits the detection result. The number of samples per frame can be attained by calling
* {@link #getFrameLength()}. The incoming audio needs to have a sample rate equal to
* {@link #getSampleRate()} and be 16-bit linearly-encoded. Porcupine operates on single-channel
* audio.
*/
public class Porcupine {
private static final int[] KEYWORDS_RESOURCES = {
R.raw.alexa, R.raw.americano, R.raw.blueberry, R.raw.bumblebee, R.raw.computer, R.raw.grapefruit,
R.raw.grasshopper, R.raw.hey_google, R.raw.hey_siri, R.raw.jarvis, R.raw.ok_google, R.raw.picovoice,
R.raw.porcupine, R.raw.terminator,
};
private static final HashMap<BuiltInKeyword, String> BUILT_IN_KEYWORD_PATHS = new HashMap<>();
private static String DEFAULT_MODEL_PATH;
private static boolean isExtracted;
private static String _sdk = "android";
static {
System.loadLibrary("pv_porcupine");
}
private long handle;
public static void setSdk(String sdk) {
Porcupine._sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param modelPath Absolute path to the file containing model parameters.
* @param keywordPaths Absolute paths to keyword model files.
* @param sensitivities Sensitivities for detecting keywords. Each value should be a number
* within [0, 1]. A higher sensitivity results in fewer misses at the cost
* of increasing the false alarm rate.
* @throws PorcupineException if there is an error while initializing Porcupine.
*/
private Porcupine(
String accessKey,
String modelPath,
String[] keywordPaths,
float[] sensitivities) throws PorcupineException {
PorcupineNative.setSdk(Porcupine._sdk);
handle = PorcupineNative.init(
accessKey,
modelPath,
keywordPaths,
sensitivities);
}
/**
* Releases resources acquired by Porcupine.
*/
public void delete() {
if (handle != 0) {
PorcupineNative.delete(handle);
handle = 0;
}
}
/**
* Processes a frame of the incoming audio stream and emits the detection result.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by
* calling {@link #getFrameLength()}. The incoming audio needs to have a sample rate
* equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Porcupine
* operates on single-channel audio.
* @return Index of observed keyword at the end of the current frame. Indexing is 0-based and
* matches the ordering of keyword models provided to the constructor. If no keyword is detected
* then it returns -1.
* @throws PorcupineException if there is an error while processing the audio frame.
*/
public int process(short[] pcm) throws PorcupineException {
if (handle == 0) {
throw new PorcupineInvalidStateException("Attempted to call Porcupine process after delete.");
}
if (pcm == null) {
throw new PorcupineInvalidArgumentException("Passed null frame to Porcupine process.");
}
if (pcm.length != getFrameLength()) {
throw new PorcupineInvalidArgumentException(
String.format("Porcupine process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
return PorcupineNative.process(handle, pcm);
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return PorcupineNative.getVersion();
}
/**
* Getter for number of audio samples per frame..
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return PorcupineNative.getFrameLength();
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return PorcupineNative.getSampleRate();
}
/**
* Porcupine BuiltInKeywords.
*/
public enum BuiltInKeyword {
ALEXA,
AMERICANO,
BLUEBERRY,
BUMBLEBEE,
COMPUTER,
GRAPEFRUIT,
GRASSHOPPER,
HEY_GOOGLE,
HEY_SIRI,
JARVIS,
OK_GOOGLE,
PICOVOICE,
PORCUPINE,
TERMINATOR
}
/**
* Builder for creating an instance of Porcupine with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private String[] keywordPaths = null;
private BuiltInKeyword[] keywords = null;
private float[] sensitivities = null;
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public Builder setKeywordPaths(String[] keywordPaths) {
this.keywordPaths = keywordPaths;
return this;
}
public Builder setKeywordPath(String keywordPaths) {
this.keywordPaths = new String[]{keywordPaths};
return this;
}
public Builder setKeywords(BuiltInKeyword[] keywords) {
this.keywords = keywords;
return this;
}
public Builder setKeyword(BuiltInKeyword keyword) {
this.keywords = new BuiltInKeyword[]{keyword};
return this;
}
public Builder setSensitivities(float[] sensitivities) {
this.sensitivities = sensitivities;
return this;
}
public Builder setSensitivity(float sensitivity) {
this.sensitivities = new float[]{sensitivity};
return this;
}
private void extractPackageResources(Context context) throws PorcupineIOException {
final Resources resources = context.getResources();
try {
for (final int resourceId : KEYWORDS_RESOURCES) {
final String keywordName = resources.getResourceEntryName(resourceId);
final String keywordPath = extractResource(context,
resources.openRawResource(resourceId),
keywordName + ".ppn");
BUILT_IN_KEYWORD_PATHS.put(
BuiltInKeyword.valueOf(keywordName.toUpperCase(Locale.ENGLISH)), keywordPath
);
}
DEFAULT_MODEL_PATH = extractResource(context,
resources.openRawResource(R.raw.porcupine_params),
resources.getResourceEntryName(R.raw.porcupine_params) + ".pv");
isExtracted = true;
} catch (IOException ex) {
throw new PorcupineIOException(ex);
}
}
private String extractResource(Context context, InputStream srcFileStream, String dstFilename)
throws IOException {
InputStream is = new BufferedInputStream(srcFileStream, 256);
OutputStream os = new BufferedOutputStream(context.openFileOutput(dstFilename, Context.MODE_PRIVATE), 256);
int r;
while ((r = is.read()) != -1) {
os.write(r);
}
os.flush();
is.close();
os.close();
return new File(context.getFilesDir(), dstFilename).getAbsolutePath();
}
/**
* Validates properties and creates an instance of the Porcupine wake word engine.
*
* @param context Android app context (for extracting Porcupine resources)
* @return An instance of Porcupine wake word engine
* @throws PorcupineException if there is an error while initializing Porcupine.
*/
public Porcupine build(Context context) throws PorcupineException {
if (!isExtracted) {
extractPackageResources(context);
}
if (modelPath == null) {
modelPath = DEFAULT_MODEL_PATH;
} else {
File modelFile = new File(modelPath);
String modelFilename = modelFile.getName();
if (!modelFile.exists() && !modelFilename.equals("")) {
try {
modelPath = extractResource(context,
context.getAssets().open(modelPath),
modelFilename);
} catch (IOException ex) {
throw new PorcupineIOException(ex);
}
}
}
if (this.accessKey == null || this.accessKey.equals("")) {
throw new PorcupineInvalidArgumentException("No AccessKey provided to Porcupine.");
}
if (this.keywordPaths != null && this.keywords != null) {
throw new PorcupineInvalidArgumentException("Both 'keywords' and 'keywordPaths' were set. " +
"Only one of the two arguments may be set for initialization.");
}
if (this.keywordPaths == null) {
if (this.keywords == null) {
throw new PorcupineInvalidArgumentException("Either 'keywords' or 'keywordPaths' must be set.");
}
this.keywordPaths = new String[keywords.length];
for (int i = 0; i < keywords.length; i++) {
this.keywordPaths[i] = BUILT_IN_KEYWORD_PATHS.get(keywords[i]);
}
} else {
for (int i = 0; i < keywordPaths.length; i++) {
if (keywordPaths[i] == null || keywordPaths[i].equals("")) {
throw new PorcupineInvalidArgumentException("Empty keyword path passed to Porcupine.");
}
File keywordFile = new File(keywordPaths[i]);
String keywordFilename = keywordFile.getName();
if (!keywordFile.exists() && !keywordFilename.equals("")) {
try {
keywordPaths[i] = extractResource(context,
context.getAssets().open(keywordPaths[i]),
keywordFilename);
} catch (IOException ex) {
throw new PorcupineIOException(ex);
}
}
}
}
if (sensitivities == null) {
sensitivities = new float[keywordPaths.length];
Arrays.fill(sensitivities, 0.5f);
}
if (sensitivities.length != keywordPaths.length) {
throw new PorcupineInvalidArgumentException(
String.format("Number of keywords (%d) " +
"does not match number of sensitivities (%d)",
keywordPaths.length,
sensitivities.length));
}
return new Porcupine(accessKey, modelPath, keywordPaths, sensitivities);
}
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/PorcupineManager.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
import android.content.Context;
import android.util.Log;
import ai.picovoice.android.voiceprocessor.VoiceProcessor;
import ai.picovoice.android.voiceprocessor.VoiceProcessorErrorListener;
import ai.picovoice.android.voiceprocessor.VoiceProcessorException;
import ai.picovoice.android.voiceprocessor.VoiceProcessorFrameListener;
/**
* High-level Android binding for Porcupine wake word engine. It handles recording audio from
* microphone, processes it in real-time using Porcupine, and notifies the client when any of the
* given keywords are detected. For detailed information regarding Porcupine refer to
* ${@link Porcupine}.
*/
public class PorcupineManager {
private final Porcupine porcupine;
private final VoiceProcessor voiceProcessor;
private final VoiceProcessorFrameListener vpFrameListener;
private final VoiceProcessorErrorListener vpErrorListener;
private boolean isListening;
/**
* Private constructor.
*
* @param porcupine An instance of the Porcupine wake word engine.
* @param callback A callback function that is invoked upon detection of any of the keywords.
* @param errorCallback A callback that reports errors encountered while processing audio.
*/
private PorcupineManager(final Porcupine porcupine,
final PorcupineManagerCallback callback,
final PorcupineManagerErrorCallback errorCallback) {
this.porcupine = porcupine;
this.voiceProcessor = VoiceProcessor.getInstance();
this.vpFrameListener = new VoiceProcessorFrameListener() {
@Override
public void onFrame(short[] frame) {
try {
int keywordIndex = porcupine.process(frame);
if (keywordIndex >= 0) {
callback.invoke(keywordIndex);
}
} catch (PorcupineException e) {
if (errorCallback != null) {
errorCallback.invoke(e);
} else {
Log.e("PorcupineManager", e.toString());
}
}
}
};
this.vpErrorListener = new VoiceProcessorErrorListener() {
@Override
public void onError(VoiceProcessorException error) {
if (errorCallback != null) {
errorCallback.invoke(new PorcupineException(error));
} else {
Log.e("PorcupineManager", error.toString());
}
}
};
}
/**
* Releases resources acquired by Porcupine. It should be called when disposing the object.
*/
public void delete() {
porcupine.delete();
}
/**
* Starts recording audio from the microphone and monitors it for the utterances of the given
* set of keywords.
*/
public void start() throws PorcupineException {
if (isListening) {
return;
}
this.voiceProcessor.addFrameListener(vpFrameListener);
this.voiceProcessor.addErrorListener(vpErrorListener);
try {
voiceProcessor.start(porcupine.getFrameLength(), porcupine.getSampleRate());
} catch (VoiceProcessorException e) {
throw new PorcupineException(e);
}
isListening = true;
}
/**
* Stops recording audio from the microphone.
*
* @throws PorcupineException if there's a problem stopping the recording.
*/
public void stop() throws PorcupineException {
if (!isListening) {
return;
}
voiceProcessor.removeErrorListener(vpErrorListener);
voiceProcessor.removeFrameListener(vpFrameListener);
if (voiceProcessor.getNumFrameListeners() == 0) {
try {
voiceProcessor.stop();
} catch (VoiceProcessorException e) {
throw new PorcupineException(e);
}
}
isListening = false;
}
/**
* Builder for creating an instance of PorcupineManager with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private String[] keywordPaths = null;
private Porcupine.BuiltInKeyword[] keywords = null;
private float[] sensitivities = null;
private PorcupineManagerErrorCallback errorCallback = null;
public PorcupineManager.Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public PorcupineManager.Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public PorcupineManager.Builder setKeywordPaths(String[] keywordPaths) {
this.keywordPaths = keywordPaths;
return this;
}
public PorcupineManager.Builder setKeywordPath(String keywordPaths) {
this.keywordPaths = new String[]{keywordPaths};
return this;
}
public PorcupineManager.Builder setKeywords(Porcupine.BuiltInKeyword[] keywords) {
this.keywords = keywords;
return this;
}
public PorcupineManager.Builder setKeyword(Porcupine.BuiltInKeyword keyword) {
this.keywords = new Porcupine.BuiltInKeyword[]{keyword};
return this;
}
public PorcupineManager.Builder setSensitivities(float[] sensitivities) {
this.sensitivities = sensitivities;
return this;
}
public PorcupineManager.Builder setSensitivity(float sensitivity) {
this.sensitivities = new float[]{sensitivity};
return this;
}
public PorcupineManager.Builder setErrorCallback(PorcupineManagerErrorCallback errorCallback) {
this.errorCallback = errorCallback;
return this;
}
/**
* Creates an instance of PorcupineManager.
*
* @param context Android app context (for extracting Porcupine resources)
* @param callback A callback function that is invoked upon detection of any of the keywords.
* @return A PorcupineManager instance
* @throws PorcupineException if there is an error while initializing Porcupine.
*/
public PorcupineManager build(
Context context,
PorcupineManagerCallback callback) throws PorcupineException {
Porcupine porcupine = new Porcupine.Builder()
.setAccessKey(accessKey)
.setModelPath(modelPath)
.setKeywordPaths(keywordPaths)
.setKeywords(keywords)
.setSensitivities(sensitivities)
.build(context);
return new PorcupineManager(porcupine, callback, errorCallback);
}
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/PorcupineManagerCallback.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public interface PorcupineManagerCallback {
void invoke(int keywordIndex);
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/PorcupineManagerErrorCallback.java
|
/*
Copyright 2021 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public interface PorcupineManagerErrorCallback {
void invoke(PorcupineException error);
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/PorcupineNative.java
|
/*
Copyright 2022-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
class PorcupineNative {
static native String getVersion();
static native int getFrameLength();
static native int getSampleRate();
static native void setSdk(String sdk);
static native long init(
String accessKey,
String modelPath,
String[] keywordPaths,
float[] sensitivities) throws PorcupineException;
static native void delete(long object);
static native int process(
long object,
short[] pcm) throws PorcupineException;
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineActivationException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineActivationException extends PorcupineException {
public PorcupineActivationException(Throwable cause) {
super(cause);
}
public PorcupineActivationException(String message) {
super(message);
}
public PorcupineActivationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineActivationLimitException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineActivationLimitException extends PorcupineException {
public PorcupineActivationLimitException(Throwable cause) {
super(cause);
}
public PorcupineActivationLimitException(String message) {
super(message);
}
public PorcupineActivationLimitException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineActivationRefusedException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineActivationRefusedException extends PorcupineException {
public PorcupineActivationRefusedException(Throwable cause) {
super(cause);
}
public PorcupineActivationRefusedException(String message) {
super(message);
}
public PorcupineActivationRefusedException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineActivationThrottledException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineActivationThrottledException extends PorcupineException {
public PorcupineActivationThrottledException(Throwable cause) {
super(cause);
}
public PorcupineActivationThrottledException(String message) {
super(message);
}
public PorcupineActivationThrottledException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
import android.annotation.SuppressLint;
public class PorcupineException extends Exception {
private final String message;
private final String[] messageStack;
public PorcupineException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public PorcupineException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public PorcupineException(String message, String[] messageStack) {
super(message);
this.message = message;
this.messageStack = messageStack;
}
public String[] getMessageStack() {
return this.messageStack;
}
@SuppressLint("DefaultLocale")
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(message);
if (messageStack != null) {
if (messageStack.length > 0) {
sb.append(":");
for (int i = 0; i < messageStack.length; i++) {
sb.append(String.format("\n [%d] %s", i, messageStack[i]));
}
}
}
return sb.toString();
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineIOException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineIOException extends PorcupineException {
public PorcupineIOException(Throwable cause) {
super(cause);
}
public PorcupineIOException(String message) {
super(message);
}
public PorcupineIOException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineInvalidArgumentException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineInvalidArgumentException extends PorcupineException {
public PorcupineInvalidArgumentException(Throwable cause) {
super(cause);
}
public PorcupineInvalidArgumentException(String message) {
super(message);
}
public PorcupineInvalidArgumentException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineInvalidStateException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineInvalidStateException extends PorcupineException {
public PorcupineInvalidStateException(Throwable cause) {
super(cause);
}
public PorcupineInvalidStateException(String message) {
super(message);
}
public PorcupineInvalidStateException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineKeyException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineKeyException extends PorcupineException {
public PorcupineKeyException(Throwable cause) {
super(cause);
}
public PorcupineKeyException(String message) {
super(message);
}
public PorcupineKeyException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineMemoryException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineMemoryException extends PorcupineException {
public PorcupineMemoryException(Throwable cause) {
super(cause);
}
public PorcupineMemoryException(String message) {
super(message);
}
public PorcupineMemoryException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineRuntimeException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineRuntimeException extends PorcupineException {
public PorcupineRuntimeException(Throwable cause) {
super(cause);
}
public PorcupineRuntimeException(String message) {
super(message);
}
public PorcupineRuntimeException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-android/3.0.3/ai/picovoice/porcupine/exception/PorcupineStopIterationException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineStopIterationException extends PorcupineException {
public PorcupineStopIterationException(Throwable cause) {
super(cause);
}
public PorcupineStopIterationException(String message) {
super(message);
}
public PorcupineStopIterationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice/porcupine/Porcupine.java
|
/*
Copyright 2018-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
import java.util.Arrays;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java binding for Porcupine wake word engine. It detects utterances of given keywords within an
* incoming stream of audio in real-time. It processes incoming audio in consecutive frames and for
* each frame emits the detection result. The number of samples per frame can be attained by calling
* {@link #getFrameLength()}. The incoming audio needs to have a sample rate equal to
* {@link #getSampleRate()} and be 16-bit linearly-encoded. Porcupine operates on single-channel
* audio.
*/
public class Porcupine {
public static final String LIBRARY_PATH;
public static final String MODEL_PATH;
public static final HashMap<BuiltInKeyword, String> BUILT_IN_KEYWORD_PATHS;
private static String sdk = "java";
static {
LIBRARY_PATH = Utils.getPackagedLibraryPath();
MODEL_PATH = Utils.getPackagedModelPath();
BUILT_IN_KEYWORD_PATHS = Utils.getPackagedKeywordPaths();
}
private long handle;
public static void setSdk(String sdk) {
Porcupine.sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console.
* @param libraryPath Absolute path to the native Porcupine library.
* @param modelPath Absolute path to the file containing model parameters.
* @param keywordPaths Absolute paths to keyword model files.
* @param sensitivities Sensitivities for detecting keywords. Each value should be a number
* within [0, 1]. A higher sensitivity results in fewer misses at the cost
* of increasing the false alarm rate.
* @throws PorcupineException if there is an error while initializing Porcupine.
*/
public Porcupine(
String accessKey,
String libraryPath,
String modelPath,
String[] keywordPaths,
float[] sensitivities) throws PorcupineException {
try {
System.load(libraryPath);
} catch (Exception exception) {
throw new PorcupineException(exception);
}
PorcupineNative.setSdk(Porcupine.sdk);
handle = PorcupineNative.init(
accessKey,
modelPath,
keywordPaths,
sensitivities);
}
/**
* Releases resources acquired by Porcupine.
*/
public void delete() {
if (handle != 0) {
PorcupineNative.delete(handle);
handle = 0;
}
}
/**
* Processes a frame of the incoming audio stream and emits the detection result.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by
* calling {@link #getFrameLength()}. The incoming audio needs to have a sample rate
* equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Porcupine
* operates on single-channel audio.
* @return Index of observed keyword at the end of the current frame. Indexing is 0-based and
* matches the ordering of keyword models provided to the constructor. If no
* keyword is detected then it returns -1.
* @throws PorcupineException if there is an error while processing the audio frame.
*/
public int process(short[] pcm) throws PorcupineException {
if (handle == 0) {
throw new PorcupineException(
new IllegalStateException("Attempted to call Porcupine process after delete."));
}
if (pcm == null) {
throw new PorcupineException(
new IllegalArgumentException("Passed null frame to Porcupine process."));
}
if (pcm.length != getFrameLength()) {
throw new PorcupineException(
new IllegalArgumentException(
String.format("Porcupine process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length)));
}
return PorcupineNative.process(handle, pcm);
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return PorcupineNative.getVersion();
}
/**
* Getter for number of audio samples per frame.
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return PorcupineNative.getFrameLength();
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return PorcupineNative.getSampleRate();
}
/**
* BuiltInKeyword Enum.
*/
public enum BuiltInKeyword {
ALEXA,
AMERICANO,
BLUEBERRY,
BUMBLEBEE,
COMPUTER,
GRAPEFRUIT,
GRASSHOPPER,
HEY_GOOGLE,
HEY_SIRI,
JARVIS,
OK_GOOGLE,
PICOVOICE,
PORCUPINE,
TERMINATOR;
public static Stream<BuiltInKeyword> stream() {
return Stream.of(BuiltInKeyword.values());
}
public static String options() {
return BuiltInKeyword.stream().map((v) -> v.name()).collect(Collectors.joining(","));
}
}
/**
* Builder for creating an instance of Porcupine with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String libraryPath = null;
private String modelPath = null;
private String[] keywordPaths = null;
private BuiltInKeyword[] keywords = null;
private float[] sensitivities = null;
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Builder setLibraryPath(String libraryPath) {
this.libraryPath = libraryPath;
return this;
}
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public Builder setKeywordPaths(String[] keywordPaths) {
this.keywordPaths = keywordPaths;
return this;
}
public Builder setKeywordPath(String keywordPaths) {
this.keywordPaths = new String[]{keywordPaths};
return this;
}
public Builder setBuiltInKeywords(BuiltInKeyword[] keywords) {
this.keywords = keywords;
return this;
}
public Builder setBuiltInKeyword(BuiltInKeyword keyword) {
this.keywords = new BuiltInKeyword[]{keyword};
return this;
}
public Builder setSensitivities(float[] sensitivities) {
this.sensitivities = sensitivities;
return this;
}
public Builder setSensitivity(float sensitivity) {
this.sensitivities = new float[]{sensitivity};
return this;
}
/**
* Validates properties and creates an instance of the Porcupine wake word engine.
*
* @return An instance of Porcupine wake word engine
* @throws PorcupineException if there is an error while initializing Porcupine.
*/
public Porcupine build() throws PorcupineException {
if (!Utils.isEnvironmentSupported()) {
throw new PorcupineRuntimeException("Could not initialize Porcupine. " +
"Execution environment not currently supported by Porcupine Java.");
}
if (accessKey == null) {
throw new PorcupineInvalidArgumentException(
"AccessKey is required for Porcupine initialization.");
}
if (libraryPath == null) {
if (Utils.isResourcesAvailable()) {
libraryPath = LIBRARY_PATH;
} else {
throw new PorcupineInvalidArgumentException("Default library unavailable. " +
"Please provide a native Porcupine library path (-l <library_path>).");
}
}
if (modelPath == null) {
if (Utils.isResourcesAvailable()) {
modelPath = MODEL_PATH;
} else {
throw new PorcupineInvalidArgumentException("Default model unavailable. " +
"Please provide a valid Porcupine model path (-m <model_path>).");
}
}
if (this.keywordPaths != null && this.keywords != null) {
throw new PorcupineInvalidArgumentException("Both 'keywords' and 'keywordPaths' " +
"were set. Only one of the two arguments may be set for initialization.");
}
if (this.keywordPaths == null) {
if (this.keywords == null) {
throw new PorcupineInvalidArgumentException(
"Either 'keywords' or 'keywordPaths' must be set.");
}
if (Utils.isResourcesAvailable()) {
this.keywordPaths = new String[keywords.length];
for (int i = 0; i < keywords.length; i++) {
this.keywordPaths[i] = BUILT_IN_KEYWORD_PATHS.get(keywords[i]);
}
} else {
throw new PorcupineInvalidArgumentException("BuiltIn keywords unavailable. " +
"Please provide a valid Porcupine keyword path.");
}
}
if (sensitivities == null) {
sensitivities = new float[keywordPaths.length];
Arrays.fill(sensitivities, 0.5f);
}
if (sensitivities.length != keywordPaths.length) {
throw new PorcupineInvalidArgumentException(
String.format(
"Number of keywords (%d) does not match number of " +
"sensitivities (%d)",
keywordPaths.length,
sensitivities.length));
}
return new Porcupine(accessKey, libraryPath, modelPath, keywordPaths, sensitivities);
}
}
}
|
0
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice/porcupine/Utils.java
|
/*
Copyright 2018-2024 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;
class Utils {
private static final Path RESOURCE_DIRECTORY;
private static final String ENVIRONMENT_NAME;
private static final String ARCHITECTURE;
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
static {
RESOURCE_DIRECTORY = getResourceDirectory();
ENVIRONMENT_NAME = getEnvironmentName();
ARCHITECTURE = getArchitecture();
}
public static boolean isResourcesAvailable() {
return RESOURCE_DIRECTORY != null;
}
public static boolean isEnvironmentSupported() {
return ENVIRONMENT_NAME != null;
}
private static Path getResourceDirectory() throws RuntimeException {
// location of resources, either a JAR file or a directory
final URL resourceURL = Porcupine.class.getProtectionDomain().getCodeSource().getLocation();
Path resourcePath;
try {
resourcePath = Paths.get(resourceURL.toURI());
} catch (URISyntaxException e) {
resourcePath = Paths.get(resourceURL.getPath());
}
if (resourcePath.toString().endsWith(".jar")) {
try {
resourcePath = extractResources(resourcePath);
} catch (IOException e) {
throw new RuntimeException("Failed to extract resources from Porcupine jar.");
}
}
return resourcePath.resolve("porcupine");
}
private static Path extractResources(Path jarPath) throws IOException {
// use jar name to create versioned extraction directory
String extractionDirName = jarPath.getFileName().toString().replace(".jar", "");
// extract jar resources to temp directory
String systemTempDir = System.getProperty("java.io.tmpdir");
Path resourceDirectoryPath = new File(systemTempDir, extractionDirName).toPath();
// try to create tmp dir for extraction
if (!Files.exists(resourceDirectoryPath)) {
try {
Files.createDirectory(resourceDirectoryPath);
} catch (IOException e) {
logger.severe("Failed to create extraction directory at " + jarPath.toString());
e.printStackTrace();
// default extraction directly to tmp
resourceDirectoryPath = new File(systemTempDir).toPath();
}
}
// read jar file entries
JarFile jf = new JarFile(jarPath.toFile());
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String jarEntryName = jarEntry.getName();
if (jarEntryName.startsWith("porcupine")) {
// copy contents into resource directory
if (jarEntry.isDirectory()) {
Path dstPath = resourceDirectoryPath.resolve(jarEntryName);
if (!dstPath.toFile().exists()) {
Files.createDirectory(dstPath);
}
} else {
Path file = resourceDirectoryPath.resolve(jarEntryName);
try (InputStream is = jf.getInputStream(jarEntry)) {
Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
return resourceDirectoryPath;
}
public static String getEnvironmentName() throws RuntimeException {
String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (os.contains("mac") || os.contains("darwin")) {
return "mac";
} else if (os.contains("win")) {
return "windows";
} else if (os.contains("linux")) {
String arch = System.getProperty("os.arch");
if (arch.equals("arm") || arch.equals("aarch64")) {
String cpuPart = getCpuPart();
switch (cpuPart) {
case "0xd03":
case "0xd08":
case "0xd0b":
return "raspberry-pi";
default:
throw new RuntimeException(String.format("Execution environment " +
"not supported. Porcupine Java does not support CPU Part (%s).",
cpuPart));
}
}
return "linux";
} else {
throw new RuntimeException("Execution environment not supported. " +
"Porcupine Java is supported on MacOS, Linux and Windows");
}
}
private static String getArchitecture() throws RuntimeException {
String arch = System.getProperty("os.arch");
boolean isArm = arch.equals("arm") || arch.equals("aarch64");
boolean isX86_64 = arch.equals("amd64") || arch.equals("x86_64");
if (ENVIRONMENT_NAME.equals("mac")) {
if (isArm) {
return "arm64";
} else if (isX86_64) {
return "x86_64";
}
} else if (ENVIRONMENT_NAME.equals("windows")) {
if (isX86_64) {
return "amd64";
} else if (isArm) {
return "arm64";
}
} else if (ENVIRONMENT_NAME.equals("linux")) {
if (isX86_64) {
return "x86_64";
}
} else if (isArm) { // RPI
String cpuPart = getCpuPart();
String archInfo = (arch.equals("aarch64")) ? "-aarch64" : "";
switch (cpuPart) {
case "0xd03":
return "cortex-a53" + archInfo;
case "0xd08":
return "cortex-a72" + archInfo;
case "0xd0b":
return "cortex-a76" + archInfo;
case "0xc08":
return "";
default:
throw new RuntimeException(
String.format("Environment (%s) with CPU Part (%s) is " +
"not supported by Porcupine.",
ENVIRONMENT_NAME,
cpuPart)
);
}
}
throw new RuntimeException(
String.format("Environment (%s) with architecture (%s) " +
"is not supported by Porcupine.",
ENVIRONMENT_NAME,
arch)
);
}
private static String getCpuPart() throws RuntimeException {
try {
return Files.lines(Paths.get("/proc/cpuinfo"))
.filter(line -> line.startsWith("CPU part"))
.map(line -> line.substring(line.lastIndexOf(" ") + 1))
.findFirst()
.orElse("");
} catch (IOException e) {
throw new RuntimeException("Porcupine failed to get get CPU information.");
}
}
public static String getPackagedModelPath() {
return RESOURCE_DIRECTORY.resolve("lib/common/porcupine_params.pv").toString();
}
public static HashMap<Porcupine.BuiltInKeyword, String> getPackagedKeywordPaths() {
HashMap<Porcupine.BuiltInKeyword, String> keywordPaths = new HashMap<>();
Path keywordFileDir = RESOURCE_DIRECTORY
.resolve("resources/keyword_files")
.resolve(ENVIRONMENT_NAME);
File[] keywordFiles = keywordFileDir.toFile().listFiles();
if (keywordFiles == null || keywordFiles.length == 0) {
logger.severe("Couldn't find any Porcupine keywords in jar.");
return keywordPaths;
}
for (File keywordFile : keywordFiles) {
final String keywordName = keywordFile
.getName().split("_")[0].toUpperCase(Locale.ENGLISH).replace(' ', '_');
keywordPaths.put(
Porcupine.BuiltInKeyword.valueOf(keywordName),
keywordFile.getAbsolutePath());
}
return keywordPaths;
}
public static String getPackagedLibraryPath() {
switch (ENVIRONMENT_NAME) {
case "windows":
return RESOURCE_DIRECTORY
.resolve("lib/java/windows")
.resolve(ARCHITECTURE)
.resolve("pv_porcupine_jni.dll")
.toString();
case "mac":
return RESOURCE_DIRECTORY.resolve("lib/java/mac")
.resolve(ARCHITECTURE)
.resolve("libpv_porcupine_jni.dylib").toString();
case "raspberry-pi":
case "linux":
return RESOURCE_DIRECTORY.resolve("lib/java")
.resolve(ENVIRONMENT_NAME)
.resolve(ARCHITECTURE)
.resolve("libpv_porcupine_jni.so").toString();
default:
return null;
}
}
}
|
0
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice/porcupine
|
java-sources/ai/picovoice/porcupine-java/3.0.5/ai/picovoice/porcupine/exception/PorcupineException.java
|
/*
Copyright 2021-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.porcupine;
public class PorcupineException extends Exception {
private final String message;
private final String[] messageStack;
public PorcupineException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public PorcupineException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public PorcupineException(String message, String[] messageStack) {
super(message);
this.message = message;
this.messageStack = messageStack;
}
public String[] getMessageStack() {
return this.messageStack;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(message);
if (messageStack != null) {
if (messageStack.length > 0) {
sb.append(":");
for (int i = 0; i < messageStack.length; i++) {
sb.append(String.format("\n [%d] %s", i, messageStack[i]));
}
}
}
return sb.toString();
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/Rhino.java
|
/*
Copyright 2018-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.rhino;
import android.content.Context;
import android.content.res.Resources;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Android binding for Rhino Speech-to-Intent engine. It directly infers the user's intent from
* spoken commands in real-time. Rhino processes incoming audio in consecutive frames and indicates
* if the inference is finalized. When finalized, the inferred intent can be retrieved as structured
* data in the form of an intent string and pairs of slots and values. The number of samples per
* frame can be attained by calling {@link #getFrameLength()} . The incoming audio needs to have a
* sample rate equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Rhino operates on
* single-channel audio.
*/
public class Rhino {
private static String DEFAULT_MODEL_PATH;
private static boolean isExtracted;
private static String _sdk = "android";
static {
System.loadLibrary("pv_rhino");
}
private long handle;
private boolean isFinalized;
public static void setSdk(String sdk) {
Rhino._sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param modelPath Absolute path to the file containing model parameters.
* @param contextPath Absolute path to file containing context parameters. A context represents
* the set of expressions (spoken commands), intents, and intent arguments
* (slots) within a domain of interest.
* @param sensitivity Inference sensitivity. It should be a number within [0, 1]. A higher
* sensitivity value results in fewer misses at the cost of (potentially)
* increasing the erroneous inference rate.
* @param endpointDurationSec Endpoint duration in seconds. An endpoint is a chunk of silence at the end of an
* utterance that marks the end of spoken command. It should be a positive
* number within [0.5, 5]. A lower endpoint duration reduces delay and improves
* responsiveness. A higher endpoint duration assures Rhino doesn't return inference
* preemptively in case the user pauses before finishing the request.
* @param requireEndpoint If set to `true`, Rhino requires an endpoint (a chunk of silence) after the
* spoken command. If set to `false`, Rhino tries to detect silence, but if it
* cannot, it still will provide inference regardless. Set to `false` only if
* operating in an environment with overlapping speech (e.g. people talking in
* the background).
*
* @throws RhinoException if there is an error while initializing Rhino.
*/
private Rhino(String accessKey,
String modelPath,
String contextPath,
float sensitivity,
float endpointDurationSec,
boolean requireEndpoint) throws RhinoException {
RhinoNative.setSdk(Rhino._sdk);
handle = RhinoNative.init(
accessKey,
modelPath,
contextPath,
sensitivity,
endpointDurationSec,
requireEndpoint);
}
/**
* Releases resources acquired by Rhino.
*/
public void delete() {
if (handle != 0) {
RhinoNative.delete(handle);
handle = 0;
}
}
/**
* Processes a frame of audio and emits a flag indicating if the inference is finalized. When
* finalized, {@link #getInference()} should be called to retrieve the intent and slots, if the
* spoken command is considered valid.
*
* @param pcm A frame of audio samples. The number of samples per frame can be attained by
* calling {@link #getFrameLength()}. The incoming audio needs to have a sample rate
* equal to {@link #getSampleRate()} and be 16-bit linearly-encoded. Furthermore,
* Rhino operates on single channel audio.
* @return Flag indicating whether the engine has finalized intent extraction.
* @throws RhinoException if there is an error while processing the audio frame.
*/
public boolean process(short[] pcm) throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino process after delete.");
}
if (pcm == null) {
throw new RhinoInvalidArgumentException("Passed null frame to Rhino process.");
}
if (pcm.length != getFrameLength()) {
throw new RhinoInvalidArgumentException(
String.format("Rhino process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
isFinalized = RhinoNative.process(handle, pcm);
return isFinalized;
}
/**
* Resets the internal state of Rhino. It should be called before the engine can be
* used to infer intent from a new stream of audio.
*
* @throws RhinoException if reset fails.
*/
public void reset() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino reset after delete.");
}
RhinoNative.reset(handle);
}
/**
* Gets inference result from Rhino. If the spoken command was understood, it includes the
* specific intent name that was inferred, and (if applicable) slot keys and specific slot
* values. Should only be called after the process function returns true, otherwise Rhino has
* not yet reached an inference conclusion.
*
* @return The result of inference as a {@link RhinoInference} object.
* @throws RhinoException if inference retrieval fails.
*/
public RhinoInference getInference() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino getInference after delete.");
}
if (!isFinalized) {
throw new RhinoInvalidStateException("getInference called before Rhino had finalized. " +
"Call getInference only after process has returned true");
}
return RhinoNative.getInference(handle);
}
/**
* Getter for context information.
*
* @return Context information.
*/
public String getContextInformation() throws RhinoException {
if (handle == 0) {
throw new RhinoInvalidStateException("Attempted to call Rhino getContextInformation after delete.");
}
return RhinoNative.getContextInfo(handle);
}
/**
* Getter for number of audio samples per frame.
*
* @return Number of audio samples per frame.
*/
public int getFrameLength() {
return RhinoNative.getFrameLength();
}
/**
* Getter for audio sample rate accepted by Picovoice.
*
* @return Audio sample rate accepted by Picovoice.
*/
public int getSampleRate() {
return RhinoNative.getSampleRate();
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return RhinoNative.getVersion();
}
/**
* Builder for creating an instance of Rhino with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private String contextPath = null;
private float sensitivity = 0.5f;
private float endpointDurationSec = 1.0f;
private boolean requireEndpoint = true;
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
public Builder setSensitivity(float sensitivity) {
this.sensitivity = sensitivity;
return this;
}
public Builder setEndpointDurationSec(float endpointDurationSec) {
this.endpointDurationSec = endpointDurationSec;
return this;
}
public Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
private void extractPackageResources(Context context) throws RhinoIOException {
final Resources resources = context.getResources();
try {
DEFAULT_MODEL_PATH = extractResource(context,
resources.openRawResource(R.raw.rhino_params),
resources.getResourceEntryName(R.raw.rhino_params) + ".pv");
isExtracted = true;
} catch (IOException ex) {
throw new RhinoIOException(ex);
}
}
private String extractResource(Context context,
InputStream srcFileStream,
String dstFilename) throws IOException {
InputStream is = new BufferedInputStream(srcFileStream, 256);
OutputStream os = new BufferedOutputStream(context.openFileOutput(dstFilename, Context.MODE_PRIVATE), 256);
int r;
while ((r = is.read()) != -1) {
os.write(r);
}
os.flush();
is.close();
os.close();
return new File(context.getFilesDir(), dstFilename).getAbsolutePath();
}
/**
* Validates properties and creates an instance of the Rhino Speech-To-Intent engine.
*
* @param context Android app context (for extracting Rhino resources)
* @return An instance of Rhino Speech-To-Intent engine
* @throws RhinoException if there is an error while initializing Rhino.
*/
public Rhino build(Context context) throws RhinoException {
if (!isExtracted) {
extractPackageResources(context);
}
if (accessKey == null || accessKey.equals("")) {
throw new RhinoInvalidArgumentException("No AccessKey provided to Rhino.");
}
if (modelPath == null) {
modelPath = DEFAULT_MODEL_PATH;
} else {
File modelFile = new File(modelPath);
String modelFilename = modelFile.getName();
if (!modelFile.exists() && !modelFilename.equals("")) {
try {
modelPath = extractResource(context,
context.getAssets().open(modelPath),
modelFilename);
} catch (IOException ex) {
throw new RhinoIOException(ex);
}
}
}
if (this.contextPath == null) {
throw new RhinoInvalidArgumentException("No context file (.rhn) was provided.");
}
File contextFile = new File(contextPath);
String contextFilename = contextFile.getName();
if (!contextFile.exists() && !contextFilename.equals("")) {
try {
contextPath = extractResource(context,
context.getAssets().open(contextPath),
contextFilename);
} catch (IOException ex) {
throw new RhinoIOException(ex);
}
}
if (sensitivity < 0 || sensitivity > 1) {
throw new RhinoInvalidArgumentException("Sensitivity value should be within [0, 1].");
}
if (endpointDurationSec < 0.5 || endpointDurationSec > 5.0) {
throw new RhinoInvalidArgumentException("Endpoint duration should be within [0.5, 5.0].");
}
return new Rhino(
accessKey,
modelPath,
contextPath,
sensitivity,
endpointDurationSec,
requireEndpoint);
}
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/RhinoInference.java
|
/*
Copyright 2018-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.rhino;
import java.util.Map;
/**
* Class that contains inference results returned from Rhino.
*/
public class RhinoInference {
private final boolean isUnderstood;
private final String intent;
private final Map<String, String> slots;
RhinoInference(boolean isUnderstood, String intent, Map<String, String> slots) {
this.isUnderstood = isUnderstood;
this.intent = intent;
this.slots = slots;
}
public boolean getIsUnderstood() {
return isUnderstood;
}
public String getIntent() {
return intent;
}
public Map<String, String> getSlots() {
return slots;
}
}
|
0
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice
|
java-sources/ai/picovoice/rhino-android/3.0.2/ai/picovoice/rhino/RhinoManager.java
|
/*
Copyright 2018-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is
located in the "LICENSE" file accompanying this source.
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 ai.picovoice.rhino;
import android.content.Context;
import android.util.Log;
import ai.picovoice.android.voiceprocessor.VoiceProcessor;
import ai.picovoice.android.voiceprocessor.VoiceProcessorErrorListener;
import ai.picovoice.android.voiceprocessor.VoiceProcessorException;
import ai.picovoice.android.voiceprocessor.VoiceProcessorFrameListener;
/**
* High-level Android binding for Rhino Speech-to-Intent engine. It handles recording audio from
* microphone, processes it in real-time using Rhino, and notifies the client when an intent is
* inferred from the spoken command. For detailed information about Rhino refer to ${@link Rhino}.
*/
public class RhinoManager {
private final Rhino rhino;
private final VoiceProcessor voiceProcessor;
private final VoiceProcessorFrameListener vpFrameListener;
private final VoiceProcessorErrorListener vpErrorListener;
private boolean isFinalized;
private boolean isListening;
/**
* Private constructor.
*
* @param rhino Absolute path to the file containing model parameters.
* @param callback It is invoked upon completion of intent inference.
* @param errorCallback A callback that reports errors encountered while processing audio.
*/
private RhinoManager(
final Rhino rhino,
final RhinoManagerCallback callback,
final RhinoManagerErrorCallback errorCallback) {
this.rhino = rhino;
this.voiceProcessor = VoiceProcessor.getInstance();
this.vpFrameListener = new VoiceProcessorFrameListener() {
@Override
public void onFrame(short[] frame) {
try {
isFinalized = rhino.process(frame);
if (isFinalized) {
final RhinoInference inference = rhino.getInference();
callback.invoke(inference);
stop();
}
} catch (RhinoException e) {
if (errorCallback != null) {
errorCallback.invoke(e);
} else {
Log.e("RhinoManager", e.toString());
}
}
}
};
this.vpErrorListener = new VoiceProcessorErrorListener() {
@Override
public void onError(VoiceProcessorException error) {
if (errorCallback != null) {
errorCallback.invoke(new RhinoException(error));
} else {
Log.e("RhinoManager", error.toString());
}
}
};
}
/**
* Stops recording audio.
*/
private void stop() throws RhinoException {
voiceProcessor.removeErrorListener(vpErrorListener);
voiceProcessor.removeFrameListener(vpFrameListener);
if (voiceProcessor.getNumFrameListeners() == 0) {
try {
voiceProcessor.stop();
} catch (VoiceProcessorException e) {
throw new RhinoException(e);
}
}
isListening = false;
}
/**
* Start recording audio from the microphone and infers the user's intent from the spoken
* command. Once the inference is finalized it will invoke the user provided callback and
* terminates recording audio.
*/
public void process() throws RhinoException {
if (isListening) {
return;
}
this.voiceProcessor.addFrameListener(vpFrameListener);
this.voiceProcessor.addErrorListener(vpErrorListener);
try {
voiceProcessor.start(rhino.getFrameLength(), rhino.getSampleRate());
} catch (VoiceProcessorException e) {
throw new RhinoException(e);
}
isListening = true;
}
/**
* Releases resources acquired by Rhino. It should be called when disposing the object.
*/
public void delete() {
rhino.delete();
}
/**
* Getter for version.
*
* @return Version.
*/
public String getVersion() {
return rhino.getVersion();
}
/**
* Getter for Rhino context information.
*
* @return Context information.
*/
public String getContextInformation() throws RhinoException {
return rhino.getContextInformation();
}
/**
* Builder for creating an instance of RhinoManager with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private String contextPath = null;
private float sensitivity = 0.5f;
private float endpointDurationSec = 1.0f;
private boolean requireEndpoint = true;
private RhinoManagerErrorCallback errorCallback = null;
public RhinoManager.Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public RhinoManager.Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
public RhinoManager.Builder setContextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
public RhinoManager.Builder setSensitivity(float sensitivity) {
this.sensitivity = sensitivity;
return this;
}
public RhinoManager.Builder setEndpointDurationSec(float endpointDurationSec) {
this.endpointDurationSec = endpointDurationSec;
return this;
}
public RhinoManager.Builder setRequireEndpoint(boolean requireEndpoint) {
this.requireEndpoint = requireEndpoint;
return this;
}
public RhinoManager.Builder setErrorCallback(RhinoManagerErrorCallback errorCallback) {
this.errorCallback = errorCallback;
return this;
}
/**
* Creates an instance of RhinoManager.
*
* @param context Android app context (for extracting Rhino resources)
* @param callback A callback function that is invoked upon intent inference.
* @return A RhinoManager instance
* @throws RhinoException if there is an error while initializing Rhino.
*/
public RhinoManager build(
Context context,
RhinoManagerCallback callback) throws RhinoException {
Rhino rhino = new Rhino.Builder()
.setAccessKey(accessKey)
.setModelPath(modelPath)
.setContextPath(contextPath)
.setSensitivity(sensitivity)
.setEndpointDurationSec(endpointDurationSec)
.setRequireEndpoint(requireEndpoint)
.build(context);
return new RhinoManager(rhino, callback, errorCallback);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.