index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/enums/EmbedModel.java
|
package ai.optfor.springopenaiapi.enums;
import lombok.Getter;
import java.util.Arrays;
@Getter
public enum EmbedModel {
TEXT_EMBEDDING_3_SMALL("text-embedding-3-small", "0.00002"),
TEXT_EMBEDDING_3_LARGE("text-embedding-3-large", "0.00013"),
TEXT_EMBEDDING_ADA_002("text-embedding-ada-002", "0.00010");
private final String apiName;
private final String cost;
EmbedModel(String apiName, String cost) {
this.apiName = apiName;
this.cost = cost;
}
public static EmbedModel apiValueOf(String apiName) {
return Arrays.stream(EmbedModel.values()).filter(x -> x.getApiName().equals(apiName)).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown model: " + apiName));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/enums/LLMModel.java
|
package ai.optfor.springopenaiapi.enums;
import lombok.Getter;
import java.util.Arrays;
@Getter
public enum LLMModel {
GPT_4_O_2024_08_06("gpt-4o-2024-08-06", "0.00250", "0.01000"),
GPT_4_O_MINI("gpt-4o-mini", "0.000150", "0.000600"),
GPT_4_O("gpt-4o", "0.005", "0.015"),
GPT_4_TURBO_PREVIEW("gpt-4-turbo-preview", "0.01", "0.03"),
GPT_4_TURBO("gpt-4-turbo", "0.01", "0.03"),
GPT_3_5_TURBO("gpt-3.5-turbo", "0.0005", "0.0015"),
GPT_3_5_TURBO_16K("gpt-3.5-turbo-16k", "0.0015", "0.0020"),
GPT_4_VISION_PREVIEW("gpt-4-vision-preview", "0.01", "0.03"),
GPT_4("gpt-4", "0.03", "0.06");
private final String apiName;
private final String promptCost;
private final String completionCost;
LLMModel(String apiName, String promptCost, String completionCost) {
this.apiName = apiName;
this.promptCost = promptCost;
this.completionCost = completionCost;
}
public static LLMModel apiValueOf(String apiName) {
return Arrays.stream(LLMModel.values()).filter(x -> apiName.startsWith(x.getApiName())).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown model: " + apiName));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/enums/Role.java
|
package ai.optfor.springopenaiapi.enums;
import ai.optfor.springopenaiapi.model.ChatMessage;
import ai.optfor.springopenaiapi.model.VisionMessage;
public enum Role {
SYSTEM, USER, ASSISTANT;
public String toApiName() {
return this.name().toLowerCase();
}
public ChatMessage message(String text) {
return ChatMessage.message(this, text);
}
public VisionMessage visionMessage(String text) {
return VisionMessage.message(this, text);
}
public VisionMessage visionMessage(String text, String imageUrl) {
if (this != USER) {
throw new RuntimeException("For image message, only USER role is permitted");
}
return VisionMessage.visionUserMessage(text, imageUrl);
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/enums/TTSModel.java
|
package ai.optfor.springopenaiapi.enums;
import lombok.Getter;
import java.util.Arrays;
@Getter
public enum TTSModel {
TTS_1("tts-1"),
TTS_1_HD("tts-1-hd"),;
private final String apiName;
TTSModel(String apiName) {
this.apiName = apiName;
}
public static TTSModel apiValueOf(String apiName) {
return Arrays.stream(TTSModel.values()).filter(x -> apiName.startsWith(x.getApiName())).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown model: " + apiName));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/enums/TTSVoice.java
|
package ai.optfor.springopenaiapi.enums;
public enum TTSVoice {
ALLOY, ECHO, FABLE, ONYX, NOVA, SHIMMER;
public String toApiName() {
return this.name().toLowerCase();
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/AudioResponse.java
|
package ai.optfor.springopenaiapi.model;
public record AudioResponse(String text) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/ChatChoice.java
|
package ai.optfor.springopenaiapi.model;
public record ChatChoice(
int index,
ChatMessage message,
ChatMessage delta,
String finish_reason) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/ChatCompletionRequest.java
|
package ai.optfor.springopenaiapi.model;
import java.util.List;
import java.util.Map;
public record ChatCompletionRequest(
String model,
List<ChatMessage> messages,
double temperature,
int max_tokens,
ResponseFormat response_format,
boolean stream,
Map<Integer, Integer> logit_bias) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/ChatCompletionResponse.java
|
package ai.optfor.springopenaiapi.model;
import ai.optfor.springopenaiapi.enums.LLMModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.micrometer.common.util.StringUtils;
import java.math.BigDecimal;
import java.util.List;
import static java.math.MathContext.DECIMAL32;
public record ChatCompletionResponse(
String model,
List<ChatChoice> choices,
Usage usage) {
@JsonIgnore
public String getFirstCompletion() {
if (choices.get(0).message() != null) {
return choices.get(0).message().content();
}
return null;
}
@JsonIgnore
public String getDelta() {
if (choices.get(0).delta() != null) {
return choices.get(0).delta().content();
}
return null;
}
public BigDecimal getCost() {
int promptLength = usage.prompt_tokens();
int completionLength = usage.completion_tokens();
if (StringUtils.isBlank(model)) {
return BigDecimal.ZERO;
}
LLMModel modelEnum = LLMModel.apiValueOf(model);
return computeCost(promptLength, modelEnum.getPromptCost()).add(computeCost(completionLength, modelEnum.getCompletionCost()));
}
private BigDecimal computeCost(int length, String costPer1000) {
return new BigDecimal(costPer1000).multiply(new BigDecimal(length).divide(new BigDecimal(1000), DECIMAL32));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/ChatMessage.java
|
package ai.optfor.springopenaiapi.model;
import ai.optfor.springopenaiapi.enums.Role;
public record ChatMessage(
String role,
String content) {
public static ChatMessage message(Role role, String text) {
return new ChatMessage(role.toApiName(), text);
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/EmbeddingData.java
|
package ai.optfor.springopenaiapi.model;
import java.util.List;
public record EmbeddingData(
List<Double> embedding) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/EmbeddingRequest.java
|
package ai.optfor.springopenaiapi.model;
import java.util.List;
public record EmbeddingRequest(
String model,
List<String> input) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/EmbeddingResponse.java
|
package ai.optfor.springopenaiapi.model;
import ai.optfor.springopenaiapi.enums.EmbedModel;
import io.micrometer.common.util.StringUtils;
import java.math.BigDecimal;
import java.util.List;
import static java.math.MathContext.DECIMAL32;
public record EmbeddingResponse(
String model,
List<EmbeddingData> data,
Usage usage) {
public EmbeddingData getFirstCompletion() {
return data.get(0);
}
public BigDecimal getCost() {
int length = usage.total_tokens();
if (StringUtils.isBlank(model)) {
return BigDecimal.ZERO;
}
EmbedModel modelEnum = EmbedModel.apiValueOf(model);
return computeCost(length, modelEnum.getCost());
}
private BigDecimal computeCost(int length, String costPer1000) {
return new BigDecimal(costPer1000).multiply(new BigDecimal(length).divide(new BigDecimal(1000), DECIMAL32));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/ResponseFormat.java
|
package ai.optfor.springopenaiapi.model;
public record ResponseFormat(String type) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/STTRequest.java
|
package ai.optfor.springopenaiapi.model;
public record STTRequest(
String model,
String input,
String voice) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/Usage.java
|
package ai.optfor.springopenaiapi.model;
public record Usage(
int prompt_tokens,
int completion_tokens,
int total_tokens) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/VisionCompletionRequest.java
|
package ai.optfor.springopenaiapi.model;
import java.util.List;
import java.util.Map;
public record VisionCompletionRequest(
String model,
List<VisionMessage> messages,
double temperature,
int max_tokens,
boolean stream,
Map<Integer, Integer> logit_bias) {
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/VisionImageUrl.java
|
package ai.optfor.springopenaiapi.model;
public record VisionImageUrl(String url) {
public static VisionImageUrl visionImageUrl(String url) {
return new VisionImageUrl(url);
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/VisionMessage.java
|
package ai.optfor.springopenaiapi.model;
import ai.optfor.springopenaiapi.enums.Role;
import java.util.List;
import static ai.optfor.springopenaiapi.enums.Role.USER;
public record VisionMessage(String role, List<VisionMessageContent> content) {
public static VisionMessage message(Role role, String text) {
return new VisionMessage(role.toApiName(), List.of(VisionMessageContent.visionTextMessageContent(text)));
}
public static VisionMessage visionUserMessage(String text, String imageUrl) {
return new VisionMessage(USER.toApiName(), List.of(VisionMessageContent.visionTextMessageContent(text),
VisionMessageContent.visionImageMessageContent(imageUrl)));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/model/VisionMessageContent.java
|
package ai.optfor.springopenaiapi.model;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record VisionMessageContent(String type, String text, VisionImageUrl image_url) {
public static VisionMessageContent visionTextMessageContent(String text) {
return new VisionMessageContent("text", text, null);
}
public static VisionMessageContent visionImageMessageContent(String image_url) {
return new VisionMessageContent("image_url", null, VisionImageUrl.visionImageUrl(image_url));
}
}
|
0
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi
|
java-sources/ai/optfor/spring-openai-api/0.3.25/ai/optfor/springopenaiapi/utils/StreamCostEstimate.java
|
package ai.optfor.springopenaiapi.utils;
import ai.optfor.springopenaiapi.enums.LLMModel;
import java.math.BigDecimal;
import static java.math.MathContext.DECIMAL32;
import static java.math.RoundingMode.HALF_UP;
public class StreamCostEstimate {
private static final BigDecimal AVERAGE_CHARS_PER_TOKEN = new BigDecimal("3.0315");
public static BigDecimal estimateCost(LLMModel model, Integer inputLength, Integer outputLength) {
BigDecimal inputTokens = new BigDecimal(inputLength).divide(AVERAGE_CHARS_PER_TOKEN, DECIMAL32);
BigDecimal outputTokens = new BigDecimal(outputLength).divide(AVERAGE_CHARS_PER_TOKEN, DECIMAL32);
BigDecimal promptCost = new BigDecimal(model.getPromptCost())
.multiply(inputTokens.divide(new BigDecimal(1000), DECIMAL32)).setScale(4, HALF_UP);
BigDecimal completionCost = new BigDecimal(model.getCompletionCost())
.multiply(outputTokens.divide(new BigDecimal(1000), DECIMAL32)).setScale(4, HALF_UP);
return promptCost.add(completionCost);
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/FastJsonProtobufHttpMessageConverter.java
|
package ai.ost.fastjson_protobuf;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Type;
public class FastJsonProtobufHttpMessageConverter extends FastJsonHttpMessageConverter {
public FastJsonProtobufHttpMessageConverter () {
super();
FastJsonConfig config = this.getFastJsonConfig();
config.setSerializeConfig(new SerializeConfig());
config.setParserConfig(new ParserConfig());
}
public void disableProtobuf () {
FastJsonConfig config = this.getFastJsonConfig();
disableProtobufWriter(config.getSerializeConfig());
disableProtobufParser(config.getParserConfig());
}
private void disableProtobufWriter (com.alibaba.fastjson.serializer.SerializeConfig serializeConfig) {
if (SerializeConfig.class.isAssignableFrom(serializeConfig.getClass())) {
((SerializeConfig) serializeConfig).disableProtobuf();
}
}
private void disableProtobufParser (com.alibaba.fastjson.parser.ParserConfig parserConfig) {
if (ParserConfig.class.isAssignableFrom(parserConfig.getClass())) {
((ParserConfig) parserConfig).disableProtobuf();
}
}
@Override
public Object read(
Type type,
Class<?> contextClass,
HttpInputMessage inputMessage
) throws IOException, HttpMessageNotReadableException {
return readType(getType(type, contextClass), inputMessage);
}
@Override
protected Object readInternal(
Class<?> clazz,
HttpInputMessage inputMessage
) throws IOException, HttpMessageNotReadableException {
return readType(getType(clazz, null), inputMessage);
}
private Object readType(Type type, HttpInputMessage inputMessage) throws IOException {
InputStream is;
try {
is = inputMessage.getBody();
} catch (IOException e) {
throw new IOException("I/O error while getting input body", e);
}
FastJsonConfig config = this.getFastJsonConfig();
StringWriter writer = new StringWriter();
try {
IOUtils.copy(is, writer, config.getCharset());
} catch (IOException e) {
throw new IOException("I/O error while reading input message", e);
}
try {
return JSON.parseObject(writer.toString(), type, config.getParserConfig(), config.getFeatures());
} catch (JSONException e) {
throw new HttpMessageNotReadableException("JSON parse error: " + e.getMessage(), e);
}
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/GeneratedMessageV3Codec.java
|
package ai.ost.fastjson_protobuf;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexerBase;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
public class GeneratedMessageV3Codec implements ObjectSerializer, ObjectDeserializer {
final static GeneratedMessageV3Codec instance = new GeneratedMessageV3Codec();
private static JsonFormat.Printer printer = JsonFormat
.printer()
.omittingInsignificantWhitespace()
.preservingProtoFieldNames();
private static JsonFormat.Parser parser = JsonFormat
.parser()
.ignoringUnknownFields();
@Override
public void write(
JSONSerializer serializer,
Object object,
Object fieldName,
Type fieldType,
int features
) throws IOException {
String json;
GeneratedMessageV3 o = (GeneratedMessageV3) object;
try {
json = printer.print(o);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw new InvalidProtocolBufferException(e);
}
serializer.out.write(json);
}
@SuppressWarnings("unchecked")
@Override
public <T> T deserialze(
DefaultJSONParser jsonParser,
Type type,
Object fieldName
) {
Message.Builder builder;
Class<?> clazz = (Class<?>) type;
try {
builder = (Message.Builder) clazz.getMethod("newBuilder").invoke(clazz);
} catch (NoSuchMethodException e) {
throw new InvalidProtocolBufferMessageClass("invalid instance");
} catch (IllegalArgumentException e) {
throw new InvalidProtocolBufferMessageClass("invalid arguments");
} catch (InvocationTargetException e) {
throw new InvalidProtocolBufferMessageClass("invalid target");
} catch (IllegalAccessException e) {
throw new InvalidProtocolBufferMessageClass("invalid access");
}
JSONLexerBase lexer = (JSONLexerBase) jsonParser.getLexer();
int startToken = lexer.token();
int endToken;
if (startToken == JSONToken.LBRACE) {
endToken = JSONToken.RBRACE;
} else if (startToken == JSONToken.LBRACKET) {
endToken = JSONToken.RBRACKET;
} else {
String str = subString(lexer, startToken);
throw new JSONException(
str.isEmpty()
? "Expect message object"
: "Expect message object but got: " + str
);
}
lexer.nextToken();
// The JSONLexer of fastjson is buggy about the pos.
// For now, we must get the pos after `nextToken()`
int startPos = lexer.pos() - 1;
int endPos = 0;
int current;
int expectR = 1;
while (true) {
current = lexer.token();
if (current == endToken && -- expectR == 0) {
endPos = lexer.pos();
lexer.nextToken(JSONToken.COMMA);
break;
}
if (current == startToken) {
++ expectR;
}
lexer.nextToken();
}
String json = lexer.subString(startPos, endPos - startPos + 1);
try {
parser.merge(json, builder);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw new InvalidProtocolBufferException(e);
}
return (T) builder.build();
}
// Get the subString of the current token
private String subString (JSONLexerBase lexer, int token) {
switch (token) {
case JSONToken.TRUE : return "true";
case JSONToken.FALSE : return "false";
case JSONToken.LITERAL_STRING : return "\"" + lexer.stringVal() + "\"";
// We can't even get the substring of the current token,
// due to the limilation of fastjson
case JSONToken.LITERAL_FLOAT : return "a float number";
case JSONToken.LITERAL_INT : return "an integer";
}
return "";
}
@Override
public int getFastMatchToken() {
return JSONToken.LBRACE;
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/InvalidProtocolBufferException.java
|
package ai.ost.fastjson_protobuf;
import java.io.IOException;
public class InvalidProtocolBufferException extends RuntimeException {
public InvalidProtocolBufferException (final String message) {
super(message);
}
public InvalidProtocolBufferException(IOException e) {
super(e.getMessage(), e);
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/InvalidProtocolBufferMessageClass.java
|
package ai.ost.fastjson_protobuf;
import java.io.IOException;
public class InvalidProtocolBufferMessageClass extends RuntimeException {
public InvalidProtocolBufferMessageClass (final String message) {
super(message);
}
public InvalidProtocolBufferMessageClass(IOException e) {
super(e.getMessage(), e);
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/ParserConfig.java
|
package ai.ost.fastjson_protobuf;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.google.protobuf.GeneratedMessageV3;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class ParserConfig extends com.alibaba.fastjson.parser.ParserConfig {
private final HashMap<Class<?>, ObjectDeserializer> genericDeserializer;
public ParserConfig () {
super();
genericDeserializer = new HashMap<>();
genericPut(GeneratedMessageV3.class, GeneratedMessageV3Codec.instance);
}
private ObjectDeserializer getGenericDeserializer (Class<?> clazz) {
ObjectDeserializer parser = genericDeserializer.get(clazz);
if (parser == null) {
for (Map.Entry<Class<?>, ObjectDeserializer> entry: genericDeserializer.entrySet()) {
if (entry.getKey().isAssignableFrom(clazz)) {
ObjectDeserializer deserializer = entry.getValue();
genericDeserializer.put(clazz, deserializer);
return deserializer;
}
}
}
return parser;
}
@Override
public ObjectDeserializer getDeserializer(Type type) {
Class<?> clazz = (Class<?>) type;
ObjectDeserializer serializer = getGenericDeserializer(clazz);
if (serializer != null) {
return serializer;
}
return super.getDeserializer(type);
}
@Override
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
ObjectDeserializer serializer = getGenericDeserializer(clazz);
if (serializer != null) {
return serializer;
}
return super.getDeserializer(clazz, type);
}
void disableProtobuf () {
genericDeserializer.clear();
}
public void genericPut (Type type, ObjectDeserializer serializer) {
genericDeserializer.put((Class<?>) type, serializer);
}
}
|
0
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost
|
java-sources/ai/ost/fastjson-protobuf/1.0.0/ai/ost/fastjson_protobuf/SerializeConfig.java
|
package ai.ost.fastjson_protobuf;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.google.protobuf.GeneratedMessageV3;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class SerializeConfig extends com.alibaba.fastjson.serializer.SerializeConfig {
private final HashMap<Class<?>, ObjectSerializer> genericSerializer;
public SerializeConfig () {
super();
genericSerializer = new HashMap<>();
genericPut(GeneratedMessageV3.class, GeneratedMessageV3Codec.instance);
}
private ObjectSerializer getGenericObjectWriter (Class<?> clazz) {
ObjectSerializer writer = genericSerializer.get(clazz);
if (writer == null) {
for (Map.Entry<Class<?>, ObjectSerializer> entry: genericSerializer.entrySet()) {
if (entry.getKey().isAssignableFrom(clazz)) {
ObjectSerializer serializer = entry.getValue();
genericSerializer.put(clazz, serializer);
return serializer;
}
}
}
return writer;
}
@Override
public ObjectSerializer getObjectWriter (Class<?> clazz) {
ObjectSerializer writer = getGenericObjectWriter(clazz);
if (writer != null) {
return writer;
}
return super.getObjectWriter(clazz);
}
void disableProtobuf () {
genericSerializer.clear();
}
public void genericPut (Type type, ObjectSerializer serializer) {
genericSerializer.put((Class<?>) type, serializer);
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/BuildConfig.java
|
/**
* Automatically generated file. DO NOT MODIFY
*/
package ai.passio.passiosdk;
public final class BuildConfig {
public static final boolean DEBUG = false;
public static final String LIBRARY_PACKAGE_NAME = "ai.passio.passiosdk";
public static final String BUILD_TYPE = "release";
// Field from build type: release
public static final boolean DEV_API = false;
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/EpochEvent.java
|
package ai.passio.passiosdk.core.migz;
/**
* Allows threads to wait for an "epoch" to occur. Once an epoch is set(), all threads
* waiting for that epoch or a lower-valued ("earlier") epoch will be awoken. A thread attempting to await an epoch
* that has already occurred will return immediately.
*
* Epochs are monotonically increasing; they never go down and start at 0 by default; this rule avoids
* race conditions where two threads try to set different epochs, as the ultimate result will be the same as if only
* the set(...) call with the higher epoch value was made.
*
* @author Jeff Pasternack
*/
interface EpochEvent {
/**
* Sets the epoch, if higher than the current epoch. Otherwise, this is a no-op.
* Any threads waiting for an epoch equal or lower to this one will be awoken.
*
* If multiple calls to set(...) are made in parallel, the effect is the same as if only the highest-epoch-value call
* had been made.
*
* @param epoch the epoch to set
*/
void set(long epoch);
/**
* If the epoch is less than or equal to the requested epoch, returns immediately.
*
* Otherwise, blocks until this epoch occurs.
*
* @param epoch the epoch to wait for
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
void get(long epoch) throws InterruptedException;
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/FutureEpochEvent.java
|
package ai.passio.passiosdk.core.migz;
import java.util.PriorityQueue;
/**
* Allows threads to wait for an "epoch" to occur. Once an epoch is set(), all threads
* waiting for that epoch or a lower-valued ("earlier") epoch will be awoken. A thread attempting to await an epoch
* that has already occurred will return immediately.
*
* Epochs are monotonically increasing; they never go down and start at 0 by default; this rule avoids
* race conditions where two threads try to set different epochs, as the ultimate result will be the same as if only
* the set(...) call with the higher epoch value was made.
*
* {@link FutureEpochEvent} is intended to be used when the epochs being awaited are sparse and far in the future.
* If you typically wait for epochs that will occur in the near future, {@link} may be more
* efficient.
*
* @author Jeff Pasternack
*/
class FutureEpochEvent implements EpochEvent {
private final Object _synchronizer = new Object();
private long _epoch = 0;
private final PriorityQueue<Long> _queue = new PriorityQueue<>();
/**
* Creates a new instance, which will begin at epoch 0.
*/
public FutureEpochEvent() {
this(0);
}
/**
* Creates a new instance, which will begin at the specified epoch.
*
* @param epoch the initial epoch
*/
public FutureEpochEvent(long epoch) {
_epoch = epoch;
}
/**
* Sets the epoch, if higher than the current epoch. Otherwise, this is a no-op.
* Any threads waiting for an epoch equal or lower to this one will be awoken.
*
* If multiple calls to set(...) are made in parallel, the effect is the same as if only the highest-epoch-value call
* had been made.
*/
public void set(long epoch) {
synchronized (_synchronizer) {
if (epoch > _epoch) {
_epoch = epoch;
Long i;
// CHECKSTYLE:OFF
while ((i = _queue.peek()) != null && i <= epoch) {
// CHECKSTYLE:ON
_queue.poll();
synchronized (i) {
i.notifyAll();
}
}
}
}
}
/**
* If the epoch is less than or equal to the requested epoch, returns immediately.
*
* Otherwise, blocks until this epoch occurs.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
public void get(long epoch) throws InterruptedException {
Long epochObj;
synchronized (_synchronizer) {
if (epoch <= _epoch) {
return;
}
epochObj = Long.valueOf(epoch);
_queue.add(epochObj);
}
synchronized (epochObj) {
while (epoch > _epoch) {
epochObj.wait();
}
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/Java7ByteUtils.java
|
package ai.passio.passiosdk.core.migz;
class Java7ByteUtils {
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/ManagedDequeueBlocker.java
|
package ai.passio.passiosdk.core.migz;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ForkJoinPool;
/**
* Implements a {@link java.util.concurrent.ForkJoinPool.ManagedBlocker} for dequeuing items from a blocking queue.
*
* @author Jeff Pasternack
* @param <T> the type of item to dequeue
*/
class ManagedDequeueBlocker<T> implements ForkJoinPool.ManagedBlocker {
private final BlockingQueue<T> _queue;
private T _item; // will be retrieved by the worker thread
/**
* Convenience method that creates and executes the blocker on the current thread, returning the result.
*
* @param queue the queue whose next item should be retrieved
* @param <T> the type of item in the queue
* @return the dequeued item
* @throws InterruptedException if the thread is interrupted while blocking
*/
public static <T> T dequeue(BlockingQueue<T> queue) throws InterruptedException {
ManagedDequeueBlocker<T> blocker = new ManagedDequeueBlocker<>(queue);
ForkJoinPool.managedBlock(blocker);
return blocker.getItem();
}
/**
* Creates a new blocker that will retrieve the next item from a blocking queue
* @param queue the queue from which the item will be retrieved
*/
public ManagedDequeueBlocker(BlockingQueue<T> queue) {
_queue = queue;
}
/**
* @return the dequeued item, if this blocker has been executed, or null otherwise
*/
public T getItem() {
return _item;
}
@Override
public boolean block() throws InterruptedException {
if (_item == null) {
_item = _queue.take();
}
return true; // we don't need to block again
}
@Override
public boolean isReleasable() {
return (_item != null || ((_item = _queue.poll()) != null));
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/ManagedStreamReadBlocker.java
|
package ai.passio.passiosdk.core.migz;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.concurrent.ForkJoinPool;
/**
* A {@link ForkJoinPool.ManagedBlocker} for reading a specified number of bytes from an input stream into a byte array.
*
* The blocker uses {@link InputStream#available()} to determine if bytes can be read without blocking. If all the
* requested bytes can be read without blocking, it will do so. Otherwise, the thread will block to wait for the
* required bytes to become available.
*
* @author Jeff Pasternack
*/
class ManagedStreamReadBlocker implements ForkJoinPool.ManagedBlocker {
private int _offset;
private int _endOffset;
private int _bytesToRead; // used for bookkeeping; not modified during reading
private boolean _finished; // e.g. EOF
private final byte[] _buffer;
private final InputStream _inputStream;
/**
* Convenience method that creates the blocker, executes it against the current thread's ForkJoinPool, and returns
* the number of bytes read.
*
* @param inputStream the stream from which to read
* @param buffer the buffer that will store the read bytes
* @param bufferOffset the offset at which bytes should be stored in the buffer
* @param bytesToRead the number of bytes to read; fewer bytes will be written if the end of the stream is reached
* @return the number of bytes actually read (may be less than the number requested if end-of-stream is reached)
* @throws InterruptedException if the thread is interrupted while blocking
*/
public static int read(InputStream inputStream, byte[] buffer, int bufferOffset, int bytesToRead)
throws InterruptedException {
ManagedStreamReadBlocker blocker = new ManagedStreamReadBlocker(inputStream, buffer, bufferOffset, bytesToRead);
ForkJoinPool.managedBlock(blocker);
return blocker.getReadCount();
}
/**
* Convenience method that creates the blocker, executes it against the current thread's ForkJoinPool, and returns
* the number of bytes read. Bytes are copied into the buffer starting at offset 0.
*
* @param inputStream the stream from which to read
* @param buffer the buffer that will store the read bytes
* @param bytesToRead the number of bytes to read; fewer bytes will be written if the end of the stream is reached
* @return the number of bytes actually read (may be less than the number requested if end-of-stream is reached)
* @throws InterruptedException if the thread is interrupted while blocking
*/
public static int read(InputStream inputStream, byte[] buffer, int bytesToRead)
throws InterruptedException {
return read(inputStream, buffer, 0, bytesToRead);
}
/**
* @return the buffer in which the read bytes are stored
*/
public byte[] getBuffer() {
return _buffer;
}
/**
* @return the number of bytes actually read (may be less than that requested if the end of stream is reached or this
* blocker has not yet run)
*/
public int getReadCount() {
return _offset - (_endOffset - _bytesToRead);
}
/**
* Creates a new blocker that will read from the specified stream into the given buffer.
*
* @param inputStream the stream from which to read
* @param buffer the buffer that will store the read bytes
* @param bufferOffset the offset in the buffer at which storage of the read bytes will begin
* @param bytesToRead the number of bytes to read; fewer bytes will be written if the end of the stream is reached
*/
public ManagedStreamReadBlocker(InputStream inputStream, byte[] buffer, int bufferOffset, int bytesToRead) {
_inputStream = inputStream;
_buffer = buffer;
reinitialize(bufferOffset, bytesToRead);
}
/**
* Reinitializes this instance so that it may be reused if desired. This should only be done after its previous
* blocking has completed; the blocker <strong>must not</strong> be reused by a thread while it is in the middle of
* blocking another thread.
*
* @param bufferOffset the offset in the buffer at which storage of the read bytes will begin
* @param bytesToRead the number of bytes to read; fewer bytes will be written if the end of the stream is reached
*/
public void reinitialize(int bufferOffset, int bytesToRead) {
_offset = bufferOffset;
_endOffset = bufferOffset + bytesToRead;
_bytesToRead = bytesToRead;
_finished = false;
}
@Override
public boolean block() {
if (!_finished) {
try {
int read;
while ((read = _inputStream.read(_buffer, _offset, _endOffset - _offset)) > 0) {
_offset += read;
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
_finished = true;
}
return true;
}
@Override
public boolean isReleasable() {
// try to read without blocking
try {
int available;
while (!_finished && (available = _inputStream.available()) > 0) {
int read = _inputStream.read(_buffer, _offset, Math.min(available, _endOffset - _offset));
if (read < 0) {
_finished = true;
} else {
_offset += read;
_finished = (_offset == _endOffset);
}
}
return _finished;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/MiGzBuffer.java
|
package ai.passio.passiosdk.core.migz;
/**
* MiGzBuffer directly exposes MiGz's internal buffers for better performance relative to the typical stream interface.
*/
class MiGzBuffer {
private final byte[] _data;
private final int _length;
/**
* Gets the byte array containing this buffer's bytes. Bytes [0, getLength()] are valid data.
*
* @return the buffer's byte array
*/
public byte[] getData() {
return _data;
}
/**
* Gets the length of the data stored in this buffer. Bytes [0, getLength()] are valid data.
*
* @return the buffer's length
*/
public int getLength() {
return _length;
}
MiGzBuffer(byte[] data, int length) {
this._data = data;
this._length = length;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/MiGzInputStream.java
|
package ai.passio.passiosdk.core.migz;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RecursiveAction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* MiGzInputStream reads compressed data from an underlying stream that was previously compressed by MiGz,
* parallelizing the decompression for maximum speed.
* <p>
* Please note that while MiGz-compressed streams can be read by any gzip utility or library, MiGzInputStream
* ONLY reads MiGz-compressed data and cannot read gzip'ed data from other sources.
* <p>
* MiGz breaks the data into blocks, compresses each block in parallel, and then writes them as them multiple gzip
* "records" in serial as per the GZip specification (this is perhaps not a widely known feature, but it's why you can
* concatenate two gzip'ed files and the result will decompress to the concatenation of the original data).
* <p>
* MiGz-compressed streams can be concatenated together and read back by MiGzInputStream to recover the original
* concatenated data.
* <p>
* With the default block size, there is experimentally a very small (~1%) increase in the compressed data size penalty
* for MiGz vs. standard GZip, mostly as a consequence of compressing data in chunks rather than holistically, and
* slightly due to the cost of writing extra GZip record headers (these are very small). The default block size is
* chosen to keep the total compressed size extremely close to normal GZip at maximum compression and still allow a high
* degree of parallelization.
*/
class MiGzInputStream extends InputStream {
/**
* The class operates as follows:
* (1) Threads in the thread pool read blocks of compressed data from the underlying stream.
* (2) Each thread decompresses its block into an output buffer taken from the buffer pool.
* (3) The output buffer is placed into the outputBufferQueue for the client to read(...)
*/
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private long _currentBlock = 0; // the current block being read from the input stream
private volatile boolean _eosCompressed = false; // have reached the end of compressed data?
private boolean _eosDecompressed = false; // have we reached the end of decompressed data?
private MiGzBuffer _activeDecompressedBuffer = null; // current buffer being read(...) or readBuffer()'ed
private int _activeDecompressedBufferOffset = 0; // offset of the next byte to be read within that buffer
private final List<TaskState> _taskStatePopulation; // needed for closing
private final LinkedBlockingQueue<TaskState> _taskStatePool; // pool of buffers for decompressed bytes
private final LinkedBlockingQueue<byte[]> _decompressedBufferPool; // pool of buffers for decompressed bytes
// sequential queue of decompressed data ready to be read by the client via readBuffer() or read(...):
private final SequentialQueue<MiGzBuffer> _decompressedBufferQueue;
// number of threads used to write the original MiGzipped file
private final InputStream _inputStream; // source of compressed bytes
private final ConcurrentHashMap<DecompressTask, Boolean> _activeTasks;
private final boolean _ownsThreadPool; // determines whether the thread pool should be terminated on close()
private final ForkJoinPool _threadPool; // decompressor thread pool
//private final ForkJoinTask[] _tasks; // keep track of these so we can cancel them later if needed
private final byte[] _minibuff = new byte[1]; // used for single-byte read()s
/**
* Creates a new MiGzInputStream that will read MiGz-compressed bytes from the specified underlying
* inputStream using the default number of threads. Worker tasks will execute on the current {@link ForkJoinPool}
* returned by {@link ForkJoinTask#getPool()} if applicable, the {@link ForkJoinPool#commonPool()} otherwise,
* with a maximum number of concurrent workers equal to the target parallelism of the pool.
*
* @param inputStream the stream from which compressed bytes will be read
* @throws UncheckedIOException if a problem occurs reading the block size header
*/
public MiGzInputStream(InputStream inputStream) {
this(inputStream, ForkJoinTask.inForkJoinPool() ? ForkJoinTask.getPool() : ForkJoinPool.commonPool());
}
/**
* Creates a new MiGzInputStream that will read MiGz-compressed bytes from the specified underlying
* inputStream. The number of worker threads will be equal to the parallelism of the pool.
*
* @param inputStream the stream from which compressed bytes will be read
* @param threadPool the thread pool on which worker threads will be scheduled
*/
public MiGzInputStream(InputStream inputStream, ForkJoinPool threadPool) {
this(inputStream, threadPool, threadPool.getParallelism());
}
/**
* Creates a new MiGzInputStream that will read MiGz-compressed bytes from the specified underlying
* inputStream. A <strong>new</strong> ForkJoinPool will be created to accommodate the specified number of threads.
*
* @param inputStream the stream from which compressed bytes will be read
* @param threadCount the maximum number of threads to use for decompression
*/
public MiGzInputStream(InputStream inputStream, int threadCount) {
this(inputStream, new ForkJoinPool(threadCount), threadCount, true);
}
/**
* Creates a new MiGzInputStream that will read MiGz-compressed bytes from the specified underlying
* inputStream.
*
* @param inputStream the stream from which compressed bytes will be read
* @param threadPool the thread pool on which worker threads will be scheduled
* @param threadCount the maximum number of threads to use for decompression; limited by the number of threads in the
* provided {@code threadPool}
*/
public MiGzInputStream(InputStream inputStream, ForkJoinPool threadPool, int threadCount) {
this(inputStream, threadPool, threadCount, false);
}
/**
* Creates a new MiGzInputStream that will read MiGz-compressed bytes from the specified underlying
* inputStream.
*
* @param inputStream the stream from which compressed bytes will be read
* @param threadPool the thread pool on which worker threads will be scheduled
* @param threadCount the maximum number of threads to use for decompression; limited by the number of threads in the
* provided {@code threadPool}
* @param ownsThreadPool whether this instance "owns" the thread pool and should shut it down when close() is called
*/
private MiGzInputStream(InputStream inputStream, ForkJoinPool threadPool, int threadCount, boolean ownsThreadPool) {
_inputStream = inputStream;
_threadPool = threadPool;
_ownsThreadPool = ownsThreadPool;
int outputBufferCount = 2 * threadCount;
_activeTasks = new ConcurrentHashMap<>(threadCount);
_taskStatePopulation = IntStream.range(0, threadCount).mapToObj(i -> new TaskState()).collect(Collectors.toList());
_taskStatePool = new LinkedBlockingQueue<>(_taskStatePopulation);
_decompressedBufferPool = new LinkedBlockingQueue<>(Collections.nCopies(outputBufferCount, EMPTY_BYTE_ARRAY));
// making the queue larger than the number of output buffers guarantees that an enqueue call on SequentialQueue will
// not block, since the indices written to are assigned sequentially only after the worker thread obtains a buffer
_decompressedBufferQueue = new SequentialQueue<>(outputBufferCount + 1);
_threadPool.execute(new DecompressTask());
}
private void enqueueException(long blockIndex, RuntimeException e) throws InterruptedException {
_eosCompressed = true; // try to stop any further reads from underlying input stream
_decompressedBufferQueue.enqueueException(blockIndex, e); // throw an exception when this block is read(...)
}
private static class TaskState {
byte[] _buffer = new byte[MiGzUtil.maxCompressedSize(MiGzUtil.DEFAULT_BLOCK_SIZE) + MiGzUtil.GZIP_FOOTER_SIZE];
final byte[] _headerBuffer = new byte[MiGzUtil.GZIP_HEADER_SIZE];
Inflater _inflater = new Inflater(true);
void close() {
_inflater.end();
}
}
private static int readFromStream(InputStream inputStream, byte[] buffer, int count) throws IOException {
int read;
int offset = 0;
while ((read = inputStream.read(buffer, offset, count - offset)) > 0) {
offset += read;
}
return offset;
}
private class DecompressTask extends RecursiveAction {
private Thread _executionThread;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
synchronized (this) {
if (_executionThread != null) {
_executionThread.interrupt();
}
}
}
return super.cancel(mayInterruptIfRunning);
}
@Override
protected void compute() {
_activeTasks.put(this, true);
synchronized (this) { // this won't block unless we're closing (and even then, almost certainly not...)
_executionThread = Thread.currentThread();
}
try {
try {
decompressorThread();
} finally { // clear our execution thread before handling any exceptions or clearing ourselves from activeTasks
synchronized (this) {
_executionThread = null;
}
}
} catch (InterruptedException e) {
throw new UncheckedInterruptedException(e);
} finally {
_activeTasks.remove(this);
}
}
private void decompressorThread() throws InterruptedException {
TaskState taskState = ManagedDequeueBlocker.dequeue(_taskStatePool);
byte[] headerBuffer = taskState._headerBuffer;
byte[] buffer = taskState._buffer;
Inflater inflater = taskState._inflater;
byte[] outputBuffer = ManagedDequeueBlocker.dequeue(_decompressedBufferPool);
// check if we should stop
if (_eosCompressed) {
return;
}
long myBlock = -1; // need to initialize this so Java doesn't complain that an uninitialized value is read in the
// catch {...} blocks, but in practice it will always be set to the correct value if/when those
// blocks execute.
try {
final int compressedSize;
boolean ensureBufferCapacity = false;
myBlock = _currentBlock++;
// first read the header
int headerBufferBytesRead = ManagedStreamReadBlocker.read(_inputStream, headerBuffer, headerBuffer.length);
// eos or partially missing header?
if (headerBufferBytesRead < headerBuffer.length) {
_eosCompressed = true;
_decompressedBufferQueue.enqueue(myBlock, null); // never blocks
if (headerBufferBytesRead == 0 || headerBufferBytesRead == 4) {
// nothing more to read
return;
} else {
// something more to read, but it's not long enough to be a valid header
throw new IOException("File is not MiGz formatted");
}
}
compressedSize = getIntFromLSBByteArray(headerBuffer, headerBuffer.length - 4);
int toRead = compressedSize + MiGzUtil.GZIP_FOOTER_SIZE;
// get new, bigger buffer if necessary
if (buffer.length < toRead) {
buffer = new byte[toRead];
ensureBufferCapacity = true;
}
ManagedStreamReadBlocker.read(_inputStream, buffer, toRead);
// note that forking synchronizes our child thread with our current state
new DecompressTask().fork(); // we've finished using exclusive resources, let someone else run
int putativeInflatedSize = getIntFromLSBByteArray(buffer, compressedSize + 4);
// check if the compressed buffer is large enough for all future inputs with this inflated block size;
// this avoids re-allocating the buffer multiple times above, though this never happens when the default block
// size is used:
if (ensureBufferCapacity && buffer.length < MiGzUtil.maxCompressedSize(putativeInflatedSize) + MiGzUtil.GZIP_FOOTER_SIZE) {
buffer = new byte[MiGzUtil.maxCompressedSize(putativeInflatedSize) + MiGzUtil.GZIP_FOOTER_SIZE];
}
// enlarge the output buffer if necessary
if (outputBuffer.length < putativeInflatedSize) {
outputBuffer = new byte[putativeInflatedSize];
}
inflater.reset();
inflater.setInput(buffer, 0, compressedSize);
int uncompressedSize = inflater.inflate(outputBuffer);
// This is extremely basic error checking: just check the decompressed size;
// at greater CPU cost we could also check the CRC32 and the header, too
if (uncompressedSize != putativeInflatedSize) {
throw new IOException("The number of bytes actually decompressed bytes does not match the number of " + "uncompressed bytes recorded in the GZip record");
} else if (!inflater.finished()) {
throw new IOException("The decompressed size is larger than that claimed in the GZip record");
}
_taskStatePool.put(taskState); // return resources to pool; never blocks
_decompressedBufferQueue.enqueue(myBlock, new MiGzBuffer(outputBuffer, uncompressedSize)); // never blocks
} catch (IOException e) {
enqueueException(myBlock, new UncheckedIOException(e));
return;
} catch (DataFormatException e) {
enqueueException(myBlock, new RuntimeException(e));
return;
} catch (RuntimeException e) {
enqueueException(myBlock, e);
return;
}
}
}
private static int getIntFromLSBByteArray(byte[] source, int offset) {
return Java7ByteUtils.toUnsignedInt(source[offset])
| (Java7ByteUtils.toUnsignedInt(source[offset + 1]) << 8)
| (Java7ByteUtils.toUnsignedInt(source[offset + 2]) << 16)
| (Java7ByteUtils.toUnsignedInt(source[offset + 3]) << 24);
}
@Override
public int read() throws IOException {
if (read(_minibuff, 0, 1) < 1) {
return -1;
} else {
return Java7ByteUtils.toUnsignedInt(_minibuff[0]);
}
}
/**
* {@link MiGzInputStream} provides this alternative to the read(...) method to avoid an extra array copy where it is
* not necessary. Returns the next MiGzBuffer object containing a byte array of decompressed data and the length of
* the data in the byte array (the decompressed data always starts at offset 0), or null if the end of stream has been
* reached.
* <p>
* The buffer remains valid until the next call to {@link #readBuffer()} or one of the {@code read(...)} methods;
* after that, MiGz may modify its contents to store further decompressed data.
* <p>
* You should avoid interleaving {@link #readBuffer()} and {@code read(...)} calls, as this can severely harm
* performance. Use one method or the other, not both, to read the stream.
*
* @return a Buffer containing decompressed data, or null if the end of stream has been reached
*/
public MiGzBuffer readBuffer() {
if (!ensureBuffer()) {
return null; // eos
}
if (_activeDecompressedBufferOffset > 0) {
// client is interleaving read(...) and readBuffer() calls--this is not advised!
_activeDecompressedBuffer = new MiGzBuffer(_activeDecompressedBuffer.getData(),
_activeDecompressedBuffer.getLength() - _activeDecompressedBufferOffset);
System.arraycopy(_activeDecompressedBuffer.getData(), _activeDecompressedBufferOffset,
_activeDecompressedBuffer.getData(), 0, _activeDecompressedBuffer.getLength());
}
_activeDecompressedBufferOffset = _activeDecompressedBuffer.getLength(); // we've now read everything in the buffer
return _activeDecompressedBuffer;
}
// gets the next read buffer if needed, returning true if there is more data to read, false if end-of-stream
private boolean ensureBuffer() {
if (_activeDecompressedBuffer == null || _activeDecompressedBuffer.getLength() == _activeDecompressedBufferOffset) {
try {
if (_activeDecompressedBuffer != null) {
// put our current buffer back in the pool
_decompressedBufferPool.offer(_activeDecompressedBuffer.getData());
} else if (_eosDecompressed) {
return false;
}
_activeDecompressedBuffer = _decompressedBufferQueue.dequeue();
if (_activeDecompressedBuffer == null) {
_eosDecompressed = true;
return false;
}
_activeDecompressedBufferOffset = 0;
} catch (InterruptedException e) {
throw new UncheckedInterruptedException(e);
}
}
return true; // not yet the end of stream
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!ensureBuffer()) {
return -1; // eos
}
int toRead = Math.min(len, _activeDecompressedBuffer.getLength() - _activeDecompressedBufferOffset);
System.arraycopy(_activeDecompressedBuffer.getData(), _activeDecompressedBufferOffset, b, off, toRead);
_activeDecompressedBufferOffset += toRead;
return toRead;
}
@Override
public int available() throws IOException {
if ((_activeDecompressedBuffer == null || _activeDecompressedBuffer.getLength() == _activeDecompressedBufferOffset)
&& _decompressedBufferQueue.isNextAvailable()) {
ensureBuffer(); // shouldn't block (at least not more than trivially)
}
if (_activeDecompressedBuffer != null) {
return _activeDecompressedBuffer.getLength() - _activeDecompressedBufferOffset;
}
return 0;
}
@Override
public void close() throws IOException {
_eosCompressed = true; // will (eventually) result in all tasks stopping
_decompressedBufferPool.offer(EMPTY_BYTE_ARRAY);
{
} // there might be a thread waiting on a buffer
// try to cancel/interrupt all tasks, then wait for them to finish
DecompressTask[] activeTasks = _activeTasks.keySet().toArray(new DecompressTask[0]);
Arrays.stream(activeTasks).forEach(task -> task.cancel(true));
try {
ForkJoinTask.invokeAll(activeTasks); // wait until our tasks have completed; may rethrow worker exceptions
} catch (Exception e) {
// do nothing--exceptions are expected here
} finally {
_inputStream.close(); // now safe to close underlying stream
_taskStatePopulation.forEach(TaskState::close); // release task state resources
try {
if (_ownsThreadPool) {
_threadPool.shutdown();
}
} catch (Exception ignored) {
} // ignore exceptions while shutting down
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/MiGzUtil.java
|
package ai.passio.passiosdk.core.migz;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.concurrent.atomic.AtomicReference;
class MiGzUtil {
// From the GZip RFC:
// +---+---+---+---+---+---+---+---+---+---+
// |ID1|ID2|CM |FLG| MTIME |XFL|OS |
// +---+---+---+---+---+---+---+---+---+---+
//
// +---+---+=================================+
// | XLEN |...XLEN bytes of "extra field"...|
// +---+---+=================================+
//
// +---+---+---+---+==================================+
// |SI1|SI2| LEN |... LEN bytes of subfield data ...|
// +---+---+---+---+==================================+
public static final byte[] GZIP_HEADER = {
0x1f, // first magic byte
(byte) 0x8b, // second magic byte
8, // deflate
4, // flags: EXTRA field is present
0, // MTIME = 0 (no timestamp available)
0,
0,
0,
2, // Max compression
0, // OS = whatever
8, // _length of extra fields LSB
0, // MSB
'M', // MiGz magic bytes
'Z',
4, // extra MZ field size LSB
0, // MSB
// After this comes:
// Compressed size (4 bytes)
// compressed data ([compressed size] bytes)
// CRC (4 bytes)
// uncompressed size (4 bytes)
};
public static final int GZIP_HEADER_SIZE = GZIP_HEADER.length + 4;
public static final int GZIP_FOOTER_SIZE = 8;
public static final int DEFAULT_BLOCK_SIZE = 512 * 1024;
public static int maxCompressedSize(int uncompressed) {
// zlib (which backs all JVM implementations of Java's Deflate class that we are aware of) will use a memLevel of 8
// for the DEFLATE algorithm by default, which translates to an uncompressable block size of 2^14 - 1 (~16KB).
// However, the minimum memLevel permitted by zlib is 1, which translates to a block size of 2^7 - 1 (127 bytes).
// Because we have no portable way to detect the memLevel that will be used in the current JVM with absolute
// certainty, we assume the worst-case block size of 127 (even though in practice it is a *virtual* certainty it
// will be 16,383). This results in slightly higher than ideal memory consumption (by about 4%).
//
// We note that, in principle, nothing stops another, non-zlib DEFLATE implementation from allowing an even smaller
// block size; however, no plausible/sane Deflate class would ever use such a small size.
final int deflateBlockSize = 127; // absolute minimum, worst-case DEFLATE block size allowed by zlib
// According to the relevant RFC, Deflate should add no more than 5 bytes per DEFLATE block;
// we add one additional byte to avoid a potential issue where Deflate does not properly report a "finished" block
// if the size of the deflated block is exactly the size of the available buffer.
return uncompressed + ((uncompressed + deflateBlockSize - 1) / deflateBlockSize) * 5 + 1;
}
public static void checkException(AtomicReference<RuntimeException> exception) throws IOException {
if (exception.get() != null) {
RuntimeException re = exception.get();
if (re instanceof UncheckedIOException) {
throw ((UncheckedIOException) re).getCause();
}
throw re;
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/ResettableEvent.java
|
package ai.passio.passiosdk.core.migz;
/**
* Inspired by C#'s AutoResetEvent and ManualResetEvent, this class is an easier-to-use variant of the kind of
* inter-thread signalling achieved with object.wait() and object.notifyAll() or Conditions.
*
* ResettableEvent has two states: set and unset. If "set" before any threads are waiting via "get", the next "get"
* call immediately returns. Otherwise, all threads currently waiting are activated when "set".
*
* @author Jeff Pasternack
*/
class ResettableEvent {
private final Object _synchronizer = new Object();
private int _setEpoch;
private int _getEpoch = 0;
/**
* Creates a new ResettableEvent with the specified initial state, set or unset.
* If set, the first call to get() will immediately succeed.
*
* @param initiallySet whether or not the object will initially be in the "set" state
*/
public ResettableEvent(boolean initiallySet) {
_setEpoch = initiallySet ? 1 : 0;
}
/**
* Sets the state of this ResettableEvent. If any threads are currently waiting on get(), they will be awoken.
* Otherwise, the next call to get() will immediately succeed.
*
* ResettableEvents are only reset once the first waiting thread is awoken (or when the next call to get() occurs, if
* no threads are waiting when set() is called). Before this happens, subsequent calls to set() have no effect.
*/
public void set() {
synchronized (_synchronizer) {
_setEpoch = _getEpoch + 1;
_synchronizer.notifyAll();
}
}
/**
* Makes this instance "unset" until set() is next called. While unset, calls to get() will block.
*/
public void reset() {
synchronized (_synchronizer) {
_getEpoch = _setEpoch;
}
}
/**
* Returns true if a call to get() would return immediately (the state is "set");
* false otherwise (state is "unset").
*
* Note that a peek() == true followed by a get() is NOT guaranteed not to block, as the state may change between
* the two calls.
*
* @return the state of object, true if "set", false if "unset"
*/
public boolean peek() {
synchronized (_synchronizer) {
return _getEpoch != _setEpoch;
}
}
/**
* If this ResettableEvent is currently "set", returns immediately.
* Otherwise, waits until set() is called on this instance.
*
* The ResettableEvent will be "reset" before returning.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
public void getAndReset() throws InterruptedException {
get(true);
}
/**
* If this ResettableEvent is currently "set", returns immediately.
* Otherwise, waits until set() is called on this instance.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
public void getWithoutReset() throws InterruptedException {
get(false);
}
/**
* If this ResettableEvent is currently "set", returns immediately.
* Otherwise, waits until set() is called on this instance.
*
* Before returning, the ResettableEvent is "reset" if the reset flag is true; it is unaffected otherwise.
*
* @param reset true if the ResettableEvent should be reset before returning; false otherwise. Passing false is a way
* to wait until the instance is set without resetting it.
* @throws InterruptedException if the thread is interrupted while waiting
*/
private void get(boolean reset) throws InterruptedException {
synchronized (_synchronizer) {
int myEpoch = _getEpoch;
while (myEpoch == _setEpoch) {
_synchronizer.wait();
}
// we can, at most, increment the _getEpoch; if it's already advanced further by the time we woke up no update
// should be performed
if (reset && _getEpoch == myEpoch) {
_getEpoch++;
}
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/SequentialQueue.java
|
package ai.passio.passiosdk.core.migz;
/**
* Queue where items are dequeued in a fixed, sequential order, starting with item 0, then 1, then 2, etc.
* Items are enqueued together with their index; the queue has a bounded capacity for future items, so enqueueing items
* will not block so long as they are not too far in the future (beyond the capacity of the queue).
*
* For example, if we create the queue with a capacity of 10, the next item is initially 0. If we try to insert an
* item with index 10 at this point, the insertion will block until the first item (at index 0) is dequeued, because
* only then will the queue have a slot to accommodate the inserted value. Conversely, inserting a value at index 9
* would not block, because there's already a slot available for it.
*
* This class is an efficient way to obtain the results of parallel computation in a predetermined order. For example,
* a parallel compression utility that compressed blocks of input in parallel threads could put each compressed
* block into a {@link SequentialQueue} while another thread wrote them to an underlying stream in their proper order.
*
* @param <T> the type of item stored in this queue
*
* @author Jeff Pasternack
*/
class SequentialQueue<T> {
private volatile long _nextIndex = 0;
private static class QueueItem<T> {
public RuntimeException _exception = null;
public T _item = null;
}
private final QueueItem<T>[] _queue;
private final ResettableEvent[] _filledSignals;
private final FutureEpochEvent _freeSignal = new FutureEpochEvent(-1);
/**
* Creates a new SequentialQueue with the specified capacity. Any index from nextIndex (the next item to be read,
* initially 0) to (nextIndex + capacity - 1) may be enqueued without blocking.
*
* @param capacity the capacity of this sequential queue.
*/
public SequentialQueue(int capacity) {
_queue = new QueueItem[capacity];
_filledSignals = new ResettableEvent[capacity];
for (int i = 0; i < capacity; i++) {
_queue[i] = new QueueItem<>();
_filledSignals[i] = new ResettableEvent(false);
}
}
/**
* Checks whether the next result is immediately dequeueable.
*
* @return true if the next result is available and can be dequeued without blocking.
*/
public boolean isNextAvailable() {
int arrayIndex = (int) (_nextIndex % _queue.length);
return _filledSignals[arrayIndex].peek();
}
/**
* Removes and returns the next object from the queue, immediately if it is already available, blocking until it is
* available otherwise.
*
* Note that SequentialQueue has no intrinsic notion of "end of results". Clients can use their own signalling
* method if needed to indicate this by, e.g. enqueueing a null value.
*
* Only one thread should call dequeue(...) and peek(...) at a time. Since there is usually one "consumer" thread
* this is typically trivial to verify, but you should otherwise provide external synchronization to avoid this.
*
* @return the next item in the queue, in order of index (starting with 0).
* @throws InterruptedException if interrupted while waiting for the next item to become available
*/
public T dequeue() throws InterruptedException {
return dequeue(false);
}
private T dequeue(boolean peek) throws InterruptedException {
long nextIndex = _nextIndex; // local copy of volatile long
int arrayIndex = (int) (nextIndex % _queue.length);
// wait for a value to be available
if (peek) {
_filledSignals[arrayIndex].getWithoutReset();
} else {
_filledSignals[arrayIndex].getAndReset();
}
QueueItem<T> queueItem = _queue[arrayIndex];
try {
if (queueItem._exception != null) {
throw queueItem._exception;
} else {
return queueItem._item;
}
} finally {
if (!peek) {
queueItem._item = null;
queueItem._exception = null;
_freeSignal.set(nextIndex);
// nextIndex needs to be updated last, because enqueue will not wait on freeSignal if it's high enough:
_nextIndex = nextIndex + 1;
}
}
}
/**
* Returns the next object from the queue, immediately if it is already available, blocking until it is
* available otherwise. The item is not removed and the queue is unchanged.
*
* peek() will still throw any enqueued exception, just like dequeue().
*
* Only one thread should call dequeue(...) and peek(...) at a time. Since there is usually one "consumer" thread
* this is typically trivial to verify, but you should otherwise provide external synchronization to avoid this.
*
* @return the next item in the queue, in order of index (starting with 0).
* @throws InterruptedException if interrupted while waiting for the next item to become available
*/
public T peek() throws InterruptedException {
return dequeue(true);
}
/**
* Dequeueing the item specified by index will cause dequeue() to throw the given exception.
* This exception is only thrown when this particular item is dequeued; the SequentialQueue may continue to be used
* after this point, if appropriate.
*
* If the index is more than (nextIndex + capacity - 1), this method blocks until there is space available. Do not
* enqueue an item at an index you have also enqueued an exception at!
*
* @param index the index of the item that, when dequeued, will result in an exception
* @param exception the exception that will be thrown
*
* @throws InterruptedException if the enqueing operation is interrupted
*/
public void enqueueException(long index, RuntimeException exception) throws InterruptedException {
enqueue(index, null, exception);
}
/**
* Enqueues an object at a specific index. Objects are dequeued in sequential order of their index, starting with
* 0. The first item dequeued will be 0, then 1, then 2, etc.
*
* Returns immediately if there is capacity to enqueue the item, blocks until there is otherwise.
*
* Enqueue should only be called for a particular index once. Enqueueing at a particular index more than once
* may result in logic errors.
*
* @param index the non-negative index of the item being enqueued
* @param obj the object to be enqueued; may be null
* @throws InterruptedException if interrupted while waiting for capacity to become available
* @throws IllegalArgumentException if the index is {@literal < 0}, or is an object that has already been dequeued
*/
public void enqueue(long index, T obj) throws InterruptedException {
enqueue(index, obj, null);
}
private void enqueue(long index, T obj, RuntimeException exception) throws InterruptedException {
long nextIndex = _nextIndex; // get a local non-volatile copy of the volatile long
if (index < nextIndex) {
throw new IllegalArgumentException("Attempted to enqueue an object at an index that has already been dequeued");
}
int arrayIndex = (int) (index % _queue.length);
if (index >= nextIndex + _queue.length) {
// we're trying to write too far into the future--need to wait
_freeSignal.get(index - _queue.length);
}
// write to queue
_queue[arrayIndex]._item = obj;
_queue[arrayIndex]._exception = exception;
_filledSignals[arrayIndex].set();
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/migz/UncheckedInterruptedException.java
|
package ai.passio.passiosdk.core.migz;
/**
* Represents an {@link InterruptedException} that has been caught and rethrown as a runtime (unchecked) exception.
*
* @author Jeff Pasternack
*/
class UncheckedInterruptedException extends RuntimeException {
/**
* Creates a new instance, wrapped the provided {@link InterruptedException}
*
* @param e the {@link InterruptedException} being wrapped
*/
public UncheckedInterruptedException(InterruptedException e) {
super(e);
}
@Override
public InterruptedException getCause() {
return (InterruptedException) super.getCause();
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/Applicable.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* A ratio/algorithm that can be applied
*/
interface Applicable {
/**
* Apply the ratio/algorithm to the input strings
*
* @param s1 Input string
* @param s2 Input string
* @return The score of similarity
*/
int apply(String s1, String s2);
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/BasicAlgorithm.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
abstract class BasicAlgorithm implements Applicable {
private ToStringFunction<String> stringFunction;
public BasicAlgorithm() {
this.stringFunction = new DefaultStringFunction();
}
public BasicAlgorithm(ToStringFunction<String> stringFunction) {
this.stringFunction = stringFunction;
}
public abstract int apply(String s1, String s2, ToStringFunction<String> stringProcessor);
public int apply(String s1, String s2){
return apply(s1, s2, this.stringFunction);
}
public BasicAlgorithm with(ToStringFunction<String> stringFunction){
setStringFunction(stringFunction);
return this;
}
public BasicAlgorithm noProcessor(){
this.stringFunction = ToStringFunction.NO_PROCESS;
return this;
}
void setStringFunction(ToStringFunction<String> stringFunction){
this.stringFunction = stringFunction;
}
public ToStringFunction<String> getStringFunction() {
return stringFunction;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/BoundExtractedResult.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
class BoundExtractedResult<T> implements Comparable<BoundExtractedResult<T>> {
private T referent;
private String string;
private int score;
private int index;
public BoundExtractedResult(T referent, String string, int score, int index) {
this.referent = referent;
this.string = string;
this.score = score;
this.index = index;
}
public T getReferent() {
return referent;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getScore() {
return score;
}
public int getIndex() {
return index;
}
@Override
public String toString() {
return "(string: " + string + ", score: " + score + ", index: " + index+ ")";
}
@Override
public int compareTo(BoundExtractedResult<T> o) {
return Integer.compare(this.getScore(), o.getScore());
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/DefaultStringFunction.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class DefaultStringFunction implements ToStringFunction<String> {
private final static String pattern = "(?ui)\\W";
private final static Pattern r = compilePattern();
/**
* Substitute non alphanumeric characters.
*
* @param in The input string
* @param sub The string to substitute with
* @return The replaced string
*/
public static String subNonAlphaNumeric(String in, String sub) {
Matcher m = r.matcher(in);
if(m.find()){
return m.replaceAll(sub);
} else {
return in;
}
}
/**
* Performs the default string processing on the input string
*
* @param in Input string
* @return The processed string
*/
@Override
public String apply(String in) {
in = subNonAlphaNumeric(in, " ");
in = in.toLowerCase();
in = in.trim();
return in;
}
private static Pattern compilePattern(){
Pattern p;
try{
p = Pattern.compile(pattern, Pattern.UNICODE_CHARACTER_CLASS);
} catch (IllegalArgumentException e) {
// Even though Android supports the unicode pattern class
// for some reason it throws an IllegalArgumentException
// if we pass the flag like on standard Java runtime
//
// We catch this and recompile without the flag (unicode should still work)
p = Pattern.compile(pattern);
}
return p;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/DefaultStringProcessor.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @deprecated Use {@code DefaultStringFunction} instead.
*/
@Deprecated
class DefaultStringProcessor extends StringProcessor {
private final static String pattern = "[^\\p{Alnum}]";
private final static Pattern r = compilePattern();
/**
* Substitute non alphanumeric characters.
*
* @param in The input string
* @param sub The string to substitute with
* @return The replaced string
*/
public static String subNonAlphaNumeric(String in, String sub) {
Matcher m = r.matcher(in);
if(m.find()){
return m.replaceAll(sub);
} else {
return in;
}
}
/**
* Performs the default string processing on the input string
*
* @param in Input string
* @return The processed string
*/
@Override
public String process(String in) {
in = subNonAlphaNumeric(in, " ");
in = in.toLowerCase();
in = in.trim();
return in;
}
private static Pattern compilePattern(){
Pattern p;
try{
p = Pattern.compile(pattern, Pattern.UNICODE_CHARACTER_CLASS);
} catch (IllegalArgumentException e) {
// Even though Android supports the unicode pattern class
// for some reason it throws an IllegalArgumentException
// if we pass the flag like on standard Java runtime
//
// We catch this and recompile without the flag (unicode should still work)
p = Pattern.compile(pattern);
}
return p;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/DiffUtils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* This is a port of all the functions needed from python-levenshtein C implementation.
* The code was ported line by line but unfortunately it was mostly undocumented,
* so it is mostly non readable (eg. var names)
*/
class DiffUtils {
public static EditOp[] getEditOps(String s1, String s2) {
return getEditOps(s1.length(), s1, s2.length(), s2);
}
private static EditOp[] getEditOps(int len1, String s1, int len2, String s2) {
int len1o, len2o;
int i;
int[] matrix;
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int p1 = 0;
int p2 = 0;
len1o = 0;
while (len1 > 0 && len2 > 0 && c1[p1] == c2[p2]) {
len1--;
len2--;
p1++;
p2++;
len1o++;
}
len2o = len1o;
/* strip common suffix */
while (len1 > 0 && len2 > 0 && c1[p1 + len1 - 1] == c2[p2 + len2 - 1]) {
len1--;
len2--;
}
len1++;
len2++;
matrix = new int[len2 * len1];
for (i = 0; i < len2; i++)
matrix[i] = i;
for (i = 1; i < len1; i++)
matrix[len2 * i] = i;
for (i = 1; i < len1; i++) {
int ptrPrev = (i - 1) * len2;
int ptrC = i * len2;
int ptrEnd = ptrC + len2 - 1;
char char1 = c1[p1 + i - 1];
int ptrChar2 = p2;
int x = i;
ptrC++;
while (ptrC <= ptrEnd) {
int c3 = matrix[ptrPrev++] + (char1 != c2[ptrChar2++] ? 1 : 0);
x++;
if (x > c3) {
x = c3;
}
c3 = matrix[ptrPrev] + 1;
if (x > c3) {
x = c3;
}
matrix[ptrC++] = x;
}
}
return editOpsFromCostMatrix(len1, c1, p1, len1o, len2, c2, p2, len2o, matrix);
}
private static EditOp[] editOpsFromCostMatrix(int len1, char[] c1, int p1, int o1,
int len2, char[] c2, int p2, int o2,
int[] matrix) {
int i, j, pos;
int ptr;
EditOp[] ops;
int dir = 0;
pos = matrix[len1 * len2 - 1];
ops = new EditOp[pos];
i = len1 - 1;
j = len2 - 1;
ptr = len1 * len2 - 1;
while (i > 0 || j > 0) {
if (i != 0 && j != 0 && matrix[ptr] == matrix[ptr - len2 - 1]
&& c1[p1 + i - 1] == c2[p2 + j - 1]) {
i--;
j--;
ptr -= len2 + 1;
dir = 0;
continue;
}
if (dir < 0 && j != 0 && matrix[ptr] == matrix[ptr - 1] + 1) {
EditOp eop = new EditOp();
pos--;
ops[pos] = eop;
eop.type = EditType.INSERT;
eop.spos = i + o1;
eop.dpos = --j + o2;
ptr--;
continue;
}
if (dir > 0 && i != 0 && matrix[ptr] == matrix[ptr - len2] + 1) {
EditOp eop = new EditOp();
pos--;
ops[pos] = eop;
eop.type = EditType.DELETE;
eop.spos = --i + o1;
eop.dpos = j + o2;
ptr -= len2;
continue;
}
if (i != 0 && j != 0 && matrix[ptr] == matrix[ptr - len2 - 1] + 1) {
pos--;
EditOp eop = new EditOp();
ops[pos] = eop;
eop.type = EditType.REPLACE;
eop.spos = --i + o1;
eop.dpos = --j + o2;
ptr -= len2 + 1;
dir = 0;
continue;
}
if (dir == 0 && j != 0 && matrix[ptr] == matrix[ptr - 1] + 1) {
pos--;
EditOp eop = new EditOp();
ops[pos] = eop;
eop.type = EditType.INSERT;
eop.spos = i + o1;
eop.dpos = --j + o2;
ptr--;
dir = -1;
continue;
}
if (dir == 0 && i != 0 && matrix[ptr] == matrix[ptr - len2] + 1) {
pos--;
EditOp eop = new EditOp();
ops[pos] = eop;
eop.type = EditType.DELETE;
eop.spos = --i + o1;
eop.dpos = j + o2;
ptr -= len2;
dir = 1;
continue;
}
assert false;
}
return ops;
}
public static MatchingBlock[] getMatchingBlocks(String s1, String s2) {
return getMatchingBlocks(s1.length(), s2.length(), getEditOps(s1, s2));
}
public static MatchingBlock[] getMatchingBlocks(int len1, int len2, OpCode[] ops) {
int n = ops.length;
int noOfMB, i;
int o = 0;
noOfMB = 0;
for (i = n; i-- != 0; o++) {
if (ops[o].type == EditType.KEEP) {
noOfMB++;
while (i != 0 && ops[o].type == EditType.KEEP) {
i--;
o++;
}
if (i == 0)
break;
}
}
MatchingBlock[] matchingBlocks = new MatchingBlock[noOfMB + 1];
int mb = 0;
o = 0;
matchingBlocks[mb] = new MatchingBlock();
for (i = n; i != 0; i--, o++) {
if (ops[o].type == EditType.KEEP) {
matchingBlocks[mb].spos = ops[o].sbeg;
matchingBlocks[mb].dpos = ops[o].dbeg;
while (i != 0 && ops[o].type == EditType.KEEP) {
i--;
o++;
}
if (i == 0) {
matchingBlocks[mb].length = len1 - matchingBlocks[mb].spos;
mb++;
break;
}
matchingBlocks[mb].length = ops[o].sbeg - matchingBlocks[mb].spos;
mb++;
matchingBlocks[mb] = new MatchingBlock();
}
}
assert mb == noOfMB;
MatchingBlock finalBlock = new MatchingBlock();
finalBlock.spos = len1;
finalBlock.dpos = len2;
finalBlock.length = 0;
matchingBlocks[mb] = finalBlock;
return matchingBlocks;
}
private static MatchingBlock[] getMatchingBlocks(int len1, int len2, EditOp[] ops) {
int n = ops.length;
int numberOfMatchingBlocks, i, spos, dpos;
numberOfMatchingBlocks = 0;
int o = 0;
spos = dpos = 0;
EditType type;
for (i = n; i != 0; ) {
while (ops[o].type == EditType.KEEP && --i != 0) {
o++;
}
if (i == 0)
break;
if (spos < ops[o].spos || dpos < ops[o].dpos) {
numberOfMatchingBlocks++;
spos = ops[o].spos;
dpos = ops[o].dpos;
}
type = ops[o].type;
switch (type) {
case REPLACE:
do {
spos++;
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case DELETE:
do {
spos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case INSERT:
do {
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
default:
break;
}
}
if (spos < len1 || dpos < len2) {
numberOfMatchingBlocks++;
}
MatchingBlock[] matchingBlocks = new MatchingBlock[numberOfMatchingBlocks + 1];
o = 0;
spos = dpos = 0;
int mbIndex = 0;
for (i = n; i != 0; ) {
while (ops[o].type == EditType.KEEP && --i != 0)
o++;
if (i == 0)
break;
if (spos < ops[o].spos || dpos < ops[o].dpos) {
MatchingBlock mb = new MatchingBlock();
mb.spos = spos;
mb.dpos = dpos;
mb.length = ops[o].spos - spos;
spos = ops[o].spos;
dpos = ops[o].dpos;
matchingBlocks[mbIndex++] = mb;
}
type = ops[o].type;
switch (type) {
case REPLACE:
do {
spos++;
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case DELETE:
do {
spos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case INSERT:
do {
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
default:
break;
}
}
if (spos < len1 || dpos < len2) {
assert len1 - spos == len2 - dpos;
MatchingBlock mb = new MatchingBlock();
mb.spos = spos;
mb.dpos = dpos;
mb.length = len1 - spos;
matchingBlocks[mbIndex++] = mb;
}
assert numberOfMatchingBlocks == mbIndex;
MatchingBlock finalBlock = new MatchingBlock();
finalBlock.spos = len1;
finalBlock.dpos = len2;
finalBlock.length = 0;
matchingBlocks[mbIndex] = finalBlock;
return matchingBlocks;
}
private static OpCode[] editOpsToOpCodes(EditOp[] ops, int len1, int len2) {
int n = ops.length;
int noOfBlocks, i, spos, dpos;
int o = 0;
EditType type;
noOfBlocks = 0;
spos = dpos = 0;
for (i = n; i != 0; ) {
while (ops[o].type == EditType.KEEP && --i != 0) {
o++;
}
if (i == 0)
break;
if (spos < ops[o].spos || dpos < ops[o].dpos) {
noOfBlocks++;
spos = ops[o].spos;
dpos = ops[o].dpos;
}
// TODO: Is this right?
noOfBlocks++;
type = ops[o].type;
switch (type) {
case REPLACE:
do {
spos++;
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case DELETE:
do {
spos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case INSERT:
do {
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
default:
break;
}
}
if (spos < len1 || dpos < len2)
noOfBlocks++;
OpCode[] opCodes = new OpCode[noOfBlocks];
o = 0;
spos = dpos = 0;
int oIndex = 0;
for (i = n; i != 0; ) {
while (ops[o].type == EditType.KEEP && --i != 0)
o++;
if (i == 0)
break;
OpCode oc = new OpCode();
opCodes[oIndex] = oc;
oc.sbeg = spos;
oc.dbeg = dpos;
if (spos < ops[o].spos || dpos < ops[o].dpos) {
oc.type = EditType.KEEP;
spos = oc.send = ops[o].spos;
dpos = oc.dend = ops[o].dpos;
oIndex++;
OpCode oc2 = new OpCode();
opCodes[oIndex] = oc2;
oc2.sbeg = spos;
oc2.dbeg = dpos;
}
type = ops[o].type;
switch (type) {
case REPLACE:
do {
spos++;
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case DELETE:
do {
spos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
case INSERT:
do {
dpos++;
i--;
o++;
} while (i != 0 && ops[o].type == type &&
spos == ops[o].spos && dpos == ops[o].dpos);
break;
default:
break;
}
opCodes[oIndex].type = type;
opCodes[oIndex].send = spos;
opCodes[oIndex].dend = dpos;
oIndex++;
}
if (spos < len1 || dpos < len2) {
assert len1 - spos == len2 - dpos;
if (opCodes[oIndex] == null)
opCodes[oIndex] = new OpCode();
opCodes[oIndex].type = EditType.KEEP;
opCodes[oIndex].sbeg = spos;
opCodes[oIndex].dbeg = dpos;
opCodes[oIndex].send = len1;
opCodes[oIndex].dend = len2;
oIndex++;
}
assert oIndex == noOfBlocks;
return opCodes;
}
public static int levEditDistance(String s1, String s2, int xcost) {
int i;
int half;
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int str1 = 0;
int str2 = 0;
int len1 = s1.length();
int len2 = s2.length();
/* strip common prefix */
while (len1 > 0 && len2 > 0 && c1[str1] == c2[str2]) {
len1--;
len2--;
str1++;
str2++;
}
/* strip common suffix */
while (len1 > 0 && len2 > 0 && c1[str1 + len1 - 1] == c2[str2 + len2 - 1]) {
len1--;
len2--;
}
/* catch trivial cases */
if (len1 == 0)
return len2;
if (len2 == 0)
return len1;
/* make the inner cycle (i.e. str2) the longer one */
if (len1 > len2) {
int nx = len1;
int temp = str1;
len1 = len2;
len2 = nx;
str1 = str2;
str2 = temp;
char[] t = c2;
c2 = c1;
c1 = t;
}
/* check len1 == 1 separately */
if (len1 == 1) {
if (xcost != 0) {
return len2 + 1 - 2 * memchr(c2, str2, c1[str1], len2);
} else {
return len2 - memchr(c2, str2, c1[str1], len2);
}
}
len1++;
len2++;
half = len1 >> 1;
int[] row = new int[len2];
int end = len2 - 1;
for (i = 0; i < len2 - (xcost != 0 ? 0 : half); i++)
row[i] = i;
/* go through the matrix and compute the costs. yes, this is an extremely
* obfuscated version, but also extremely memory-conservative and relatively
* fast. */
if (xcost != 0) {
for (i = 1; i < len1; i++) {
int p = 1;
char ch1 = c1[str1 + i - 1];
int c2p = str2;
int D = i;
int x = i;
while (p <= end) {
if (ch1 == c2[c2p++]) {
x = --D;
} else {
x++;
}
D = row[p];
D++;
if (x > D)
x = D;
row[p++] = x;
}
}
} else {
/* in this case we don't have to scan two corner triangles (of size len1/2)
* in the matrix because no best path can go throught them. note this
* breaks when len1 == len2 == 2 so the memchr() special case above is
* necessary */
row[0] = len1 - half - 1;
for (i = 1; i < len1; i++) {
int p;
char ch1 = c1[str1 + i - 1];
int c2p;
int D, x;
/* skip the upper triangle */
if (i >= len1 - half) {
int offset = i - (len1 - half);
int c3;
c2p = str2 + offset;
p = offset;
c3 = row[p++] + ((ch1 != c2[c2p++]) ? 1 : 0);
x = row[p];
x++;
D = x;
if (x > c3) {
x = c3;
}
row[p++] = x;
} else {
p = 1;
c2p = str2;
D = x = i;
}
/* skip the lower triangle */
if (i <= half + 1)
end = len2 + i - half - 2;
/* main */
while (p <= end) {
int c3 = --D + ((ch1 != c2[c2p++]) ? 1 : 0);
x++;
if (x > c3) {
x = c3;
}
D = row[p];
D++;
if (x > D)
x = D;
row[p++] = x;
}
/* lower triangle sentinel */
if (i <= half) {
int c3 = --D + ((ch1 != c2[c2p]) ? 1 : 0);
x++;
if (x > c3) {
x = c3;
}
row[p] = x;
}
}
}
i = row[end];
return i;
}
private static int memchr(char[] haystack, int offset, char needle, int num) {
if (num != 0) {
int p = 0;
do {
if (haystack[offset + p] == needle)
return 1;
p++;
} while (--num != 0);
}
return 0;
}
public static double getRatio(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int lensum = len1 + len2;
int editDistance = levEditDistance(s1, s2, 1);
return (lensum - editDistance) / (double) lensum;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/EditOp.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
final class EditOp {
public EditType type;
public int spos; // source block pos
public int dpos; // destination block pos
@Override
public String toString() {
return type.name() + "(" + spos + "," + dpos + ")";
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/EditType.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
enum EditType {
DELETE,
EQUAL,
INSERT,
REPLACE,
KEEP
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/ExtractedResult.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
class ExtractedResult implements Comparable<ExtractedResult> {
private String string;
private int score;
private int index;
public ExtractedResult(String string, int score, int index) {
this.string = string;
this.score = score;
this.index = index;
}
@Override
public int compareTo(ExtractedResult o) {
return Integer.compare(this.getScore(), o.getScore());
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getScore() {
return score;
}
public void setMaxScore() {
score = 100;
}
public int getIndex() {
return index;
}
@Override
public String toString() {
return "(string: " + string + ", score: " + score + ", index: " + index+ ")";
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/Extractor.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class Extractor {
private int cutoff;
public Extractor() {
this.cutoff = 0;
}
public Extractor(int cutoff) {
this.cutoff = cutoff;
}
public Extractor with(int cutoff) {
this.setCutoff(cutoff);
return this;
}
/**
* Returns the list of choices with their associated scores of similarity in a list
* of {@link ExtractedResult}
*
* @param query The query string
* @param choices The list of choices
* @param func The function to apply
* @return The list of results
*/
public List<ExtractedResult> extractWithoutOrder(String query, Collection<String> choices,
Applicable func) {
List<ExtractedResult> yields = new ArrayList<>();
int index = 0;
for (String s : choices) {
int score = func.apply(query, s);
if (score >= cutoff) {
yields.add(new ExtractedResult(s, score, index));
}
index++;
}
return yields;
}
/**
* Returns the list of choices with their associated scores of similarity in a list
* of {@link ExtractedResult}
*
* @param query The query string
* @param choices The list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The function to apply
* @return The list of results
*/
public <T> List<BoundExtractedResult<T>> extractWithoutOrder(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func) {
List<BoundExtractedResult<T>> yields = new ArrayList<>();
int index = 0;
for (T t : choices) {
String s = toStringFunction.apply(t);
int score = func.apply(query, s);
if (score >= cutoff) {
yields.add(new BoundExtractedResult<>(t, s, score, index));
}
index++;
}
return yields;
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @param func Scoring function
* @return An object containing the best match and it's score
*/
public ExtractedResult extractOne(String query, Collection<String> choices, Applicable func) {
List<ExtractedResult> extracted = extractWithoutOrder(query, choices, func);
return Collections.max(extracted);
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func Scoring function
* @return An object containing the best match and it's score
*/
public <T> BoundExtractedResult<T> extractOne(String query, Collection<T> choices, ToStringFunction<T> toStringFunction,
Applicable func) {
List<BoundExtractedResult<T>> extracted = extractWithoutOrder(query, choices, toStringFunction, func);
return Collections.max(extracted);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @return A list of the results
*/
public List<ExtractedResult> extractTop(String query, Collection<String> choices, Applicable func) {
List<ExtractedResult> best = extractWithoutOrder(query, choices, func);
Collections.sort(best, Collections.<ExtractedResult>reverseOrder());
return best;
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @return A list of the results
*/
public <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func) {
List<BoundExtractedResult<T>> best = extractWithoutOrder(query, choices, toStringFunction, func);
Collections.sort(best, Collections.<BoundExtractedResult<T>>reverseOrder());
return best;
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param limit Limits the number of results and speeds up
* the search (k-top heap sort) is used
* @return A list of the results
*/
public List<ExtractedResult> extractTop(String query, Collection<String> choices, Applicable func, int limit) {
List<ExtractedResult> best = extractWithoutOrder(query, choices, func);
List<ExtractedResult> results = Utils.findTopKHeap(best, limit);
Collections.reverse(results);
return results;
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param limit Limits the number of results and speeds up
* the search (k-top heap sort) is used
* @return A list of the results
*/
public <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func, int limit) {
List<BoundExtractedResult<T>> best = extractWithoutOrder(query, choices, toStringFunction, func);
List<BoundExtractedResult<T>> results = Utils.findTopKHeap(best, limit);
Collections.reverse(results);
return results;
}
public int getCutoff() {
return cutoff;
}
public void setCutoff(int cutoff) {
this.cutoff = cutoff;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/FuzzySearch.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.Collection;
import java.util.List;
/**
* FuzzySearch facade class
*/
class FuzzySearch {
/**
* Calculates a Levenshtein simple ratio between the strings.
* This is indicates a measure of similarity
*
* @param s1 Input string
* @param s2 Input string
* @return The simple ratio
*/
public static int ratio(String s1, String s2) {
return new SimpleRatio().apply(s1, s2);
}
/**
* Calculates a Levenshtein simple ratio between the strings.
* This is indicates a measure of similarity
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The simple ratio
*/
public static int ratio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new SimpleRatio().apply(s1, s2, stringFunction);
}
/**
* Inconsistent substrings lead to problems in matching. This ratio
* uses a heuristic called "best partial" for when two strings
* are of noticeably different lengths.
*
* @param s1 Input string
* @param s2 Input string
* @return The partial ratio
*/
public static int partialRatio(String s1, String s2) {
return new PartialRatio().apply(s1, s2);
}
/**
* Inconsistent substrings lead to problems in matching. This ratio
* uses a heuristic called "best partial" for when two strings
* are of noticeably different lengths.
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The partial ratio
*/
public static int partialRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new PartialRatio().apply(s1, s2, stringFunction);
}
/**
* Find all alphanumeric tokens in the string and sort
* those tokens and then take ratio of resulting
* joined strings.
*
* @param s1 Input string
* @param s2 Input string
* @return The partial ratio of the strings
*/
public static int tokenSortPartialRatio(String s1, String s2) {
return new TokenSort().apply(s1, s2, new PartialRatio());
}
/**
* Find all alphanumeric tokens in the string and sort
* those tokens and then take ratio of resulting
* joined strings.
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The partial ratio of the strings
*/
public static int tokenSortPartialRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new TokenSort().apply(s1, s2, new PartialRatio(), stringFunction);
}
/**
* Find all alphanumeric tokens in the string and sort
* those tokens and then take ratio of resulting
* joined strings.
*
* @param s1 Input string
* @param s2 Input string
* @return The full ratio of the strings
*/
public static int tokenSortRatio(String s1, String s2) {
return new TokenSort().apply(s1, s2, new SimpleRatio());
}
/**
* Find all alphanumeric tokens in the string and sort
* those tokens and then take ratio of resulting
* joined strings.
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The full ratio of the strings
*/
public static int tokenSortRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new TokenSort().apply(s1, s2, new SimpleRatio(), stringFunction);
}
/**
* Splits the strings into tokens and computes intersections and remainders
* between the tokens of the two strings. A comparison string is then
* built up and is compared using the simple ratio algorithm.
* Useful for strings where words appear redundantly.
*
* @param s1 Input string
* @param s2 Input string
* @return The ratio of similarity
*/
public static int tokenSetRatio(String s1, String s2) {
return new TokenSet().apply(s1, s2, new SimpleRatio());
}
/**
* Splits the strings into tokens and computes intersections and remainders
* between the tokens of the two strings. A comparison string is then
* built up and is compared using the simple ratio algorithm.
* Useful for strings where words appear redundantly.
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The ratio of similarity
*/
public static int tokenSetRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new TokenSet().apply(s1, s2, new SimpleRatio(), stringFunction);
}
/**
* Splits the strings into tokens and computes intersections and remainders
* between the tokens of the two strings. A comparison string is then
* built up and is compared using the simple ratio algorithm.
* Useful for strings where words appear redundantly.
*
* @param s1 Input string
* @param s2 Input string
* @return The ratio of similarity
*/
public static int tokenSetPartialRatio(String s1, String s2) {
return new TokenSet().apply(s1, s2, new PartialRatio());
}
/**
* Splits the strings into tokens and computes intersections and remainders
* between the tokens of the two strings. A comparison string is then
* built up and is compared using the simple ratio algorithm.
* Useful for strings where words appear redundantly.
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The ratio of similarity
*/
public static int tokenSetPartialRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new TokenSet().apply(s1, s2, new PartialRatio(), stringFunction);
}
/**
* Calculates a weighted ratio between the different algorithms for best results
*
* @param s1 Input string
* @param s2 Input string
* @return The ratio of similarity
*/
public static int weightedRatio(String s1, String s2) {
return new WeightedRatio().apply(s1, s2);
}
/**
* Calculates a weighted ratio between the different algorithms for best results
*
* @param s1 Input string
* @param s2 Input string
* @param stringFunction Functor which transforms strings before
* calculating the ratio
* @return The ratio of similarity
*/
public static int weightedRatio(String s1, String s2, ToStringFunction<String> stringFunction) {
return new WeightedRatio().apply(s1, s2, stringFunction);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @return A list of the results
*/
public static List<ExtractedResult> extractTop(String query, Collection<String> choices,
Applicable func, int limit, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, func, limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param limit Limits the number of results and speeds up
* the search (k-top heap sort) is used
* @param cutoff Rejects any entries with score below this
* @return A list of the results
*/
public static List<ExtractedResult> extractTop(String query, Collection<String> choices,
int limit, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, new WeightedRatio(), limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @param limit The number of results to return
* @return A list of the results
*/
public static List<ExtractedResult> extractTop(String query, Collection<String> choices,
Applicable func, int limit) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, func, limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param limit The number of results to return
* @return A list of the results
*/
public static List<ExtractedResult> extractTop(String query, Collection<String> choices,
int limit) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, new WeightedRatio(), limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @return A list of the results
*/
public static List<ExtractedResult> extractSorted(String query, Collection<String> choices, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, func);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static List<ExtractedResult> extractSorted(String query, Collection<String> choices, Applicable func,
int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, func);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @return A list of the results
*/
public static List<ExtractedResult> extractSorted(String query, Collection<String> choices) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, new WeightedRatio());
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static List<ExtractedResult> extractSorted(String query, Collection<String> choices,
int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, new WeightedRatio());
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @return A list of the results
*/
public static List<ExtractedResult> extractAll(String query, Collection<String> choices, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractWithoutOrder(query, choices, func);
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param func The scoring function
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static List<ExtractedResult> extractAll(String query, Collection<String> choices, Applicable func,
int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractWithoutOrder(query, choices, func);
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @return A list of the results
*/
public static List<ExtractedResult> extractAll(String query, Collection<String> choices) {
Extractor extractor = new Extractor();
return extractor.extractWithoutOrder(query, choices, new WeightedRatio());
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static List<ExtractedResult> extractAll(String query, Collection<String> choices, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractWithoutOrder(query, choices, new WeightedRatio());
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @param func Scoring function
* @return An object containing the best match and it's score
*/
public static ExtractedResult extractOne(String query, Collection<String> choices, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractOne(query, choices, func);
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @return An object containing the best match and it's score
*/
public static ExtractedResult extractOne(String query, Collection<String> choices) {
Extractor extractor = new Extractor();
return extractor.extractOne(query, choices, new WeightedRatio());
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func,
int limit, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, toStringFunction, func, limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param limit Limits the number of results and speeds up
* the search (k-top heap sort) is used
* @param cutoff Rejects any entries with score below this
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, int limit, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, toStringFunction, new WeightedRatio(), limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @param limit The number of results to return
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func,
int limit) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, toStringFunction, func, limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain the
* top @param limit most similar choices
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param limit The number of results to return
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractTop(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, int limit) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, toStringFunction, new WeightedRatio(), limit);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractSorted(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, toStringFunction, func);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractSorted(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func,
int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, toStringFunction, func);
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractSorted(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction) {
Extractor extractor = new Extractor();
return extractor.extractTop(query, choices, toStringFunction, new WeightedRatio());
}
/**
* Creates a <b>sorted</b> list of {@link ExtractedResult} which contain all the choices
* with their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractSorted(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractTop(query, choices, toStringFunction, new WeightedRatio());
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractAll(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractWithoutOrder(query, choices, toStringFunction, func);
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func The scoring function
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractAll(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func,
int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractWithoutOrder(query, choices, toStringFunction, func);
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractAll(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction) {
Extractor extractor = new Extractor();
return extractor.extractWithoutOrder(query, choices, toStringFunction, new WeightedRatio());
}
/**
* Creates a list of {@link ExtractedResult} which contain all the choices with
* their corresponding score where higher is more similar
*
* @param query The query string
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param cutoff Keep only scores above cutoff
* @return A list of the results
*/
public static <T> List<BoundExtractedResult<T>> extractAll(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, int cutoff) {
Extractor extractor = new Extractor(cutoff);
return extractor.extractWithoutOrder(query, choices, toStringFunction, new WeightedRatio());
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @param func Scoring function
* @return An object containing the best match and it's score
*/
public static <T> BoundExtractedResult<T> extractOne(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction, Applicable func) {
Extractor extractor = new Extractor();
return extractor.extractOne(query, choices, toStringFunction, func);
}
/**
* Find the single best match above a score in a list of choices.
*
* @param query A string to match against
* @param choices A list of choices
* @param toStringFunction The ToStringFunction to be applied to all choices.
* @return An object containing the best match and it's score
*/
public static <T> BoundExtractedResult<T> extractOne(String query, Collection<T> choices,
ToStringFunction<T> toStringFunction) {
Extractor extractor = new Extractor();
return extractor.extractOne(query, choices, toStringFunction, new WeightedRatio());
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/MatchingBlock.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
final class MatchingBlock {
public int spos;
public int dpos;
public int length;
@Override
public String toString() {
return "(" + spos + "," + dpos + "," + length + ")";
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/NoProcess.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* @deprecated Use {@code ToStringFunction#NO_PROCESS} instead.
*/
@Deprecated
class NoProcess extends StringProcessor {
@Override
@Deprecated
public String process(String in) {
return in;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/OpCode.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
final class OpCode {
public EditType type;
public int sbeg, send;
public int dbeg, dend;
@Override
public String toString() {
return type.name() + "(" + sbeg + "," + send + ","
+ dbeg + "," + dend + ")";
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/PartialRatio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Partial ratio of similarity
*/
class PartialRatio implements Ratio {
/**
* Computes a partial ratio between the strings
*
* @param s1 Input string
* @param s2 Input string
* @return The partial ratio
*/
@Override
public int apply(String s1, String s2) {
String shorter;
String longer;
if (s1.length() <= s2.length()){
shorter = s1;
longer = s2;
} else {
shorter = s2;
longer = s1;
}
MatchingBlock[] matchingBlocks = DiffUtils.getMatchingBlocks(shorter, longer);
List<Double> scores = new ArrayList<>();
for (MatchingBlock mb : matchingBlocks) {
int dist = mb.dpos - mb.spos;
int long_start = dist > 0 ? dist : 0;
int long_end = long_start + shorter.length();
if(long_end > longer.length()) long_end = longer.length();
String long_substr = longer.substring(long_start, long_end);
double ratio = DiffUtils.getRatio(shorter, long_substr);
if (ratio > .995) {
return 100;
} else {
scores.add(ratio);
}
}
return (int) Math.round(100 * Collections.max(scores));
}
@Override
public int apply(String s1, String s2, ToStringFunction<String> sp) {
return apply(sp.apply(s1), sp.apply(s2));
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/PrimitiveUtils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
class PrimitiveUtils {
static double max(double ... elems) {
if (elems.length == 0) return 0;
double best = elems[0];
for(double t : elems){
if (t > best) {
best = t;
}
}
return best;
}
static int max(int ... elems) {
if (elems.length == 0) return 0;
int best = elems[0];
for(int t : elems){
if (t > best) {
best = t;
}
}
return best;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/Ratio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* Interface for the different ratios
*/
interface Ratio extends Applicable {
/**
* Applies the ratio between the two strings
*
* @param s1 Input string
* @param s2 Input string
* @return Integer representing ratio of similarity
*/
int apply(String s1, String s2);
/**
* Applies the ratio between the two strings
*
* @param s1 Input string
* @param s2 Input string
* @param sp String processor to pre-process strings before calculating the ratio
* @return Integer representing ratio of similarity
*/
int apply(String s1, String s2, ToStringFunction<String> sp);
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/RatioAlgorithm.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
abstract class RatioAlgorithm extends BasicAlgorithm {
private Ratio ratio;
public RatioAlgorithm() {
super();
this.ratio = new SimpleRatio();
}
public RatioAlgorithm(ToStringFunction<String> stringFunction) {
super(stringFunction);
}
public RatioAlgorithm(Ratio ratio) {
super();
this.ratio = ratio;
}
public RatioAlgorithm(ToStringFunction<String> stringFunction, Ratio ratio) {
super(stringFunction);
this.ratio = ratio;
}
public abstract int apply(String s1, String s2, Ratio ratio, ToStringFunction<String> stringFunction);
public RatioAlgorithm with(Ratio ratio) {
setRatio(ratio);
return this;
}
public int apply(String s1, String s2, Ratio ratio) {
return apply(s1, s2, ratio, getStringFunction());
}
@Override
public int apply(String s1, String s2, ToStringFunction<String> stringFunction) {
return apply(s1, s2, getRatio(), stringFunction);
}
public void setRatio(Ratio ratio) {
this.ratio = ratio;
}
public Ratio getRatio() {
return ratio;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/SetUtils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.HashSet;
import java.util.Set;
final class SetUtils {
static <T> Set<T> intersection(Set<T> s1, Set<T> s2) {
Set<T> intersection = new HashSet<>(s1);
intersection.retainAll(s2);
return intersection;
}
static <T> Set<T> difference(Set<T> s1, Set<T> s2) {
Set<T> difference = new HashSet<>(s1);
difference.removeAll(s2);
return difference;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/SimpleRatio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
class SimpleRatio implements Ratio {
/**
* Computes a simple Levenshtein distance ratio between the strings
*
* @param s1 Input string
* @param s2 Input string
* @return The resulting ratio of similarity
*/
@Override
public int apply(String s1, String s2) {
return (int) Math.round(100 * DiffUtils.getRatio(s1, s2));
}
@Override
public int apply(String s1, String s2, ToStringFunction<String> sp) {
return apply(sp.apply(s1), sp.apply(s2));
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/StringProcessor.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* Transforms the input string
*
* @deprecated Use {@code ToStringFunction<String>} instead.
*/
@Deprecated
abstract class StringProcessor implements ToStringFunction<String> {
// now abstract class because JDK1.7 does not allow default methods in interfaces
/**
* Transforms the input string
*
* @deprecated Use {@code ToStringFunction#apply(String)} instead.
* @param in Input string
* @return The processed string
*/
@Deprecated
public abstract String process(String in);
@Override
public String apply(String item) {
return process(item);
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/ToStringFunction.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
/**
* Transforms an item of type T to a String.
*
* @param <T> The type of the item to transform.
*/
interface ToStringFunction<T> {
/**
* Transforms the input item to a string.
*
* @param item The item to transform.
* @return A string to use for comparing the item.
*/
String apply(T item);
/**
* A default ToStringFunction that returns the input string;
* used by methods that use plain strings in {@link FuzzySearch}.
*/
ToStringFunction<String> NO_PROCESS = new ToStringFunction<String>() {
@Override
public String apply(String item) {
return item;
}
};
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/TokenSet.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
class TokenSet extends RatioAlgorithm {
@Override
public int apply(String s1, String s2, Ratio ratio, ToStringFunction<String> stringFunction) {
s1 = stringFunction.apply(s1);
s2 = stringFunction.apply(s2);
Set<String> tokens1 = Utils.tokenizeSet(s1);
Set<String> tokens2 = Utils.tokenizeSet(s2);
Set<String> intersection = SetUtils.intersection(tokens1, tokens2);
Set<String> diff1to2 = SetUtils.difference(tokens1, tokens2);
Set<String> diff2to1 = SetUtils.difference(tokens2, tokens1);
String sortedInter = Utils.sortAndJoin(intersection, " ").trim();
String sorted1to2 = (sortedInter + " " + Utils.sortAndJoin(diff1to2, " ")).trim();
String sorted2to1 = (sortedInter + " " + Utils.sortAndJoin(diff2to1, " ")).trim();
List<Integer> results = new ArrayList<>();
results.add(ratio.apply(sortedInter, sorted1to2));
results.add(ratio.apply(sortedInter, sorted2to1));
results.add(ratio.apply(sorted1to2, sorted2to1));
return Collections.max(results);
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/TokenSort.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.Arrays;
import java.util.List;
class TokenSort extends RatioAlgorithm {
@Override
public int apply(String s1, String s2, Ratio ratio, ToStringFunction<String> stringFunction) {
String sorted1 = processAndSort(s1, stringFunction);
String sorted2 = processAndSort(s2, stringFunction);
return ratio.apply(sorted1, sorted2);
}
private static String processAndSort(String in, ToStringFunction<String> stringProcessor) {
in = stringProcessor.apply(in);
String[] wordsArray = in.split("\\s+");
List<String> words = Arrays.asList(wordsArray);
String joined = Utils.sortAndJoin(words, " ");
return joined.trim();
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/Utils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
final class Utils {
static List<String> tokenize(String in) {
return Arrays.asList(in.split("\\s+"));
}
static Set<String> tokenizeSet(String in) {
return new HashSet<>(tokenize(in));
}
static String sortAndJoin(List<String> col, String sep) {
Collections.sort(col);
return join(col, sep);
}
static String join(List<String> strings, String sep) {
final StringBuilder buf = new StringBuilder(strings.size() * 16);
for (int i = 0; i < strings.size(); i++) {
if (i < strings.size()) {
buf.append(sep);
}
buf.append(strings.get(i));
}
return buf.toString().trim();
}
static String sortAndJoin(Set<String> col, String sep) {
return sortAndJoin(new ArrayList<>(col), sep);
}
public static <T extends Comparable<T>> List<T> findTopKHeap(List<T> arr, int k) {
PriorityQueue<T> pq = new PriorityQueue<T>();
for (T x : arr) {
if (pq.size() < k) pq.add(x);
else if (x.compareTo(pq.peek()) > 0) {
pq.poll();
pq.add(x);
}
}
List<T> res = new ArrayList<>();
for (int i = k; i > 0; i--) {
T polled = pq.poll();
if (polled != null) {
res.add(polled);
}
}
return res;
}
static <T extends Comparable<? super T>> T max(T... elems) {
if (elems.length == 0) return null;
T best = elems[0];
for (T t : elems) {
if (t.compareTo(best) > 0) {
best = t;
}
}
return best;
}
}
|
0
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/nutrition-ai/3.2.10-preview1/ai/passio/passiosdk/core/search/fuzzywuzzy/WeightedRatio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import static java.lang.Math.round;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.partialRatio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.ratio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.tokenSetPartialRatio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.tokenSetRatio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.tokenSortPartialRatio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.tokenSortRatio;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.PrimitiveUtils.max;
@SuppressWarnings("WeakerAccess")
class WeightedRatio extends BasicAlgorithm {
public static final double UNBASE_SCALE = .95;
public static final double PARTIAL_SCALE = .90;
public static final boolean TRY_PARTIALS = true;
@Override
public int apply(String s1, String s2, ToStringFunction<String> stringProcessor) {
s1 = stringProcessor.apply(s1);
s2 = stringProcessor.apply(s2);
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0) {
return 0;
}
boolean tryPartials = TRY_PARTIALS;
double unbaseScale = UNBASE_SCALE;
double partialScale = PARTIAL_SCALE;
int base = ratio(s1, s2);
double lenRatio = ((double) Math.max(len1, len2)) / Math.min(len1, len2);
// if strings are similar length don't use partials
if (lenRatio < 1.5) tryPartials = false;
// if one string is much shorter than the other
if (lenRatio > 8) partialScale = .6;
if (tryPartials) {
double partial = partialRatio(s1, s2) * partialScale;
double partialSor = tokenSortPartialRatio(s1, s2) * unbaseScale * partialScale;
double partialSet = tokenSetPartialRatio(s1, s2) * unbaseScale * partialScale;
return (int) round(max(base, partial, partialSor, partialSet));
} else {
double tokenSort = tokenSortRatio(s1, s2) * unbaseScale;
double tokenSet = tokenSetRatio(s1, s2) * unbaseScale;
return (int) round(max(base, tokenSort, tokenSet));
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/BuildConfig.java
|
/**
* Automatically generated file. DO NOT MODIFY
*/
package ai.passio.passiosdk;
public final class BuildConfig {
public static final boolean DEBUG = false;
public static final String LIBRARY_PACKAGE_NAME = "ai.passio.passiosdk";
public static final String BUILD_TYPE = "release";
// Field from build type: release
public static final String SDK_TYPE = "Platform";
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/migz/FutureEpochEvent.java
|
package ai.passio.passiosdk.core.migz;
import java.util.PriorityQueue;
/**
* Allows threads to wait for an "epoch" to occur. Once an epoch is set(), all threads
* waiting for that epoch or a lower-valued ("earlier") epoch will be awoken. A thread attempting to await an epoch
* that has already occurred will return immediately.
*
* Epochs are monotonically increasing; they never go down and start at 0 by default; this rule avoids
* race conditions where two threads try to set different epochs, as the ultimate result will be the same as if only
* the set(...) call with the higher epoch value was made.
*
* {@link FutureEpochEvent} is intended to be used when the epochs being awaited are sparse and far in the future.
* If you typically wait for epochs that will occur in the near future, {@link} may be more
* efficient.
*
* @author Jeff Pasternack
*/
class FutureEpochEvent implements EpochEvent {
private final Object _synchronizer = new Object();
private long _epoch = 0;
private final PriorityQueue<Long> _queue = new PriorityQueue<>();
/**
* Creates a new instance, which will begin at epoch 0.
*/
public FutureEpochEvent() {
this(0);
}
/**
* Creates a new instance, which will begin at the specified epoch.
*
* @param epoch the initial epoch
*/
public FutureEpochEvent(long epoch) {
_epoch = epoch;
}
/**
* Sets the epoch, if higher than the current epoch. Otherwise, this is a no-op.
* Any threads waiting for an epoch equal or lower to this one will be awoken.
*
* If multiple calls to set(...) are made in parallel, the effect is the same as if only the highest-epoch-value call
* had been made.
*/
public void set(long epoch) {
synchronized (_synchronizer) {
if (epoch > _epoch) {
_epoch = epoch;
Long i;
// CHECKSTYLE:OFF
while ((i = _queue.peek()) != null && i <= epoch) {
// CHECKSTYLE:ON
_queue.poll();
synchronized (i) {
i.notifyAll();
}
}
}
}
}
/**
* If the epoch is less than or equal to the requested epoch, returns immediately.
*
* Otherwise, blocks until this epoch occurs.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
public void get(long epoch) throws InterruptedException {
Long epochObj;
synchronized (_synchronizer) {
if (epoch <= _epoch) {
return;
}
epochObj = new Long(epoch);
_queue.add(epochObj);
}
synchronized (epochObj) {
while (epoch > _epoch) {
epochObj.wait();
}
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/ocr/JavaSerializer.java
|
package ai.passio.passiosdk.core.ocr;
import androidx.annotation.Keep;
import java.io.Serializable;
class JavaSerializer {
@Keep
class OcrVectorizeModel implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private float[] weights = null;
private String[] upcs = null;
private String[] names = null;
private Matrix[] matrix = null;
private VocabItem[] vocab;
public float[] getWeights() {
return weights;
}
public String[] getUpcs() {
return upcs;
}
public String[] getNames() {
return names;
}
public Matrix[] getMatrix() {
return matrix;
}
public VocabItem[] getVocab() {
return vocab;
}
protected float[] getMatrixElementAt(int index) {
float r = matrix[index].getR();
float c = matrix[index].getC();
float v = matrix[index].getV();
return new float[]{r, c, v};
}
protected int getMatrixSize() {
return matrix.length;
}
protected String getVocabNGramAt(int index) {
return vocab[index].getNgram();
}
protected int getVocabIndexAt(int index) {
return vocab[index].getIndex();
}
protected int getVocabSize() {
return vocab.length;
}
}
@Keep
class VocabItem implements Serializable {
private static final long serialVersionUID = 8889685098567756911L;
private String ngram;
private int index;
public void setNgram(final String ngram) {
this.ngram = ngram;
}
public void setIndex(final int index) {
this.index = index;
}
public String getNgram() {
return ngram;
}
public int getIndex() {
return index;
}
}
@Keep
class Matrix implements Serializable {
private static final long serialVersionUID = 6549685098567756911L;
private int r;
private int c;
private float v;
public int getR() {
return r;
}
public int getC() {
return c;
}
public float getV() {
return v;
}
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search/fuzzywuzzy/ExtractedResult.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
class ExtractedResult implements Comparable<ExtractedResult> {
private String string;
private int score;
private int index;
public ExtractedResult(String string, int score, int index) {
this.string = string;
this.score = score;
this.index = index;
}
@Override
public int compareTo(ExtractedResult o) {
return Integer.compare(this.getScore(), o.getScore());
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getScore() {
return score;
}
public int getIndex() {
return index;
}
@Override
public String toString() {
return "(string: " + string + ", score: " + score + ", index: " + index+ ")";
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search/fuzzywuzzy/PartialRatio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Partial ratio of similarity
*/
class PartialRatio implements Ratio {
/**
* Computes a partial ratio between the strings
*
* @param s1 Input string
* @param s2 Input string
* @return The partial ratio
*/
@Override
public int apply(String s1, String s2) {
String shorter;
String longer;
if (s1.length() <= s2.length()) {
shorter = s1;
longer = s2;
} else {
shorter = s2;
longer = s1;
}
MatchingBlock[] matchingBlocks = DiffUtils.getMatchingBlocks(shorter, longer);
List<Double> scores = new ArrayList<>();
for (MatchingBlock mb : matchingBlocks) {
int dist = mb.dpos - mb.spos;
int long_start = dist > 0 ? dist : 0;
int long_end = long_start + shorter.length();
if (long_end > longer.length()) {
long_end = longer.length();
}
String long_substr = longer.substring(long_start, long_end);
double ratio = DiffUtils.getRatio(shorter, long_substr);
if (ratio > .995) {
return 100;
} else {
scores.add(ratio);
}
}
return (int) Math.round(100 * Collections.max(scores));
}
@Override
public int apply(String s1, String s2, ToStringFunction<String> sp) {
return apply(sp.apply(s1), sp.apply(s2));
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search/fuzzywuzzy/SetUtils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.HashSet;
import java.util.Set;
class SetUtils {
static <T> Set<T> intersection (Set<T> s1, Set<T> s2){
Set<T> intersection = new HashSet<>(s1);
intersection.retainAll(s2);
return intersection;
}
static <T> Set<T> difference (Set<T> s1, Set<T> s2) {
Set<T> difference = new HashSet<>(s1);
difference.removeAll(s2);
return difference;
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search/fuzzywuzzy/Utils.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
class Utils {
static List<String> tokenize(String in){
return Arrays.asList(in.split("\\s+"));
}
static Set<String> tokenizeSet(String in){
return new HashSet<>(tokenize(in));
}
static String sortAndJoin(List<String> col, String sep){
Collections.sort(col);
return join(col, sep);
}
static String join(List<String> strings, String sep) {
final StringBuilder buf = new StringBuilder(strings.size() * 16);
for(int i = 0; i < strings.size(); i++){
if(i < strings.size()) {
buf.append(sep);
}
buf.append(strings.get(i));
}
return buf.toString().trim();
}
static String sortAndJoin(Set<String> col, String sep){
return sortAndJoin(new ArrayList<>(col), sep);
}
public static <T extends Comparable<T>> List<T> findTopKHeap(List<T> arr, int k) {
PriorityQueue<T> pq = new PriorityQueue<T>();
for (T x : arr) {
if (pq.size() < k) pq.add(x);
else if (x.compareTo(pq.peek()) > 0) {
pq.poll();
pq.add(x);
}
}
List<T> res = new ArrayList<>();
for (int i =k; i > 0; i--) {
T polled = pq.poll();
if (polled != null) {
res.add(polled);
}
}
return res;
}
static <T extends Comparable<? super T>> T max(T ... elems) {
if (elems.length == 0) return null;
T best = elems[0];
for(T t : elems){
if (t.compareTo(best) > 0) {
best = t;
}
}
return best;
}
}
|
0
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search
|
java-sources/ai/passio/passiosdk/platformsdk/2.2.15/ai/passio/passiosdk/core/search/fuzzywuzzy/WeightedRatio.java
|
package ai.passio.passiosdk.core.search.fuzzywuzzy;
import static java.lang.Math.round;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.FuzzySearch.*;
import static ai.passio.passiosdk.core.search.fuzzywuzzy.PrimitiveUtils.max;
@SuppressWarnings("WeakerAccess")
class WeightedRatio extends BasicAlgorithm {
public static final double UNBASE_SCALE = .95;
public static final double PARTIAL_SCALE = .90;
public static final boolean TRY_PARTIALS = true;
@Override
public int apply(String s1, String s2, ToStringFunction<String> stringProcessor) {
s1 = stringProcessor.apply(s1);
s2 = stringProcessor.apply(s2);
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0) { return 0; }
boolean tryPartials = TRY_PARTIALS;
double unbaseScale = UNBASE_SCALE;
double partialScale = PARTIAL_SCALE;
int base = ratio(s1, s2);
double lenRatio = ((double) Math.max(len1, len2)) / Math.min(len1, len2);
// if strings are similar length don't use partials
if (lenRatio < 1.5) tryPartials = false;
// if one string is much shorter than the other
if (lenRatio > 8) partialScale = .6;
if (tryPartials) {
double partial = partialRatio(s1, s2) * partialScale;
double partialSor = tokenSortPartialRatio(s1, s2) * unbaseScale * partialScale;
double partialSet = tokenSetPartialRatio(s1, s2) * unbaseScale * partialScale;
return (int) round(max(base, partial, partialSor, partialSet));
} else {
double tokenSort = tokenSortRatio(s1, s2) * unbaseScale;
double tokenSet = tokenSetRatio(s1, s2) * unbaseScale;
return (int) round(max(base, tokenSort, tokenSet));
}
}
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessor.java
|
/*
Copyright 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.android.voiceprocessor;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The Android Voice Processor is an asynchronous audio recorder designed for real-time
* audio processing. Given some specifications, the library delivers frames of raw audio
* data to the user via listeners. Audio will be 16-bit and mono.
*/
public class VoiceProcessor {
private static VoiceProcessor instance = null;
private final ArrayList<VoiceProcessorFrameListener> frameListeners = new ArrayList<>();
private final ArrayList<VoiceProcessorErrorListener> errorListeners = new ArrayList<>();
private final AtomicBoolean isStopRequested = new AtomicBoolean(false);
private final Handler callbackHandler = new Handler(Looper.getMainLooper());
private final Object listenerLock = new Object();
private Future<Void> readThread = null;
private int frameLength;
private int sampleRate;
private VoiceProcessor() {
}
/**
* Obtain singleton instance of the VoiceProcessor.
*
* @return VoiceProcessor instance
*/
public static synchronized VoiceProcessor getInstance() {
if (instance == null) {
instance = new VoiceProcessor();
}
return instance;
}
/**
* Indicates whether the VoiceProcessor is currently recording or not.
*
* @return boolean indicating whether the VoiceProcessor is currently recording.
*/
public boolean getIsRecording() {
return readThread != null;
}
/**
* Indicates whether the given context has been granted RECORD_AUDIO permissions or not.
*
* @return boolean indicating whether RECORD_AUDIO permission has been granted.
*/
public boolean hasRecordAudioPermission(Context context) {
return ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
/**
* Add a frame listener that will receive audio frames generated by the VoiceProcessor.
*
* @param listener VoiceProcessorFrameListener for processing frames of audio.
*/
public void addFrameListener(VoiceProcessorFrameListener listener) {
synchronized (listenerLock) {
frameListeners.add(listener);
}
}
/**
* Add multiple frame listeners that will receive audio frames generated by the VoiceProcessor.
*
* @param listeners VoiceProcessorFrameListeners for processing frames of audio.
*/
public void addFrameListeners(VoiceProcessorFrameListener[] listeners) {
synchronized (listenerLock) {
frameListeners.addAll(Arrays.asList(listeners));
}
}
/**
* Remove a frame listener from the VoiceProcessor. It will no longer receive audio frames.
*
* @param listener VoiceProcessorFrameListener that you would like to remove.
*/
public void removeFrameListener(VoiceProcessorFrameListener listener) {
synchronized (listenerLock) {
frameListeners.remove(listener);
}
}
/**
* Remove frame listeners from the VoiceProcessor. They will no longer receive audio frames.
*
* @param listeners VoiceProcessorFrameListeners that you would like to remove.
*/
public void removeFrameListeners(VoiceProcessorFrameListener[] listeners) {
synchronized (listenerLock) {
frameListeners.removeAll(Arrays.asList(listeners));
}
}
/**
* Clear all frame listeners from the VoiceProcessor. They will no longer receive audio frames.
*/
public void clearFrameListeners() {
synchronized (listenerLock) {
frameListeners.clear();
}
}
/**
* Get number of frame listeners that are currently subscribed to the VoiceProcessor.
*
* @return the number of frame listeners
*/
public int getNumFrameListeners() {
return frameListeners.size();
}
/**
* Add an error listener that will receive errors generated by the VoiceProcessor.
*
* @param errorListener VoiceProcessorErrorListener for catching recording errors.
*/
public void addErrorListener(VoiceProcessorErrorListener errorListener) {
synchronized (listenerLock) {
errorListeners.add(errorListener);
}
}
/**
* Remove an error listener from the VoiceProcessor that had previously been added.
*
* @param errorListener VoiceProcessorErrorListener for catching recording errors.
*/
public void removeErrorListener(VoiceProcessorErrorListener errorListener) {
synchronized (listenerLock) {
errorListeners.remove(errorListener);
}
}
/**
* Clear all error listeners from the VoiceProcessor.
*/
public void clearErrorListeners() {
synchronized (listenerLock) {
errorListeners.clear();
}
}
/**
* Get number of error listeners that are currently subscribed to the VoiceProcessor.
*
* @return the number of error listeners
*/
public int getNumErrorListeners() {
return errorListeners.size();
}
/**
* Starts audio capture. You need to subscribe a VoiceProcessorFrameListener via
* {@link #addFrameListener(VoiceProcessorFrameListener)} in order to receive audio
* frames from the VoiceProcessor.
*
* @param requestedFrameLength Number of audio samples per frame.
* @param requestedSampleRate Audio sample rate that the audio will be captured with.
* @throws VoiceProcessorArgumentException if VoiceProcessor is already recording with
* a different configuration
*/
public synchronized void start(
final int requestedFrameLength,
final int requestedSampleRate) throws VoiceProcessorArgumentException {
if (getIsRecording()) {
if (requestedFrameLength != frameLength || requestedSampleRate != sampleRate) {
throw new VoiceProcessorArgumentException(
String.format(
"VoiceProcessor start() was called with frame length " +
"%d and sample rate %d while already recording with " +
"frame length %d and sample rate %d",
requestedFrameLength,
requestedSampleRate,
frameLength,
sampleRate));
} else {
return;
}
}
frameLength = requestedFrameLength;
sampleRate = requestedSampleRate;
readThread = Executors.newSingleThreadExecutor().submit(new Callable<Void>() {
@Override
public Void call() {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
read(frameLength, sampleRate);
return null;
}
});
}
/**
* Stops audio capture. Frames will stop being delivered to the subscribed listeners.
*
* @throws VoiceProcessorException if an error is encountered while trying to stop the
* recorder thread.
*/
public synchronized void stop() throws VoiceProcessorException {
if (!getIsRecording()) {
return;
}
isStopRequested.set(true);
try {
readThread.get();
readThread = null;
} catch (ExecutionException | InterruptedException e) {
throw new VoiceProcessorException(
"An error was encountered while requesting to stop the audio recording",
e);
} finally {
isStopRequested.set(false);
}
}
@SuppressLint({"MissingPermission", "DefaultLocale"})
private void read(int frameLength, int sampleRate) {
final int minBufferSize = AudioRecord.getMinBufferSize(
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
final int bufferSize = Math.max(sampleRate / 2, minBufferSize);
AudioRecord recorder;
try {
recorder = new AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
} catch (IllegalArgumentException e) {
onError(new VoiceProcessorArgumentException(
"Unable to initialize audio recorder with required parameters",
e));
return;
}
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
onError(new VoiceProcessorStateException(
"Audio recorder did not initialize successfully. " +
"Ensure you have acquired permission to record audio from the user."));
return;
}
try {
recorder.startRecording();
while (!isStopRequested.get()) {
final short[] frame = new short[frameLength];
final int numSamplesRead = recorder.read(frame, 0, frame.length);
if (numSamplesRead == frame.length) {
onFrame(frame);
} else {
onError(new VoiceProcessorReadException(
String.format(
"Expected a frame of size %d, but read one of size %d",
frame.length,
numSamplesRead)
));
}
}
recorder.stop();
} catch (IllegalStateException e) {
onError(new VoiceProcessorStateException(
"Audio recorder entered invalid state",
e));
} finally {
recorder.release();
}
}
private void onFrame(final short[] frame) {
synchronized (listenerLock) {
for (final VoiceProcessorFrameListener listener : frameListeners) {
callbackHandler.post(new Runnable() {
@Override
public void run() {
listener.onFrame(frame);
}
});
}
}
}
private void onError(final VoiceProcessorException e) {
synchronized (listenerLock) {
for (final VoiceProcessorErrorListener listener : errorListeners) {
callbackHandler.post(new Runnable() {
@Override
public void run() {
listener.onError(e);
}
});
}
}
}
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorArgumentException.java
|
/*
Copyright 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.android.voiceprocessor;
public class VoiceProcessorArgumentException extends VoiceProcessorException {
public VoiceProcessorArgumentException(Throwable cause) {
super(cause);
}
public VoiceProcessorArgumentException(String message) {
super(message);
}
public VoiceProcessorArgumentException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorErrorListener.java
|
/*
Copyright 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.android.voiceprocessor;
/**
* Listener type that can be added to VoiceProcessor with `.addErrorListener()`. Captures errors
* that are thrown by the recording thread.
*/
public interface VoiceProcessorErrorListener {
void onError(VoiceProcessorException error);
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorException.java
|
/*
Copyright 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.android.voiceprocessor;
public class VoiceProcessorException extends Exception {
public VoiceProcessorException(Throwable cause) {
super(cause);
}
public VoiceProcessorException(String message) {
super(message);
}
public VoiceProcessorException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorFrameListener.java
|
/*
Copyright 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.android.voiceprocessor;
/**
* Listener type that can be added to VoiceProcessor with `.addFrameListener()`. Captures audio
* frames that are generated by the recording thread.
*/
public interface VoiceProcessorFrameListener {
void onFrame(short[] frame);
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorReadException.java
|
/*
Copyright 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.android.voiceprocessor;
public class VoiceProcessorReadException extends VoiceProcessorException {
public VoiceProcessorReadException(Throwable cause) {
super(cause);
}
public VoiceProcessorReadException(String message) {
super(message);
}
public VoiceProcessorReadException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android
|
java-sources/ai/picovoice/android-voice-processor/1.0.2/ai/picovoice/android/voiceprocessor/VoiceProcessorStateException.java
|
/*
Copyright 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.android.voiceprocessor;
public class VoiceProcessorStateException extends VoiceProcessorException {
public VoiceProcessorStateException(Throwable cause) {
super(cause);
}
public VoiceProcessorStateException(String message) {
super(message);
}
public VoiceProcessorStateException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/Cheetah.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.cheetah;
import android.content.Context;
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 Cheetah Speech-to-Text engine.
*/
public class Cheetah {
private static String _sdk = "android";
static {
System.loadLibrary("pv_cheetah");
}
private long handle;
public static void setSdk(String sdk) {
Cheetah._sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console
* @param modelPath Absolute path to the file containing Cheetah model parameters.
* @param endpointDuration Duration of endpoint in seconds. A speech endpoint is detected when there is a
* chunk of audio (with a duration specified herein) after an utterance without
* any speech in it. Set duration to 0 to disable this.
* Default is 1 second in the Builder.
* @param enableAutomaticPunctuation Set to `true` to enable automatic punctuation insertion.
* @throws CheetahException if there is an error while initializing Cheetah.
*/
private Cheetah(
String accessKey,
String modelPath,
float endpointDuration,
boolean enableAutomaticPunctuation) throws CheetahException {
CheetahNative.setSdk(Cheetah._sdk);
handle = CheetahNative.init(
accessKey,
modelPath,
endpointDuration,
enableAutomaticPunctuation);
}
private static 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();
}
/**
* Releases resources acquired by Cheetah.
*/
public void delete() {
if (handle != 0) {
CheetahNative.delete(handle);
handle = 0;
}
}
/**
* Processes given audio data and returns its transcription.
*
* @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,
* Cheetah operates on single channel audio only.
* @return Inferred transcription.
* @throws CheetahException if there is an error while processing the audio frame.
*/
public CheetahTranscript process(short[] pcm) throws CheetahException {
if (handle == 0) {
throw new CheetahInvalidStateException("Attempted to call Cheetah process after delete.");
}
if (pcm == null) {
throw new CheetahInvalidArgumentException("Passed null frame to Cheetah process.");
}
if (pcm.length != getFrameLength()) {
throw new CheetahInvalidArgumentException(
String.format("Cheetah process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
return CheetahNative.process(handle, pcm);
}
/**
* Processes any remaining audio data and returns its transcription.
*
* @return Inferred transcription.
* @throws CheetahException if there is an error while processing the audio frame.
*/
public CheetahTranscript flush() throws CheetahException {
if (handle == 0) {
throw new CheetahInvalidStateException("Attempted to call Cheetah flush after delete.");
}
return CheetahNative.flush(handle);
}
/**
* Getter for required number of audio samples per frame.
*
* @return Required number of audio samples per frame.
*/
public int getFrameLength() {
return CheetahNative.getFrameLength();
}
/**
* Getter for required audio sample rate for PCM data.
*
* @return Required audio sample rate for PCM data.
*/
public int getSampleRate() {
return CheetahNative.getSampleRate();
}
/**
* Getter for Cheetah version.
*
* @return Cheetah version.
*/
public String getVersion() {
return CheetahNative.getVersion();
}
/**
* Builder for creating an instance of Cheetah with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String modelPath = null;
private float endpointDuration = 1f;
private boolean enableAutomaticPunctuation = false;
/**
* Setter the AccessKey.
*
* @param accessKey AccessKey obtained from Picovoice Console
*/
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
/**
* Setter for the absolute path to the file containing Cheetah model parameters.
*
* @param modelPath Absolute path to the file containing Cheetah model parameters.
*/
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
/**
* Setter for the duration of endpoint in seconds.
*
* @param endpointDuration Duration of endpoint in seconds.
*/
public Builder setEndpointDuration(float endpointDuration) {
this.endpointDuration = endpointDuration;
return this;
}
/**
* Setter for enabling automatic punctuation insertion.
*
* @param enableAutomaticPunctuation Set to `true` to enable automatic punctuation insertion.
*/
public Builder setEnableAutomaticPunctuation(boolean enableAutomaticPunctuation) {
this.enableAutomaticPunctuation = enableAutomaticPunctuation;
return this;
}
/**
* Validates properties and creates an instance of the Cheetah speech-to-text engine.
*
* @return An instance of Cheetah Engine
* @throws CheetahException if there is an error while initializing Cheetah.
*/
public Cheetah build(Context context) throws CheetahException {
if (accessKey == null || this.accessKey.equals("")) {
throw new CheetahInvalidArgumentException("No AccessKey was provided to Cheetah");
}
if (modelPath == null) {
throw new CheetahInvalidArgumentException("ModelPath must not be null");
} 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 CheetahIOException(ex);
}
}
}
if (endpointDuration < 0f) {
throw new CheetahInvalidArgumentException("endpointDuration must be greater than or equal to 0.0");
}
return new Cheetah(
accessKey,
modelPath,
endpointDuration,
enableAutomaticPunctuation);
}
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/CheetahNative.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.cheetah;
class CheetahNative {
static native String getVersion();
static native int getFrameLength();
static native int getSampleRate();
static native void setSdk(String sdk) throws CheetahException;
static native long init(
String accessKey,
String modelPath,
float endpointDurationSec,
boolean enableAutomaticPunctuation) throws CheetahException;
static native void delete(long object);
static native CheetahTranscript process(long object, short[] pcm) throws CheetahException;
static native CheetahTranscript flush(long object) throws CheetahException;
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/CheetahTranscript.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.cheetah;
/**
* Cheetah Speech-to-Text engine Transcript Object.
*/
public class CheetahTranscript {
private final String transcript;
private final boolean isEndpoint;
/**
* Constructor.
*
* @param transcript String transcript returned from Cheetah
* @param isEndpoint Whether the transcript has an endpoint
*/
public CheetahTranscript(String transcript, boolean isEndpoint) {
this.transcript = transcript;
this.isEndpoint = isEndpoint;
}
/**
* Getter for transcript.
*
* @return Transcript string.
*/
public String getTranscript() {
return transcript;
}
/**
* Getter for isEndpoint.
*
* @return Whether the transcript has an endpoint.
*/
public boolean getIsEndpoint() {
return isEndpoint;
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahActivationException.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.cheetah;
public class CheetahActivationException extends CheetahException {
public CheetahActivationException(Throwable cause) {
super(cause);
}
public CheetahActivationException(String message) {
super(message);
}
public CheetahActivationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahActivationLimitException.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.cheetah;
public class CheetahActivationLimitException extends CheetahException {
public CheetahActivationLimitException(Throwable cause) {
super(cause);
}
public CheetahActivationLimitException(String message) {
super(message);
}
public CheetahActivationLimitException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahActivationRefusedException.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.cheetah;
public class CheetahActivationRefusedException extends CheetahException {
public CheetahActivationRefusedException(Throwable cause) {
super(cause);
}
public CheetahActivationRefusedException(String message) {
super(message);
}
public CheetahActivationRefusedException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahActivationThrottledException.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.cheetah;
public class CheetahActivationThrottledException extends CheetahException {
public CheetahActivationThrottledException(Throwable cause) {
super(cause);
}
public CheetahActivationThrottledException(String message) {
super(message);
}
public CheetahActivationThrottledException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahException.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.cheetah;
public class CheetahException extends Exception {
private final String message;
private final String[] messageStack;
public CheetahException(Throwable cause) {
super(cause);
this.message = cause.getMessage();
this.messageStack = null;
}
public CheetahException(String message) {
super(message);
this.message = message;
this.messageStack = null;
}
public CheetahException(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/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahIOException.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.cheetah;
public class CheetahIOException extends CheetahException {
public CheetahIOException(Throwable cause) {
super(cause);
}
public CheetahIOException(String message) {
super(message);
}
public CheetahIOException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahInvalidArgumentException.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.cheetah;
public class CheetahInvalidArgumentException extends CheetahException {
public CheetahInvalidArgumentException(Throwable cause) {
super(cause);
}
public CheetahInvalidArgumentException(String message) {
super(message);
}
public CheetahInvalidArgumentException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahInvalidStateException.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.cheetah;
public class CheetahInvalidStateException extends CheetahException {
public CheetahInvalidStateException(Throwable cause) {
super(cause);
}
public CheetahInvalidStateException(String message) {
super(message);
}
public CheetahInvalidStateException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahKeyException.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.cheetah;
public class CheetahKeyException extends CheetahException {
public CheetahKeyException(Throwable cause) {
super(cause);
}
public CheetahKeyException(String message) {
super(message);
}
public CheetahKeyException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahMemoryException.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.cheetah;
public class CheetahMemoryException extends CheetahException {
public CheetahMemoryException(Throwable cause) {
super(cause);
}
public CheetahMemoryException(String message) {
super(message);
}
public CheetahMemoryException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahRuntimeException.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.cheetah;
public class CheetahRuntimeException extends CheetahException {
public CheetahRuntimeException(Throwable cause) {
super(cause);
}
public CheetahRuntimeException(String message) {
super(message);
}
public CheetahRuntimeException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah
|
java-sources/ai/picovoice/cheetah-android/2.3.0/ai/picovoice/cheetah/exception/CheetahStopIterationException.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.cheetah;
public class CheetahStopIterationException extends CheetahException {
public CheetahStopIterationException(Throwable cause) {
super(cause);
}
public CheetahStopIterationException(String message) {
super(message);
}
public CheetahStopIterationException(String message, String[] messageStack) {
super(message, messageStack);
}
}
|
0
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice/cheetah/Cheetah.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.cheetah;
import java.io.File;
/**
* Cheetah Class.
*/
public class Cheetah {
private static String sdk = "java";
public static final String LIBRARY_PATH;
public static final String MODEL_PATH;
static {
LIBRARY_PATH = Utils.getPackagedLibraryPath();
MODEL_PATH = Utils.getPackagedModelPath();
}
public static void setSdk(String sdk) {
Cheetah.sdk = sdk;
}
private long handle;
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console.
* @param modelPath Absolute path to the file containing model parameters.
* @param libraryPath Absolute path to the native Cheetah library.
* @param endpointDurationSec Duration of endpoint in seconds. A speech endpoint is detected when there is a
* chunk of audio (with a duration specified herein) after an utterance without
* any speech in it. Set duration to 0 to disable this.
* Default is 1 second in the Builder.
* @param enableAutomaticPunctuation Set to `true` to enable automatic punctuation insertion.
* @throws CheetahException if there is an error while initializing Cheetah.
*/
private Cheetah(
String accessKey,
String modelPath,
String libraryPath,
float endpointDurationSec,
boolean enableAutomaticPunctuation) throws CheetahException {
try {
System.load(libraryPath);
} catch (Exception exception) {
throw new CheetahException(exception);
}
CheetahNative.setSdk(Cheetah.sdk);
handle = CheetahNative.init(
accessKey,
modelPath,
endpointDurationSec,
enableAutomaticPunctuation);
}
/**
* Releases resources acquired by Cheetah.
*/
public void delete() {
if (handle != 0) {
CheetahNative.delete(handle);
handle = 0;
}
}
/**
* Processes given audio data and returns its transcription.
*
* @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,
* Cheetah operates on single channel audio only.
* @return Inferred transcription.
* @throws CheetahException if there is an error while processing the audio frame.
*/
public CheetahTranscript process(short[] pcm) throws CheetahException {
if (handle == 0) {
throw new CheetahInvalidStateException("Attempted to call Cheetah process after delete.");
}
if (pcm == null) {
throw new CheetahInvalidArgumentException("Passed null frame to Cheetah process.");
}
if (pcm.length != getFrameLength()) {
throw new CheetahInvalidArgumentException(
String.format("Cheetah process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
return CheetahNative.process(handle, pcm);
}
/**
* Processes any remaining audio data and returns its transcription.
*
* @return Inferred transcription.
* @throws CheetahException if there is an error while processing the audio frame.
*/
public CheetahTranscript flush() throws CheetahException {
if (handle == 0) {
throw new CheetahInvalidStateException("Attempted to call Cheetah flush after delete.");
}
return CheetahNative.flush(handle);
}
/**
* Getter for required number of audio samples per frame.
*
* @return Required number of audio samples per frame.
*/
public int getFrameLength() {
return CheetahNative.getFrameLength();
}
/**
* Getter for required audio sample rate for PCM data.
*
* @return Required audio sample rate for PCM data.
*/
public int getSampleRate() {
return CheetahNative.getSampleRate();
}
/**
* Getter for Cheetah version.
*
* @return Cheetah version.
*/
public String getVersion() {
return CheetahNative.getVersion();
}
/**
* Builder for creating an instance of Cheetah with a mixture of default arguments.
*/
public static class Builder {
private String accessKey = null;
private String libraryPath = null;
private String modelPath = null;
private float endpointDuration = 1f;
private boolean enableAutomaticPunctuation = false;
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
public Builder setLibraryPath(String libraryPath) {
this.libraryPath = libraryPath;
return this;
}
/**
* Setter for the absolute path to the file containing Cheetah model parameters.
*
* @param modelPath Absolute path to the file containing Cheetah model parameters.
*/
public Builder setModelPath(String modelPath) {
this.modelPath = modelPath;
return this;
}
/**
* Setter for the duration of endpoint in seconds.
*
* @param endpointDuration Duration of endpoint in seconds. A speech endpoint is detected when there is a
* chunk of audio (with a duration specified herein) after an utterance without
* any speech in it.
*/
public Builder setEndpointDuration(float endpointDuration) {
this.endpointDuration = endpointDuration;
return this;
}
/**
* Setter for enabling automatic punctuation insertion.
*
* @param enableAutomaticPunctuation Set to `true` to enable automatic punctuation insertion.
*/
public Builder setEnableAutomaticPunctuation(boolean enableAutomaticPunctuation) {
this.enableAutomaticPunctuation = enableAutomaticPunctuation;
return this;
}
/**
* Validates properties and creates an instance of the Cheetah speech-to-text engine.
*
* @return An instance of Cheetah Engine
* @throws CheetahException if there is an error while initializing Cheetah.
*/
public Cheetah build() throws CheetahException {
if (!Utils.isEnvironmentSupported()) {
throw new CheetahRuntimeException("Could not initialize Cheetah. " +
"Execution environment not currently supported by Cheetah Java.");
}
if (accessKey == null) {
throw new CheetahInvalidArgumentException("AccessKey must not be null");
}
if (libraryPath == null) {
if (Utils.isResourcesAvailable()) {
libraryPath = LIBRARY_PATH;
} else {
throw new CheetahInvalidArgumentException("Default library unavailable. Please " +
"provide a native Cheetah library path (-l <library_path>).");
}
if (!new File(libraryPath).exists()) {
throw new CheetahIOException(String.format("Couldn't find library file at " +
"'%s'", libraryPath));
}
}
if (modelPath == null) {
if (Utils.isResourcesAvailable()) {
modelPath = MODEL_PATH;
} else {
throw new CheetahInvalidArgumentException("Default model unavailable. Please provide a " +
"valid Cheetah model path (-m <model_path>).");
}
if (!new File(modelPath).exists()) {
throw new CheetahIOException(String.format("Couldn't find model file at " +
"'%s'", modelPath));
}
}
if (endpointDuration < 0f) {
throw new CheetahInvalidArgumentException("endpointDuration must be greater than or equal to 0.0");
}
return new Cheetah(
accessKey,
modelPath,
libraryPath,
endpointDuration,
enableAutomaticPunctuation);
}
}
}
|
0
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice/cheetah/CheetahNative.java
|
/*
Copyright 2022 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.cheetah;
class CheetahNative {
static native int getFrameLength();
static native int getSampleRate();
static native String getVersion();
static native void setSdk(String sdk);
static native long init(
String accessKey,
String modelPath,
float endpointDurationSec,
boolean enableAutomaticPunctuation) throws CheetahException;
static native void delete(long object);
static native CheetahTranscript process(long object, short[] pcm) throws CheetahException;
static native CheetahTranscript flush(long object) throws CheetahException;
}
|
0
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice/cheetah/CheetahTranscript.java
|
/*
Copyright 2022 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.cheetah;
/**
* Cheetah Speech-to-Text engine Transcript Object.
*/
public class CheetahTranscript {
private final String transcript;
private final boolean isEndpoint;
/**
* Constructor.
*
* @param transcript String transcript returned from Cheetah
* @param isEndpoint Whether the transcript has an endpoint
*/
public CheetahTranscript(String transcript, boolean isEndpoint) {
this.transcript = transcript;
this.isEndpoint = isEndpoint;
}
/**
* Getter for transcript.
*
* @return Transcript string.
*/
public String getTranscript() {
return transcript;
}
/**
* Getter for isEndpoint.
*
* @return Whether the transcript has an endpoint.
*/
public boolean getIsEndpoint() {
return isEndpoint;
}
}
|
0
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice
|
java-sources/ai/picovoice/cheetah-java/2.3.0/ai/picovoice/cheetah/Utils.java
|
/*
Copyright 2022-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.cheetah;
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 = Cheetah.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 Cheetah jar.");
}
}
return resourcePath.resolve("cheetah");
}
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("cheetah")) {
// 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. " +
"Cheetah Java does not support CPU Part (%s).", cpuPart));
}
}
return "linux";
} else {
throw new RuntimeException("Execution environment not supported. " +
"Cheetah 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;
default:
throw new RuntimeException(
String.format(
"Environment (%s) with CPU Part (%s) is not supported by Cheetah.",
ENVIRONMENT_NAME,
cpuPart)
);
}
}
throw new RuntimeException(
String.format(
"Environment (%s) with architecture (%s) is not supported by Cheetah.",
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("Cheetah failed to get get CPU information.");
}
}
public static String getPackagedModelPath() {
return RESOURCE_DIRECTORY.resolve("lib/common/cheetah_params.pv").toString();
}
public static String getPackagedLibraryPath() {
switch (ENVIRONMENT_NAME) {
case "windows":
return RESOURCE_DIRECTORY.resolve("lib/java/windows")
.resolve(ARCHITECTURE)
.resolve("libpv_cheetah_jni.dll").toString();
case "mac":
return RESOURCE_DIRECTORY.resolve("lib/java/mac")
.resolve(ARCHITECTURE)
.resolve("libpv_cheetah_jni.dylib").toString();
case "raspberry-pi":
case "linux":
return RESOURCE_DIRECTORY.resolve("lib/java")
.resolve(ENVIRONMENT_NAME)
.resolve(ARCHITECTURE)
.resolve("libpv_cheetah_jni.so").toString();
default:
return null;
}
}
}
|
0
|
java-sources/ai/picovoice/cobra-android/2.1.0/ai/picovoice
|
java-sources/ai/picovoice/cobra-android/2.1.0/ai/picovoice/cobra/Cobra.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.cobra;
/**
* Android binding for Cobra voice activity detection (VAD) engine. It detects speech signals
* within an incoming stream of audio in real-time. It processes incoming audio in consecutive
* frames and for each frame emits the probability of voice activity. 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. Cobra operates on
* single-channel audio.
**/
public class Cobra {
private static String _sdk = "android";
static {
System.loadLibrary("pv_cobra");
}
private long handle;
public static void setSdk(String sdk) {
Cobra._sdk = sdk;
}
/**
* Constructor.
*
* @param accessKey AccessKey obtained from Picovoice Console
* @throws CobraException if there is an error while initializing Cobra.
*/
public Cobra(String accessKey) throws CobraException {
CobraNative.setSdk(Cobra._sdk);
handle = CobraNative.init(accessKey);
}
/**
* Releases resources acquired by Cobra.
*/
public void delete() {
if (handle != 0) {
CobraNative.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. Furthermore,
* Cobra operates on single channel audio only.
* @return Probability of voice activity. It is a floating-point number within [0, 1].
* @throws CobraException if there is an error while processing the audio frame.
*/
public float process(short[] pcm) throws CobraException {
if (handle == 0) {
throw new CobraInvalidStateException("Attempted to call Cobra process after delete.");
}
if (pcm == null) {
throw new CobraInvalidArgumentException("Passed null frame to Cobra process.");
}
if (pcm.length != getFrameLength()) {
throw new CobraInvalidArgumentException(
String.format("Cobra process requires frames of length %d. " +
"Received frame of size %d.", getFrameLength(), pcm.length));
}
return CobraNative.process(handle, pcm);
}
/**
* Getter for required number of audio samples per frame.
*
* @return Required number of audio samples per frame.
*/
public int getFrameLength() {
return CobraNative.getFrameLength();
}
/**
* Getter for required audio sample rate.
*
* @return Required audio sample rate.
*/
public int getSampleRate() {
return CobraNative.getSampleRate();
}
/**
* Getter for Cobra version.
*
* @return Cobra version.
*/
public String getVersion() {
return CobraNative.getVersion();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.