index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/EngineProvider.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine;
/**
* The {@code EngineProvider} instance manufactures an {@link Engine} instance, which is available
* in the system.
*
* <p>At initialization time, the {@link java.util.ServiceLoader} will search for {@code
* EngineProvider} implementations available in the class path.
*
* <p>{@link Engine} is designed as a collection of singletons. {@link Engine#getInstance()} will
* return the default Engine, which is the first one found in the classpath. Many of the standard
* APIs will rely on this default Engine instance such as when creating a {@link
* ai.djl.ndarray.NDManager} or {@link ai.djl.Model}. However, you can directly get a specific
* Engine instance (e.g. {@code MxEngine}) by calling {@link Engine#getEngine(String)}.
*/
public interface EngineProvider {
/**
* Returns the name of the {@link Engine}.
*
* @return the name of {@link Engine}
*/
String getEngineName();
/**
* Returns the rank of the {@link Engine}.
*
* @return the rank of {@link Engine}
*/
int getEngineRank();
/**
* Returns the instance of the {@link Engine} class EngineProvider should bind to.
*
* @return the instance of {@link Engine}
*/
Engine getEngine();
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/StandardCapabilities.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine;
/** Constant definitions for the standard capability. */
public final class StandardCapabilities {
public static final String CUDA = "CUDA";
public static final String CUDNN = "CUDNN";
public static final String MKL = "MKL";
public static final String MKLDNN = "MKLDNN";
public static final String OPENMP = "OPENMP";
private StandardCapabilities() {}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* Contains classes responsible for loading a deep learning engine.
*
* <p>Deep Java Library (DJL) is a higher level API that is used alongside implementations built on
* other deep learning engines. By using only the higher level abstractions defined in the core DJL
* API, it makes it easy to switch between underlying engines.
*
* <p>Each deep learning engine is implemented as a {@link java.util.ServiceLoader} and supplies an
* implementation of the {@link ai.djl.engine.Engine} interface.
*
* @see ai.djl.engine.Engine
* @see ai.djl.engine.EngineProvider
*/
package ai.djl.engine;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcClient.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.inference.streaming.ChunkedBytesSupplier;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.ndarray.BytesSupplier;
import ai.djl.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
/** A client used to connect to remote model server. */
public final class RpcClient {
private static final Logger logger = LoggerFactory.getLogger(RpcClient.class);
private static final Set<String> RESERVED_KEYS =
new HashSet<>(
Arrays.asList(
"engine",
"translatorfactory",
"translator",
"model_name",
"artifact_id",
"application",
"task",
"djl_rpc_uri",
"method",
"api_key",
"content-type"));
private URL url;
private String method;
private Map<CaseInsensitiveKey, String> headers;
private RpcClient(URL url, String method, Map<CaseInsensitiveKey, String> headers) {
this.url = url;
this.method = method;
this.headers = headers;
}
/**
* Returns a new {@code Client} instance from criteria arguments.
*
* @param arguments the criteria arguments.
* @return a new {@code Client} instance
* @throws MalformedURLException if url is invalid
*/
public static RpcClient getClient(Map<String, ?> arguments) throws MalformedURLException {
String url = arguments.get("djl_rpc_uri").toString();
String method = getOrDefault(arguments, "method", "POST");
String apiKey = getOrDefault(arguments, "api_key", null);
String contentType = getOrDefault(arguments, "content-type", "application/json");
Map<CaseInsensitiveKey, String> httpHeaders = new ConcurrentHashMap<>();
for (Map.Entry<String, ?> entry : arguments.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString().trim();
if (RESERVED_KEYS.contains(key.toLowerCase(Locale.ROOT))) {
continue;
}
httpHeaders.put(new CaseInsensitiveKey(key), value);
}
httpHeaders.put(new CaseInsensitiveKey("Content-Type"), contentType);
if (url.startsWith("https://generativelanguage.googleapis.com")) {
if (apiKey == null) {
apiKey = Utils.getenv("GEMINI_API_KEY");
if (apiKey == null) {
apiKey = Utils.getenv("GOOGLE_API_KEY");
}
}
if (apiKey != null) {
if (url.endsWith("/openai/chat/completions")) {
httpHeaders.put(new CaseInsensitiveKey("Authorization"), "Bearer " + apiKey);
} else {
httpHeaders.put(new CaseInsensitiveKey("x-goog-api-key"), apiKey);
}
}
} else if (url.startsWith("https://api.anthropic.com")) {
if (apiKey == null) {
apiKey = Utils.getEnvOrSystemProperty("ANTHROPIC_API_KEY");
}
if (apiKey != null) {
httpHeaders.put(new CaseInsensitiveKey("x-api-key"), apiKey);
}
}
if (apiKey == null) {
apiKey = Utils.getEnvOrSystemProperty("GENAI_API_KEY");
}
if (apiKey != null) {
httpHeaders.put(new CaseInsensitiveKey("Authorization"), "Bearer " + apiKey);
}
return new RpcClient(new URL(url), method, httpHeaders);
}
/**
* Sends request to remote server.
*
* @param input the input
* @return the output
* @throws IOException if connection failed
*/
public Output send(Input input) throws IOException {
if (Utils.isOfflineMode()) {
throw new IOException("Offline mode is enabled.");
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
boolean isStream = false;
try {
conn.setRequestMethod(method);
if ("POST".equals(method) || "PUT".equals(method)) {
conn.setDoOutput(true);
}
Map<String, String> prop = input.getProperties();
Map<CaseInsensitiveKey, String> reqHeaders = new ConcurrentHashMap<>(headers);
for (Map.Entry<String, String> entry : prop.entrySet()) {
reqHeaders.put(new CaseInsensitiveKey(entry.getKey()), entry.getValue());
}
for (Map.Entry<CaseInsensitiveKey, String> header : reqHeaders.entrySet()) {
conn.addRequestProperty(header.getKey().key, header.getValue());
}
conn.connect();
BytesSupplier content = input.getData();
if (content != null) {
try (OutputStream os = conn.getOutputStream()) {
os.write(content.getAsBytes());
}
}
int code = conn.getResponseCode();
Output out = new Output(code, conn.getResponseMessage());
Map<String, List<String>> respHeaders = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : respHeaders.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().get(0);
if (key != null && value != null) {
value = value.toLowerCase(Locale.ROOT);
if ("content-type".equalsIgnoreCase(key)
&& (value.startsWith("text/event-stream")
|| value.startsWith("application/jsonlines"))) {
isStream = true;
}
out.addProperty(key, value);
}
}
if (code == 200) {
if (isStream) {
ChunkedBytesSupplier cbs = new ChunkedBytesSupplier();
out.add(cbs);
CompletableFuture.supplyAsync(() -> handleStream(conn, cbs));
} else {
try (InputStream is = conn.getInputStream()) {
out.add(Utils.toByteArray(is));
}
}
} else {
try (InputStream is = conn.getErrorStream()) {
if (is != null) {
String error = Utils.toString(is);
out.add(error);
logger.warn("Failed to invoke model server: {}", error);
} else {
logger.warn("Failed to invoke model server, code: {}", code);
}
}
}
return out;
} finally {
if (!isStream) {
conn.disconnect();
}
}
}
private static String getOrDefault(Map<String, ?> arguments, String key, String def) {
for (Map.Entry<String, ?> entry : arguments.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue().toString();
}
}
return def;
}
private static Void handleStream(HttpURLConnection conn, ChunkedBytesSupplier cbs) {
BytesSupplier pendingChunk = null;
try (Reader r = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(r)) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
if (line.startsWith("data: ")) {
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(line.substring(6));
} else if (line.startsWith("event: ")) {
// ignore
continue;
} else if (!line.isEmpty()) {
// jsonlines
if (pendingChunk != null) {
cbs.appendContent(pendingChunk, false);
}
pendingChunk = BytesSupplier.wrap(line);
} else if (sb.length() > 0) {
if (pendingChunk != null) {
cbs.appendContent(pendingChunk, false);
}
pendingChunk = BytesSupplier.wrap(sb.toString());
sb.setLength(0);
}
}
} catch (IOException e) {
logger.warn("Failed run inference.", e);
cbs.appendContent(BytesSupplier.wrap("connection abort exceptionally"), false);
} finally {
if (pendingChunk == null) {
pendingChunk = BytesSupplier.wrap(new byte[0]);
}
cbs.appendContent(pendingChunk, true);
conn.disconnect();
}
return null;
}
static final class CaseInsensitiveKey {
String key;
public CaseInsensitiveKey(String key) {
this.key = key;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CaseInsensitiveKey)) {
return false;
}
CaseInsensitiveKey header = (CaseInsensitiveKey) o;
return key.equalsIgnoreCase(header.key);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hashCode(key.toLowerCase(Locale.ROOT));
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcEngine.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.Device;
import ai.djl.Model;
import ai.djl.engine.Engine;
import ai.djl.ndarray.NDManager;
import ai.djl.util.passthrough.PassthroughNDManager;
/** The {@code RpcEngine} is a client side implementation for remote model server. */
public class RpcEngine extends Engine {
public static final String ENGINE_NAME = "RPC";
static final int RANK = 15;
private Engine alternativeEngine;
private boolean initialized;
static Engine newInstance() {
return new RpcEngine();
}
/** {@inheritDoc} */
@Override
public Engine getAlternativeEngine() {
if (!initialized && !Boolean.getBoolean("ai.djl.java.disable_alternative")) {
Engine engine = Engine.getInstance();
if (engine.getRank() < getRank()) {
// alternativeEngine should not have the same rank as OnnxRuntime
alternativeEngine = engine;
}
initialized = true;
}
return alternativeEngine;
}
/** {@inheritDoc} */
@Override
public String getEngineName() {
return ENGINE_NAME;
}
/** {@inheritDoc} */
@Override
public int getRank() {
return RANK;
}
/** {@inheritDoc} */
@Override
public String getVersion() {
return Engine.class.getPackage().getSpecificationVersion();
}
/** {@inheritDoc} */
@Override
public boolean hasCapability(String capability) {
return false;
}
/** {@inheritDoc} */
@Override
public Model newModel(String name, Device device) {
return new RpcModel(name);
}
/** {@inheritDoc} */
@Override
public NDManager newBaseManager() {
return newBaseManager(null);
}
/** {@inheritDoc} */
@Override
public NDManager newBaseManager(Device device) {
return PassthroughNDManager.INSTANCE;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcEngineProvider.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.engine.Engine;
import ai.djl.engine.EngineProvider;
/** {@code RpcEngineProvider} is the client side implementation for remote model server. */
public class RpcEngineProvider implements EngineProvider {
/** {@inheritDoc} */
@Override
public String getEngineName() {
return RpcEngine.ENGINE_NAME;
}
/** {@inheritDoc} */
@Override
public int getEngineRank() {
return RpcEngine.RANK;
}
/** {@inheritDoc} */
@Override
public Engine getEngine() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
static final Engine INSTANCE = RpcEngine.newInstance();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcModel.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.BaseModel;
import ai.djl.MalformedModelException;
import ai.djl.Model;
import ai.djl.ndarray.types.DataType;
import ai.djl.util.passthrough.PassthroughNDManager;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
/** {@code RpcModel} is an implementation for the {@link Model} deployed on remote model server. */
public class RpcModel extends BaseModel {
/**
* Constructs a new Model on a given device.
*
* @param name the model name
*/
RpcModel(String name) {
super(name);
manager = PassthroughNDManager.INSTANCE;
dataType = DataType.FLOAT32;
}
/** {@inheritDoc} */
@Override
public void load(Path modelPath, String prefix, Map<String, ?> options)
throws IOException, MalformedModelException {
setModelDir(modelPath);
wasLoaded = true;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcTranslator.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.ndarray.NDList;
import ai.djl.translate.NoBatchifyTranslator;
import ai.djl.translate.TranslateException;
import ai.djl.translate.TranslatorContext;
import java.io.IOException;
/** The {@link ai.djl.translate.Translator} for model deploy on remote model server. */
public class RpcTranslator<I, O> implements NoBatchifyTranslator<I, O> {
private RpcClient client;
private TypeConverter<I, O> converter;
/**
* Constructs a {@code RpcTranslator} instance.
*
* @param client a {@link RpcClient} connects to remote model server
* @param converter a {@link TypeConverter} to convert data type
*/
protected RpcTranslator(RpcClient client, TypeConverter<I, O> converter) {
this.client = client;
this.converter = converter;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, I input) throws IOException {
Input in = converter.toInput(input);
Output output = client.send(in);
ctx.setAttachment("output", output);
return new NDList();
}
/** {@inheritDoc} */
@Override
public O processOutput(TranslatorContext ctx, NDList list) throws TranslateException {
Output output = (Output) ctx.getAttachment("output");
return converter.fromOutput(output);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/RpcTranslatorFactory.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.Model;
import ai.djl.inference.streaming.ChunkedBytesSupplier;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.ndarray.BytesSupplier;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import ai.djl.util.JsonUtils;
import ai.djl.util.Pair;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/** A {@link TranslatorFactory} that creates an {@link RpcTranslator}. */
public class RpcTranslatorFactory implements TranslatorFactory {
private TypeConverter<?, ?> converter;
private Set<Pair<Type, Type>> supportedTypes;
/** Constructs a {@code RpcTranslatorFactory} instance. */
public RpcTranslatorFactory() {
supportedTypes = Collections.emptySet();
}
/**
* Constructs a {@code RpcTranslatorFactory} instance.
*
* @param converter the {@code TypeConverter}
*/
public RpcTranslatorFactory(TypeConverter<?, ?> converter) {
this.converter = converter;
supportedTypes = Collections.singleton(converter.getSupportedType());
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <I, O> Translator<I, O> newInstance(
Class<I> input, Class<O> output, Model model, Map<String, ?> arguments)
throws TranslateException {
try {
if (!isSupported(input, output)) {
throw new IllegalArgumentException("Unsupported input/output types.");
}
RpcClient client = RpcClient.getClient(arguments);
if (converter != null) {
return new RpcTranslator<>(client, (TypeConverter<I, O>) converter);
}
return new RpcTranslator<>(client, new DefaultTypeConverter<>(input, output));
} catch (IOException e) {
throw new TranslateException(e);
}
}
/** {@inheritDoc} */
@Override
public Set<Pair<Type, Type>> getSupportedTypes() {
return supportedTypes;
}
/** {@inheritDoc} */
@Override
public boolean isSupported(Class<?> input, Class<?> output) {
if (converter == null) {
return true;
}
return TranslatorFactory.super.isSupported(input, output);
}
private static final class DefaultTypeConverter<I, O> implements TypeConverter<I, O> {
private Class<I> input;
private Class<O> output;
private Method fromJson;
private Method fromJsonStream;
DefaultTypeConverter(Class<I> input, Class<O> output) {
this.input = input;
this.output = output;
try {
fromJsonStream = output.getDeclaredMethod("fromJson", Iterator.class);
} catch (ReflectiveOperationException e) {
// ignore
}
try {
fromJson = output.getDeclaredMethod("fromJson", String.class);
} catch (ReflectiveOperationException e) {
// ignore
}
}
/** {@inheritDoc} */
@Override
public Pair<Type, Type> getSupportedType() {
return new Pair<>(input, output);
}
/** {@inheritDoc} */
@Override
public Input toInput(I in) {
if (in instanceof Input) {
return (Input) in;
}
Input converted = new Input();
if (in instanceof String) {
converted.add((String) in);
} else if (in instanceof byte[]) {
converted.add((byte[]) in);
} else {
converted.add(BytesSupplier.wrapAsJson(in));
}
return converted;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public O fromOutput(Output out) throws TranslateException {
if (output == Output.class) {
return (O) out;
}
int code = out.getCode();
BytesSupplier data = out.getData();
if (code != 200) {
String error;
if (data == null) {
error = out.getMessage();
} else {
error = out.getMessage() + " " + data.getAsString();
}
throw new TranslateException(error);
}
if (output == String.class) {
return (O) data.getAsString();
}
try {
if (data instanceof ChunkedBytesSupplier && fromJsonStream != null) {
Iterator<String> it = new ChunkIterator((ChunkedBytesSupplier) data);
return (O) fromJsonStream.invoke(null, it);
} else if (fromJson != null) {
return (O) fromJson.invoke(null, data.getAsString());
}
} catch (ReflectiveOperationException e) {
throw new TranslateException("Failed convert from json", e);
}
return JsonUtils.GSON.fromJson(data.getAsString(), output);
}
}
private static final class ChunkIterator implements Iterator<String> {
private ChunkedBytesSupplier cbs;
private boolean error;
ChunkIterator(ChunkedBytesSupplier cbs) {
this.cbs = cbs;
}
@Override
public boolean hasNext() {
if (error) {
return false;
}
return cbs.hasNext();
}
@Override
public String next() {
try {
return new String(cbs.nextChunk(20, TimeUnit.SECONDS), StandardCharsets.UTF_8);
} catch (InterruptedException e) {
error = true;
return null;
}
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/TypeConverter.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.engine.rpc;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.translate.TranslateException;
import ai.djl.util.Pair;
import java.lang.reflect.Type;
/**
* A {code TypeConverter} interface defines how data type is converted to Input/Output.
*
* @param <I> the target input type
* @param <O> the target output type
*/
public interface TypeConverter<I, O> {
/**
* Returns the supported type.
*
* @return the supported type
*/
Pair<Type, Type> getSupportedType();
/**
* Convert the data type to {@link Input}.
*
* @param in the input data
* @return the converted data
*/
Input toInput(I in);
/**
* Convert the {@link Output} to target data type.
*
* @param out the output data
* @return the converted data
*/
O fromOutput(Output out) throws TranslateException;
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/rpc/package-info.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains classes to interface with the underlying RPC engine. */
package ai.djl.engine.rpc;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/Predictor.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference;
import ai.djl.Device;
import ai.djl.Model;
import ai.djl.inference.streaming.StreamingBlock;
import ai.djl.inference.streaming.StreamingTranslator;
import ai.djl.inference.streaming.StreamingTranslator.StreamOutput;
import ai.djl.metric.Dimension;
import ai.djl.metric.Metrics;
import ai.djl.metric.Unit;
import ai.djl.ndarray.LazyNDArray;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.nn.Block;
import ai.djl.training.ParameterStore;
import ai.djl.translate.Batchifier;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* The {@code Predictor} interface provides a session for model inference.
*
* <p>You can use a {@code Predictor}, with a specified {@link Translator}, to perform inference on
* a {@link Model}. The following is example code that uses {@code Predictor}:
*
* <pre>
* Model model = Model.load(modelDir, modelName);
*
* // User must implement Translator interface, read {@link Translator} for detail.
* Translator<String, String> translator = new MyTranslator();
*
* try (Predictor<String, String> predictor = model.newPredictor(translator)) {
* String result = predictor.predict("What's up");
* }
* </pre>
*
* <p>See the tutorials on:
*
* <ul>
* <li><a
* href="https://docs.djl.ai/master/docs/demos/jupyter/tutorial/03_image_classification_with_your_model.html">Inference
* with a custom trained model</a>
* <li><a
* href="https://docs.djl.ai/master/docs/demos/jupyter/object_detection_with_model_zoo.html">Inference
* with a model zoo model</a>
* <li><a href="https://docs.djl.ai/master/docs/demos/jupyter/load_mxnet_model.html">Inference
* with an MXNet model</a>
* </ul>
*
* @param <I> the input type
* @param <O> the output type
* @see Model
* @see Translator
* @see <a href="https://docs.djl.ai/master/docs/development/memory_management.html">The guide on
* memory management</a>
* @see <a
* href="https://github.com/deepjavalibrary/djl/blob/master/examples/docs/multithread_inference.md">The
* guide on running multi-threaded inference</a>
* @see <a
* href="https://docs.djl.ai/master/docs/development/inference_performance_optimization.html">The
* guide on inference performance optimization</a>
*/
public class Predictor<I, O> implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(Predictor.class);
protected Translator<I, O> translator;
protected long timestamp;
protected boolean prepared;
protected Model model;
protected NDManager manager;
protected Metrics metrics;
protected Block block;
protected ParameterStore parameterStore;
protected Dimension dimension;
/**
* Creates a new instance of {@code BasePredictor} with the given {@link Model} and {@link
* Translator}.
*
* @param model the model on which the predictions are based
* @param translator the translator to be used
* @param device the device for prediction
* @param copy whether to copy the parameters to the parameter store. If the device changes, it
* will copy regardless
*/
public Predictor(Model model, Translator<I, O> translator, Device device, boolean copy) {
if (!device.equals(model.getNDManager().getDevice())) {
// Always copy during device changes
copy = true;
}
this.model = model;
this.manager = model.getNDManager().newSubManager(device);
this.manager.setName("predictor");
this.translator = translator;
block = model.getBlock();
parameterStore = new ParameterStore(manager, copy);
dimension = new Dimension("Model", model.getProperty("metric_dimension", "model"));
}
/**
* Predicts an item for inference.
*
* @param input the input
* @return the output object defined by the user
* @throws TranslateException if an error occurs during prediction
*/
public O predict(I input) throws TranslateException {
return batchPredict(Collections.singletonList(input)).get(0);
}
/**
* Predicts an item for inference.
*
* @param ctx the context for the {@code Predictor}.
* @param ndList the input {@code NDList}
* @return the output {@code NDList}
* @throws TranslateException if an error occurs during prediction
*/
protected NDList predictInternal(TranslatorContext ctx, NDList ndList)
throws TranslateException {
logger.trace("Predictor input data: {}", ndList);
if (ndList.isEmpty()) {
return new NDList();
}
return block.forward(parameterStore, ndList, false);
}
/**
* Predicts a batch for inference.
*
* @param inputs a list of inputs
* @return a list of output objects defined by the user
* @throws TranslateException if an error occurs during prediction
*/
@SuppressWarnings({"PMD.AvoidRethrowingException", "PMD.IdenticalCatchBranches"})
public List<O> batchPredict(List<I> inputs) throws TranslateException {
try (PredictorContext context = new PredictorContext(model, manager, metrics)) {
if (!prepared) {
translator.prepare(context);
prepared = true;
}
if (translator.getBatchifier() == null) {
List<O> ret = new ArrayList<>(inputs.size());
for (I input : inputs) {
timestamp = System.nanoTime();
long begin = timestamp;
NDList ndList = translator.processInput(context, input);
preprocessEnd(ndList, 1);
NDList result = predictInternal(context, ndList);
predictEnd(result, 1);
ret.add(translator.processOutput(context, result));
postProcessEnd(begin, 1);
}
return ret;
}
int batchSize = inputs.size();
timestamp = System.nanoTime();
long begin = timestamp;
NDList ndList = translator.batchProcessInput(context, inputs);
preprocessEnd(ndList, batchSize);
NDList result = predictInternal(context, ndList);
predictEnd(result, batchSize);
List<O> ret = translator.batchProcessOutput(context, result);
postProcessEnd(begin, batchSize);
return ret;
} catch (TranslateException e) {
throw e;
} catch (Exception e) {
throw new TranslateException(e);
}
}
/**
* Predicts an item for inference.
*
* @param input the input
* @return the output object defined by the user
* @throws TranslateException if an error occurs during prediction
*/
@SuppressWarnings({"PMD.AvoidRethrowingException", "PMD.IdenticalCatchBranches"})
public StreamOutput<O> streamingPredict(I input) throws TranslateException {
String streamingSupported = streamingSupportError();
if (streamingSupported != null) {
throw new IllegalStateException(streamingSupported);
}
StreamingBlock streamingBlock = (StreamingBlock) block;
StreamingTranslator<I, O> streamingTranslator = (StreamingTranslator<I, O>) translator;
try {
PredictorContext context = new PredictorContext(model, manager, metrics);
if (!prepared) {
translator.prepare(context);
prepared = true;
}
Batchifier batchifier = translator.getBatchifier();
if (batchifier == null) {
NDList ndList = translator.processInput(context, input);
return streamingTranslator.processStreamOutput(
context,
streamingBlock
.forwardStream(parameterStore, ndList, false)
.onClose(context::close));
}
// For the batched case, need to create singleton batch and unbatchify singleton
NDList inputBatch = processInputs(context, Collections.singletonList(input));
return streamingTranslator.processStreamOutput(
context,
streamingBlock
.forwardStream(parameterStore, inputBatch, false)
.map(
result -> {
NDList[] unbatched =
translator.getBatchifier().unbatchify(result);
if (unbatched.length != 1) {
throw new IllegalStateException(
"Unexpected number of outputs from model");
}
return unbatched[0];
})
.onClose(context::close));
} catch (TranslateException e) {
throw e;
} catch (Exception e) {
throw new TranslateException(e);
}
}
/**
* Returns true if streaming is supported by the predictor, block, and translator.
*
* @return true if streaming is supported by the predictor, block, and translator
*/
public boolean supportsStreaming() {
return streamingSupportError() == null;
}
private String streamingSupportError() {
if (!(block instanceof StreamingBlock)) {
return "streamingPredict() can only be called with a StreamingBlock";
}
if (!(translator instanceof StreamingTranslator)) {
return "streamingPredict() can only be called with a StreamingTranslator";
}
return null;
}
/**
* Attaches a Metrics param to use for benchmark.
*
* @param metrics the Metrics class
*/
public void setMetrics(Metrics metrics) {
this.metrics = metrics;
}
private void waitToRead(NDList list) {
for (NDArray array : list) {
if (array instanceof LazyNDArray) {
((LazyNDArray) array).waitToRead();
}
}
}
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private NDList processInputs(TranslatorContext ctx, List<I> inputs) throws Exception {
int batchSize = inputs.size();
NDList[] preprocessed = new NDList[batchSize];
for (int i = 0; i < batchSize; ++i) {
preprocessed[i] = translator.processInput(ctx, inputs.get(i));
}
return translator.getBatchifier().batchify(preprocessed);
}
private void preprocessEnd(NDList list, int batchSize) {
if (metrics != null) {
waitToRead(list);
long tmp = System.nanoTime();
long duration = (tmp - timestamp) / 1000 / batchSize;
timestamp = tmp;
metrics.addMetric("Preprocess", duration, Unit.MICROSECONDS, dimension);
}
}
private void predictEnd(NDList list, int batchSize) {
if (metrics != null) {
waitToRead(list);
long tmp = System.nanoTime();
long duration = (tmp - timestamp) / 1000 / batchSize;
timestamp = tmp;
metrics.addMetric("Inference", duration, Unit.MICROSECONDS, dimension);
}
}
private void postProcessEnd(long begin, int batchSize) {
if (metrics != null) {
long tmp = System.nanoTime();
long duration = (tmp - timestamp) / 1000 / batchSize;
timestamp = tmp;
metrics.addMetric("Postprocess", duration, Unit.MICROSECONDS, dimension);
long prediction = (tmp - begin) / 1000;
metrics.addMetric("Prediction", prediction, Unit.MICROSECONDS, dimension);
}
}
/** {@inheritDoc} */
@Override
public void close() {
manager.close();
}
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override
protected void finalize() throws Throwable {
if (manager.isOpen()) {
if (logger.isDebugEnabled()) {
logger.warn("Predictor for {} was not closed explicitly.", model.getName());
}
close();
}
super.finalize();
}
/** An implementation of {@link TranslatorContext}. */
public static final class PredictorContext implements TranslatorContext {
private Model model;
private NDManager predictorManager;
private Metrics metrics;
private NDManager ctxManager;
private Map<String, Object> attachments;
/** Constructs a new {@code PredictorContext} instance. */
public PredictorContext(Model model, NDManager predictorManager, Metrics metrics) {
this.model = model;
this.predictorManager = predictorManager;
this.metrics = metrics;
ctxManager = predictorManager.newSubManager();
ctxManager.setName("predictor ctx");
attachments = new ConcurrentHashMap<>();
}
/** {@inheritDoc} */
@Override
public Model getModel() {
return model;
}
/** {@inheritDoc} */
@Override
public NDManager getNDManager() {
return ctxManager;
}
/** {@inheritDoc} */
@Override
public NDManager getPredictorManager() {
return predictorManager;
}
/** {@inheritDoc} */
@Override
public Block getBlock() {
return model.getBlock();
}
/** {@inheritDoc} */
@Override
public Metrics getMetrics() {
return metrics;
}
/** {@inheritDoc} */
@Override
public void close() {
ctxManager.close();
}
/** {@inheritDoc} */
@Override
public Object getAttachment(String key) {
return attachments.get(key);
}
/** {@inheritDoc} */
@Override
public void setAttachment(String key, Object value) {
attachments.put(key, value);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* Contains classes to implement inference tasks.
*
* @see ai.djl.inference.Predictor
*/
package ai.djl.inference;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/ChunkedBytesSupplier.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference.streaming;
import ai.djl.ndarray.BytesSupplier;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/** A {link BytesSupplier} that supports chunked reading. */
public class ChunkedBytesSupplier implements BytesSupplier {
private LinkedBlockingQueue<BytesSupplier> queue;
private AtomicBoolean completed;
/** Constructs a new {code ChunkedBytesSupplier} instance. */
public ChunkedBytesSupplier() {
queue = new LinkedBlockingQueue<>();
completed = new AtomicBoolean();
}
/**
* Appends content to the {@code BytesSupplier}.
*
* @param data bytes to append
* @param lastChunk true if this is the last chunk
*/
public void appendContent(byte[] data, boolean lastChunk) {
appendContent(BytesSupplier.wrap(data), lastChunk);
}
/**
* Appends content to the {@code BytesSupplier}.
*
* @param bytesSupplier BytesSupplier to append
* @param lastChunk true if this is the last chunk
*/
public void appendContent(BytesSupplier bytesSupplier, boolean lastChunk) {
if (lastChunk) {
completed.set(true);
}
queue.offer(bytesSupplier);
}
/**
* Returns {@code true} if has more chunk.
*
* @return {@code true} if has more chunk
*/
public boolean hasNext() {
return !completed.get() || !queue.isEmpty();
}
/**
* Returns the next chunk.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the next chunk
* @throws InterruptedException if the thread is interrupted
*/
public BytesSupplier next(long timeout, TimeUnit unit) throws InterruptedException {
BytesSupplier data = queue.poll(timeout, unit);
if (data == null) {
throw new IllegalStateException("Read chunk timeout.");
}
return data;
}
/**
* Returns the next chunk.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the next chunk
* @throws InterruptedException if the thread is interrupted
*/
public byte[] nextChunk(long timeout, TimeUnit unit) throws InterruptedException {
return next(timeout, unit).getAsBytes();
}
/**
* Retrieves and removes the head of chunk or returns {@code null} if data is not available.
*
* @return the head of chunk or returns {@code null} if data is not available
*/
public BytesSupplier poll() {
return queue.poll();
}
/**
* Retrieves and removes the head of chunk or returns {@code null} if data is not available.
*
* @return the head of chunk or returns {@code null} if data is not available
*/
public byte[] pollChunk() {
BytesSupplier data = poll();
return data == null ? null : data.getAsBytes();
}
/** {@inheritDoc} */
@Override
public byte[] getAsBytes() {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
while (hasNext()) {
bos.write(nextChunk(1, TimeUnit.MINUTES));
}
return bos.toByteArray();
} catch (IOException | InterruptedException e) {
throw new AssertionError("Failed to read BytesSupplier", e);
}
}
/** {@inheritDoc} */
@Override
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(getAsBytes());
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/IteratorBytesSupplier.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference.streaming;
import ai.djl.ndarray.BytesSupplier;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Iterator;
/**
* An {@link IteratorBytesSupplier} is a streaming {@link BytesSupplier} suitable for synchronous
* usage.
*/
public class IteratorBytesSupplier implements BytesSupplier, Iterator<byte[]> {
private Iterator<BytesSupplier> sources;
/**
* Constructs an {@link IteratorBytesSupplier}.
*
* @param sources the source suppliers
*/
public IteratorBytesSupplier(Iterator<BytesSupplier> sources) {
this.sources = sources;
}
/** {@inheritDoc} */
@Override
public boolean hasNext() {
return sources.hasNext();
}
/** {@inheritDoc} */
@Override
public byte[] next() {
return sources.next().getAsBytes();
}
/** {@inheritDoc} */
@Override
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(getAsBytes());
}
/** {@inheritDoc} */
@Override
public byte[] getAsBytes() {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
while (hasNext()) {
bos.write(next());
}
return bos.toByteArray();
} catch (IOException e) {
throw new AssertionError("Failed to read BytesSupplier", e);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/PublisherBytesSupplier.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference.streaming;
import ai.djl.ndarray.BytesSupplier;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* An {@link PublisherBytesSupplier} is a streaming {@link BytesSupplier} suitable for reactive
* asynchronous usage.
*/
public class PublisherBytesSupplier implements BytesSupplier {
private Consumer<byte[]> subscriber;
private CountDownLatch latch;
private CompletableFuture<Void> future;
/** Constructs a {@link PublisherBytesSupplier}. */
public PublisherBytesSupplier() {
latch = new CountDownLatch(1);
future = new CompletableFuture<>();
}
/**
* Appends content to the {@code BytesSupplier}.
*
* @param data bytes to append
* @param lastChunk true if this is the last chunk
*/
public void appendContent(byte[] data, boolean lastChunk) {
if (subscriber == null) {
try {
if (!latch.await(2, TimeUnit.MINUTES)) {
throw new IllegalStateException("Wait for subscriber timeout.");
}
if (subscriber == null) {
// workaround Spotbugs
throw new IllegalStateException("subscriber is not set.");
}
} catch (InterruptedException e) {
throw new IllegalStateException("Append content interrupted.", e);
}
}
subscriber.accept(data);
if (lastChunk) {
subscriber.accept(null);
future.complete(null);
}
}
/**
* Adds the subscriber to the {@link BytesSupplier} to get notified about additional data.
*
* @param subscriber a consumer function that will receive bytes when new daata is added and
* null when completed
* @return a {@code CompletableFuture} object
*/
public CompletableFuture<Void> subscribe(Consumer<byte[]> subscriber) {
if (this.subscriber != null) {
throw new IllegalStateException(
"The PublisherBytesSupplier only allows a single Subscriber");
}
this.subscriber = subscriber;
latch.countDown();
return future;
}
/** {@inheritDoc} */
@Override
public ByteBuffer toByteBuffer() {
throw new UnsupportedOperationException("Not supported.");
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/StreamingBlock.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference.streaming;
import ai.djl.ndarray.NDList;
import ai.djl.nn.Block;
import ai.djl.training.ParameterStore;
import ai.djl.util.PairList;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* A {@link Block} possessing the additional streaming forward capabilities used by {@link
* ai.djl.inference.Predictor#streamingPredict(Object)}.
*/
public interface StreamingBlock extends Block {
/**
* Applies the operating function of the block once, but returns the result in chunks. This
* method should only be called on blocks that are initialized.
*
* @param parameterStore the parameter store
* @param inputs the input NDList
* @param training true for a training forward pass (turn on dropout and layerNorm)
* @return the output of the forward pass
*/
default Stream<NDList> forwardStream(
ParameterStore parameterStore, NDList inputs, boolean training) {
return forwardStream(parameterStore, inputs, training, null);
}
/**
* Applies the operating function of the block once, but returns the result in chunks. This
* method should only be called on blocks that are initialized.
*
* @param parameterStore the parameter store
* @param inputs the input NDList
* @param training true for a training forward pass (turn on dropout and layerNorm)
* @param params optional parameters
* @return the output of the forward pass
*/
default Stream<NDList> forwardStream(
ParameterStore parameterStore,
NDList inputs,
boolean training,
PairList<String, Object> params) {
Iterator<NDList> itr = forwardStreamIter(parameterStore, inputs, training, params);
Spliterator<NDList> spitr = Spliterators.spliteratorUnknownSize(itr, Spliterator.NONNULL);
return StreamSupport.stream(spitr, false);
}
/**
* Applies the operating function of the block once, but returns the result in chunks. This
* method should only be called on blocks that are initialized.
*
* @param parameterStore the parameter store
* @param inputs the input NDList
* @param training true for a training forward pass (turn on dropout and layerNorm)
* @param params optional parameters
* @return the output of the forward pass
*/
Iterator<NDList> forwardStreamIter(
ParameterStore parameterStore,
NDList inputs,
boolean training,
PairList<String, Object> params);
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/StreamingTranslator.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.inference.streaming;
import ai.djl.ndarray.NDList;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import java.util.stream.Stream;
/**
* An expansion of the {@link Translator} with postProcessing for the {@link StreamingBlock} (used
* by {@link ai.djl.inference.Predictor#streamingPredict(Object)}.
*
* @param <I> the input type
* @param <O> the output type
*/
public interface StreamingTranslator<I, O> extends Translator<I, O> {
/**
* Processes the output NDList to the corresponding output object.
*
* @param ctx the toolkit used for post-processing
* @param list the output NDList after inference, usually immutable in engines like
* PyTorch. @see <a href="https://github.com/deepjavalibrary/djl/issues/1774">Issue 1774</a>
* @return the output object of expected type
* @throws Exception if an error occurs during processing output
*/
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
StreamOutput<O> processStreamOutput(TranslatorContext ctx, Stream<NDList> list)
throws Exception;
/**
* Returns what kind of {@link StreamOutput} this {@link StreamingTranslator} supports.
*
* @return what kind of {@link StreamOutput} this {@link StreamingTranslator} supports
*/
Support getSupport();
/**
* Returns whether the {@link StreamingTranslator} supports iterative output.
*
* @return whether the {@link StreamingTranslator} supports iterative output
* @see StreamOutput#getIterativeOutput()
*/
default boolean supportsIterative() {
return getSupport().iterative();
}
/**
* Returns whether the {@link StreamingTranslator} supports iterative output.
*
* @return whether the {@link StreamingTranslator} supports iterative output
* @see StreamOutput#getAsyncOutput()
*/
default boolean supportsAsync() {
return getSupport().async();
}
/**
* A {@link StreamOutput} represents a streamable output type (either iterative or
* asynchronous).
*
* <p>There are two modes for the {@link StreamOutput}. When using it, you must choose one of
* the modes and can only access it once. Any other usage including trying both modes or trying
* one mode twice will result in an {@link IllegalStateException}.
*
* <p>The first mode is the iterative mode which can be used by calling {@link
* #getIterativeOutput()}, it returns a result that has an internal iterate method. When calling
* the iterating method, it will compute an additional part of the output.
*
* <p>The second mode is asynchronous mode. Here, you can produce a mutable output object by
* calling {@link #getAsyncOutput()}. Then, calling {@link #computeAsyncOutput()} will
* synchronously compute the results and deposit them into the prepared output. This method
* works best with manual threading where the worker can return the template result to another
* thread and then continue to compute it.
*
* @param <O> the output type
*/
abstract class StreamOutput<O> {
private O output;
private boolean computed;
/**
* Returns a template object to be used with the async output.
*
* <p>This should only be an empty data structure until {@link #computeAsyncOutput()} is
* called.
*
* @return a template object to be used with the async output
*/
public final O getAsyncOutput() {
if (output != null) {
throw new IllegalStateException("The StreamOutput can only be gotten once");
}
if (computed) {
throw new IllegalStateException(
"Attempted to getAsyncOutput, but has already called getIterativeOutput."
+ " Only one kind of output can be used.");
}
output = buildAsyncOutput();
return output;
}
/**
* Performs the internal implementation of {@link #getAsyncOutput()}.
*
* @return the output for {@link #getAsyncOutput()}.
*/
protected abstract O buildAsyncOutput();
/**
* Computes the actual value and stores it in the object returned earlier by {@link
* #getAsyncOutput()}.
*/
public final void computeAsyncOutput() {
if (output == null) {
throw new IllegalStateException(
"Before calling computeAsyncOutput, you must first getAsyncOutput");
}
if (computed) {
throw new IllegalStateException("Attempted to computeAsyncOutput multiple times.");
}
computed = true;
computeAsyncOutputInternal(output);
}
/**
* Performs the internal implementation of {@link #computeAsyncOutput()}.
*
* @param output the output object returned by the earlier call to {@link
* #getAsyncOutput()}.
*/
protected abstract void computeAsyncOutputInternal(O output);
/**
* Returns an iterative streamable output.
*
* @return an iterative streamable output
*/
public final O getIterativeOutput() {
if (output != null) {
throw new IllegalStateException(
"Can't call getIterativeOutput after already using getAsyncOutput.");
}
if (computed) {
throw new IllegalStateException(
"Attempted to getIterativeOutput multiple times. getIterativeOutput can"
+ " only be called once");
}
return getIterativeOutputInternal();
}
/**
* Performs the internal implementation of {@link #getIterativeOutput()}.
*
* @return the output for {@link #getIterativeOutput()}
*/
public abstract O getIterativeOutputInternal();
}
/** What types of {@link StreamOutput}s are supported by a {@link StreamingTranslator}. */
enum Support {
/** Supports {@link #iterative()} but not {@link #async()}. */
ITERATIVE(true, false),
/** Supports {@link #async()} but not {@link #iterative()}. */
ASYNC(false, true),
/** Supports both {@link #iterative()} and {@link #async()}. */
BOTH(true, true);
private boolean iterative;
private boolean async;
Support(boolean iterative, boolean async) {
this.iterative = iterative;
this.async = async;
}
/**
* Returns whether the {@link StreamingTranslator} supports iterative output.
*
* @return whether the {@link StreamingTranslator} supports iterative output
* @see StreamOutput#getIterativeOutput()
*/
public boolean iterative() {
return iterative;
}
/**
* Returns whether the {@link StreamingTranslator} supports iterative output.
*
* @return whether the {@link StreamingTranslator} supports iterative output
* @see StreamOutput#getAsyncOutput()
*/
public boolean async() {
return async;
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference
|
java-sources/ai/djl/api/0.34.0/ai/djl/inference/streaming/package-info.java
|
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* Contains classes to implement streaming inference tasks.
*
* @see ai.djl.inference.Predictor
*/
package ai.djl.inference.streaming;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/Dimension.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.metric;
import com.google.gson.annotations.SerializedName;
/** A class represents a metric dimension. */
public class Dimension {
@SerializedName("Name")
private String name;
@SerializedName("Value")
private String value;
/** Constructs a new {@code Dimension} instance. */
public Dimension() {}
/**
* Constructs a new {@code Dimension} instance.
*
* @param name the dimension name
* @param value the dimension value
*/
public Dimension(String name, String value) {
this.name = name;
this.value = value;
}
/**
* Returns the dimension name.
*
* @return the dimension name
*/
public String getName() {
return name;
}
/**
* Returns the dimension value.
*
* @return the dimension value
*/
public String getValue() {
return value;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/Metric.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.metric;
import com.google.gson.annotations.SerializedName;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A class representing a single recorded {@code Metric} value.
*
* @see Metrics
*/
public class Metric {
private static final Pattern PATTERN =
Pattern.compile(
"\\s*([\\w\\s]+)\\.([\\w\\s]+):([0-9\\-,.e]+)(?>\\|#([^|]*))?(?>\\|(\\d+))?(?>\\|([cgh]))?");
private static final Dimension[] HOST = {new Dimension("Host", getLocalHostName())};
@SerializedName("MetricName")
private String metricName;
private transient MetricType metricType;
@SerializedName("Value")
private String value;
@SerializedName("Unit")
private String unit;
@SerializedName("Dimensions")
private Dimension[] dimensions;
@SerializedName("Timestamp")
private String timestamp;
/**
* Constructs a {@code Metric} instance with the specified {@code metricName} and <code>
* value</code>.
*
* @param metricName the metric name
* @param value the metric value
*/
public Metric(String metricName, Number value) {
this(metricName, value, Unit.COUNT);
}
/**
* Constructs a {@code Metric} instance with the specified {@code metricName}, <code>value
* </code>, and {@code unit}.
*
* @param metricName the metric name
* @param value the metric value
* @param unit the metric unit
* @param dimensions the metric dimensions
*/
public Metric(String metricName, Number value, Unit unit, Dimension... dimensions) {
this(metricName, null, value, unit, dimensions);
}
/**
* Constructs a {@code Metric} instance with the specified {@code metricName}, <code>value
* </code>, and {@code unit}.
*
* @param metricName the metric name
* @param metricType the {@link MetricType}
* @param value the metric value
* @param unit the metric unit
* @param dimensions the metric dimensions
*/
public Metric(
String metricName,
MetricType metricType,
Number value,
Unit unit,
Dimension... dimensions) {
this(metricName, metricType, value.toString(), unit.getValue(), null, dimensions);
}
/**
* Constructs a new {@code Metric} instance.
*
* @param metricName the metric name
* @param metricType the {@link MetricType}
* @param value the metric value
* @param unit the metric unit
* @param timestamp the metric timestamp
* @param dimensions the metric dimensions
*/
private Metric(
String metricName,
MetricType metricType,
String value,
String unit,
String timestamp,
Dimension... dimensions) {
this.metricName = metricName;
this.metricType = metricType;
this.unit = unit;
this.value = value;
this.timestamp = timestamp;
this.dimensions = dimensions.length == 0 ? HOST : dimensions;
}
/**
* Returns a copy of the metric with a new name.
*
* @param name the new metric name
* @return a copy of the metric
*/
public Metric copyOf(String name) {
return new Metric(name, metricType, value, unit, timestamp, dimensions);
}
/**
* Returns the name of the {@code Metric}.
*
* @return the metric name
*/
public String getMetricName() {
return metricName;
}
/**
* Returns the type of the {@code Metric}.
*
* @return the metric type
*/
public MetricType getMetricType() {
return metricType;
}
/**
* Returns the int value of the {@code Metric}.
*
* @return the metric value in int
*/
public Double getValue() {
return Double.valueOf(value);
}
/**
* Returns the unit of the {@code Metric}.
*
* @return the metric unit
*/
public Unit getUnit() {
return Unit.fromValue(unit);
}
/**
* Returns the timestamp of the {@code Metric}.
*
* @return the metric timestamp
*/
public String getTimestamp() {
return timestamp;
}
/**
* Returns the metric dimensions.
*
* @return the metric dimensions
*/
public Dimension[] getDimensions() {
return dimensions;
}
/**
* Returns a {@code Metric} instance parsed from the log string.
*
* @param line the input string
* @return a {@code Metric} object
*/
public static Metric parse(String line) {
// DiskAvailable.Gigabytes:311|#Host:localhost|1650953744320|c
Matcher matcher = PATTERN.matcher(line);
if (!matcher.matches()) {
return null;
}
String metricName = matcher.group(1);
String unit = matcher.group(2);
String value = matcher.group(3);
String dimension = matcher.group(4);
String timestamp = matcher.group(5);
String type = matcher.group(6);
MetricType metricType = type == null ? null : MetricType.of(type);
Dimension[] dimensions;
if (dimension != null) {
String[] dims = dimension.split(",");
dimensions = new Dimension[dims.length];
int index = 0;
for (String dim : dims) {
String[] pair = dim.split(":");
if (pair.length == 2) {
dimensions[index++] = new Dimension(pair[0], pair[1]);
}
}
} else {
dimensions = HOST;
}
return new Metric(metricName, metricType, value, unit, timestamp, dimensions);
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
sb.append(metricName).append('.').append(unit).append(':').append(value);
if (dimensions != null) {
boolean first = true;
for (Dimension dimension : dimensions) {
if (dimension == null) {
continue;
}
if (first) {
sb.append("|#");
first = false;
} else {
sb.append(',');
}
sb.append(dimension.getName()).append(':').append(dimension.getValue());
}
}
if (timestamp != null) {
sb.append('|').append(timestamp);
}
if (metricType != null) {
sb.append('|').append(metricType.getValue());
}
return sb.toString();
}
private static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "Unknown";
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/MetricType.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.metric;
/** An enum holds metric type constants. */
public enum MetricType {
COUNTER("c"),
GAUGE("g"),
HISTOGRAM("h");
private final String value;
MetricType(String value) {
this.value = value;
}
/**
* Returns the string value of the {@code MetricType}.
*
* @return the string value of the {@code MetricType}
*/
public String getValue() {
return value;
}
/**
* Returns {@code Unit} instance from an string value.
*
* @param value the String value of Unit
* @return the {@code Unit}
*/
public static MetricType of(String value) {
if ("c".equals(value)) {
return COUNTER;
} else if ("g".equals(value)) {
return GAUGE;
} else if ("h".equals(value)) {
return HISTOGRAM;
}
throw new IllegalArgumentException("Invalid MetricType value: " + value);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/Metrics.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.metric;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* A collection of {@link Metric} objects organized by metric name.
*
* <p>{@code Metric} is a utility class that is used in the {@link ai.djl.training.Trainer} and
* {@link ai.djl.inference.Predictor} to capture performance and other metrics during runtime.
*
* <p>It is built as a collection of individual {@link Metric} classes. As a container for
* individual metrics classes, {@code Metrics} stores them as time series data so that
* metric-vs-timeline analysis can be performed. It also provides convenient statistical methods for
* getting aggregated information, such as mean and percentile. The metrics is used to store key
* performance indicators (KPIs) during inference and training runs. These KPIs include various
* latencies, CPU and GPU memory consumption, losses, etc.
*
* <p>For more details about using the metrics, see the <a
* href="https://github.com/deepjavalibrary/djl/blob/master/docs/how_to_collect_metrics.md">metrics
* tutorial</a>.
*/
public class Metrics {
private Map<String, List<Metric>> metrics;
private int limit;
private BiConsumer<Metrics, String> onLimit;
/** Constructs an empty {@code Metrics} instance. */
public Metrics() {
metrics = new ConcurrentHashMap<>();
}
/**
* Sets the max size for each metric.
*
* @param limit the max size for each metric
*/
public void setLimit(int limit) {
this.limit = limit;
}
/**
* Sets the callback function when hit the limit.
*
* @param onLimit the callback function
*/
public void setOnLimit(BiConsumer<Metrics, String> onLimit) {
this.onLimit = onLimit;
}
/**
* Adds a {@link Metric} to the collection.
*
* @param metric the {@link Metric} to be added
*/
public void addMetric(Metric metric) {
List<Metric> list =
metrics.computeIfAbsent(
metric.getMetricName(),
v -> Collections.synchronizedList(new ArrayList<>()));
if (limit > 0 && list.size() >= limit) {
if (onLimit != null) {
onLimit.accept(this, metric.getMetricName());
}
list.clear();
}
list.add(metric);
}
/**
* Adds a {@code Metric} given the metric's {@code name} and {@code value}.
*
* @param name the metric name
* @param value the metric value
*/
public void addMetric(String name, Number value) {
addMetric(new Metric(name, value));
}
/**
* Adds a {@code Metric} given the metric's {@code name}, {@code value}, and {@code unit}.
*
* @param name the metric name
* @param value the metric value
* @param unit the metric unit
* @param dimensions the metric dimensions
*/
public void addMetric(String name, Number value, Unit unit, Dimension... dimensions) {
addMetric(new Metric(name, value, unit, dimensions));
}
/**
* Returns {@code true} if the metrics object has a metric with the given name.
*
* @param name the name to check for
* @return {@code true} if the metrics object has a metric with the given name
*/
public boolean hasMetric(String name) {
return metrics.containsKey(name);
}
/**
* Returns all {@link Metric}s with the specified metric name.
*
* @param name the name of the metric
* @return a list of {@link Metric} with the specified metric name
*/
public List<Metric> getMetric(String name) {
List<Metric> list = metrics.get(name);
if (list == null) {
return Collections.emptyList();
}
return list;
}
/**
* Returns a set of {@link String} metric names.
*
* @return a set of {@link String} metric names
*/
public Set<String> getMetricNames() {
return metrics.keySet();
}
/**
* Returns the latest {@link Metric} with the specified metric name.
*
* @param name the name of the metric
* @return the {@link Metric} with the specified metric name
* @throws IllegalArgumentException if the given name is not found
*/
public Metric latestMetric(String name) {
List<Metric> list = metrics.get(name);
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException("Could not find metric: " + name);
}
return list.get(list.size() - 1);
}
/**
* Returns a percentile {@link Metric} object for the specified metric name.
*
* @param metricName the name of the metric
* @param percentile the percentile
* @return the {@link Metric} object at specified {@code percentile}
*/
public Metric percentile(String metricName, int percentile) {
List<Metric> metric = metrics.get(metricName);
if (metric == null || metrics.isEmpty()) {
throw new IllegalArgumentException("Metric name not found: " + metricName);
}
List<Metric> list = new ArrayList<>(metric);
list.sort(Comparator.comparingDouble(Metric::getValue));
int index = metric.size() * percentile / 100;
Metric m = list.get(index);
return m.copyOf(m.getMetricName() + "_p" + percentile);
}
/**
* Returns the average value of the specified metric.
*
* @param metricName the name of the metric
* @return the average value of the specified metric
*/
public double mean(String metricName) {
List<Metric> metric = metrics.get(metricName);
if (metric == null || metrics.isEmpty()) {
throw new IllegalArgumentException("Metric name not found: " + metricName);
}
return metric.stream().collect(Collectors.averagingDouble(Metric::getValue));
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/Unit.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.metric;
import java.util.concurrent.ConcurrentHashMap;
/** An interface holds metric unit constants. */
public enum Unit {
MICROSECONDS("Microseconds"),
MILLISECONDS("Milliseconds"),
BYTES("Bytes"),
KILOBYTES("Kilobytes"),
MEGABYTES("Megabytes"),
GIGABYTES("Gigabytes"),
TERABYTES("Terabytes"),
BITS("Bits"),
KILOBITS("Kilobits"),
MEGABITS("Megabits"),
GIGABITS("Gigabits"),
TERABITS("Terabits"),
PERCENT("Percent"),
COUNT("Count"),
BYTES_PER_SECOND("Bytes/Second"),
KILOBYTES_PER_SECOND("Kilobytes/Second"),
MEGABYTES_PER_SECOND("Megabytes/Second"),
GIGABYTES_PER_SECOND("Gigabytes/Second"),
TERABYTES_PER_SECOND("Terabytes/Second"),
BITS_PER_SECOND("Bits/Second"),
KILOBITS_PER_SECOND("Kilobits/Second"),
MEGABITS_PER_SECOND("Megabits/Second"),
GIGABITS_PER_SECOND("Gigabits/Second"),
TERABITS_PER_SECOND("Terabits/Second"),
COUNT_PER_SECOND("Count/Second"),
COUNT_PER_ITEM("Count/Item"),
NONE("None");
private static final ConcurrentHashMap<String, Unit> MAP = new ConcurrentHashMap<>();
static {
for (Unit unit : values()) {
MAP.put(unit.value, unit);
}
}
private final String value;
Unit(String value) {
this.value = value;
}
/**
* Returns the string value of the {@code Unit}.
*
* @return the string value of the {@code Unit}
*/
public String getValue() {
return value;
}
/**
* Returns {@code Unit} instance from an string value.
*
* @param value the String value of Unit
* @return the {@code Unit}
*/
public static Unit fromValue(String value) {
Unit ret = MAP.get(value);
if (ret == null) {
throw new IllegalArgumentException("Invalid unit value: " + value);
}
return ret;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/metric/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* Contains classes to collect metrics information.
*
* @see ai.djl.metric.Metric
* @see ai.djl.metric.Metrics
*/
package ai.djl.metric;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/Classifications.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.types.DataType;
import ai.djl.translate.Ensembleable;
import ai.djl.util.JsonSerializable;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* {@code Classifications} is the container that stores the classification results for
* classification on a single input.
*/
public class Classifications implements JsonSerializable, Ensembleable<Classifications> {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
protected List<String> classNames;
@SuppressWarnings("serial")
protected List<Double> probabilities;
protected int topK;
/**
* Constructs a {@code Classifications} using a parallel list of classNames and probabilities.
*
* @param classNames the names of the classes
* @param probabilities the probabilities for each class for the input
*/
public Classifications(List<String> classNames, List<Double> probabilities) {
this.classNames = classNames;
this.probabilities = probabilities;
this.topK = 5;
}
/**
* Constructs a {@code Classifications} using list of classNames parallel to an NDArray of
* probabilities.
*
* @param classNames the names of the classes
* @param probabilities the probabilities for each class for the input
*/
public Classifications(List<String> classNames, NDArray probabilities) {
this(classNames, probabilities, 5);
}
/**
* Constructs a {@code Classifications} using list of classNames parallel to an NDArray of
* probabilities.
*
* @param classNames the names of the classes
* @param probabilities the probabilities for each class for the input
* @param topK the number of top classes to return
*/
public Classifications(List<String> classNames, NDArray probabilities, int topK) {
this.classNames = classNames;
if (probabilities.getDataType() == DataType.FLOAT32) {
// Avoid converting float32 to float64 as this is not supported on MPS device
this.probabilities = new ArrayList<>();
for (float prob : probabilities.toFloatArray()) {
this.probabilities.add((double) prob);
}
} else {
NDArray array = probabilities.toType(DataType.FLOAT64, false);
this.probabilities =
Arrays.stream(array.toDoubleArray()).boxed().collect(Collectors.toList());
array.close();
}
this.topK = topK;
}
/**
* Returns the classes that were classified into.
*
* @return the classes that were classified into
*/
public List<String> getClassNames() {
return classNames;
}
/**
* Returns the list of probabilities for each class (matching the order of the class names).
*
* @return the list of probabilities for each class (matching the order of the class names)
*/
public List<Double> getProbabilities() {
return probabilities;
}
/**
* Set the topK number of classes to be displayed.
*
* @param topK the number of top classes to return
*/
public final void setTopK(int topK) {
this.topK = topK;
}
/**
* Returns a classification item for each potential class for the input.
*
* @param <T> the type of classification item for the task
* @return the list of classification items
*/
public <T extends Classification> List<T> items() {
List<T> list = new ArrayList<>(classNames.size());
for (int i = 0; i < classNames.size(); i++) {
list.add(item(i));
}
return list;
}
/**
* Returns the item at a given index based on the order used to construct the {@link
* Classifications}.
*
* @param index the index of the item to return
* @param <T> the type of classification item for the task
* @return the item at the given index, equivalent to {@code classifications.items().get(index)}
*/
@SuppressWarnings("unchecked")
public <T extends Classification> T item(int index) {
return (T) new Classification(classNames.get(index), probabilities.get(index));
}
/**
* Returns a list of the top classes.
*
* @param <T> the type of the classification item for the task
* @return the list of classification items for the best classes in order of best to worst
*/
public <T extends Classification> List<T> topK() {
return topK(topK);
}
/**
* Returns a list of the top {@code k} best classes.
*
* @param k the number of classes to return
* @param <T> the type of the classification item for the task
* @return the list of classification items for the best classes in order of best to worst
*/
public <T extends Classification> List<T> topK(int k) {
List<T> items = items();
items.sort(Comparator.comparingDouble(Classification::getProbability).reversed());
int count = Math.min(items.size(), k);
return items.subList(0, count);
}
/**
* Returns the most likely class for the classification.
*
* @param <T> the type of the classification item for the task
* @return the classification item
*/
public <T extends Classification> T best() {
return item(probabilities.indexOf(Collections.max(probabilities)));
}
/**
* Returns the result for a particular class name.
*
* @param className the class name to get results for
* @param <T> the type of the classification item for the task
* @return the (first if multiple) classification item
*/
public <T extends Classification> T get(String className) {
int size = classNames.size();
for (int i = 0; i < size; i++) {
if (classNames.get(i).equals(className)) {
return item(i);
}
}
return null;
}
/** {@inheritDoc} */
@Override
public JsonElement serialize() {
return JsonUtils.GSON.toJsonTree(topK());
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
List<Classification> list = topK();
int index = 0;
for (Classification item : list) {
sb.append('\t').append(item);
if (++index < list.size()) {
sb.append(',');
}
sb.append('\n');
}
sb.append("]\n");
return sb.toString();
}
/** {@inheritDoc} */
@Override
public Classifications ensembleWith(Iterator<Classifications> it) {
int size = probabilities.size();
List<Double> newProbabilities = new ArrayList<>(size);
newProbabilities.addAll(probabilities);
int count = 1;
while (it.hasNext()) {
++count;
Classifications c = it.next();
for (int i = 0; i < size; ++i) {
newProbabilities.set(i, newProbabilities.get(i) + c.probabilities.get(i));
}
if (!c.classNames.equals(classNames)) {
throw new IllegalArgumentException(
"Found a classNames mismatch during ensembling. All input Classifications"
+ " should have the same classNames, but some were different");
}
}
final int total = count;
newProbabilities.replaceAll(p -> p / total);
return new Classifications(classNames, newProbabilities);
}
/**
* A {@code Classification} stores the classification result for a single class on a single
* input.
*/
public static class Classification {
private String className;
private double probability;
/**
* Constructs a single class result for a classification.
*
* @param className the class name of the result
* @param probability the probability of the result
*/
public Classification(String className, double probability) {
this.className = className;
this.probability = probability;
}
/**
* Returns the class name.
*
* @return the class name
*/
public String getClassName() {
return className;
}
/**
* Returns the probability.
*
* <p>Probability explains how accurately the classifier identified the target class.
*
* @return the probability
*/
public double getProbability() {
return probability;
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append("{\"className\": \"").append(className).append("\", \"probability\": ");
if (probability < 0.00001) {
sb.append(String.format("%.1e", probability));
} else {
probability = (int) (probability * 100000) / 100000f;
sb.append(String.format("%.5f", probability));
}
sb.append('}');
return sb.toString();
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/Input.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality;
import ai.djl.ndarray.BytesSupplier;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.util.Pair;
import ai.djl.util.PairList;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
/** A class stores the generic input data for inference. */
public class Input {
private static final long serialVersionUID = 1L;
protected Map<String, String> properties;
protected PairList<String, BytesSupplier> content;
private boolean cancelled;
/** Constructs a new {@code Input} instance. */
public Input() {
properties = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
content = new PairList<>();
}
/**
* Returns {@code true} if the input is cancelled.
*
* @return {@code true} if the input is cancelled.
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Sets the cancelled status.
*
* @param cancelled the cancelled status
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Returns the properties of the input.
*
* @return the properties of the input
*/
public Map<String, String> getProperties() {
return properties;
}
/**
* Sets the properties of the input.
*
* @param properties the properties of the input
*/
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
/**
* Adds a property to the input.
*
* @param key key with which the specified value is to be added
* @param value value to be added with the specified key
*/
public void addProperty(String key, String value) {
properties.put(key, value);
}
/**
* Returns the value to which the specified key is mapped.
*
* @param key the key whose associated value is to be returned
* @param defaultValue the default mapping of the key
* @return the value to which the specified key is mapped
*/
public String getProperty(String key, String defaultValue) {
return properties.getOrDefault(key, defaultValue);
}
/**
* Returns the content of the input.
*
* <p>A {@code Input} may contains multiple data.
*
* @return the content of the input
*/
public PairList<String, BytesSupplier> getContent() {
return content;
}
/**
* Returns the content of the input as {@link ByteBuffer}s.
*
* <p>A {@code Input} may contains multiple data.
*
* @return the content of the input as {@link ByteBuffer}s.
*/
public PairList<String, ByteBuffer> getContentAsBuffers() {
PairList<String, ByteBuffer> result = new PairList<>(content.size());
for (Pair<String, BytesSupplier> c : content) {
result.add(c.getKey(), c.getValue().toByteBuffer());
}
return result;
}
/**
* Sets the content of the input.
*
* @param content the content of the input
*/
public void setContent(PairList<String, BytesSupplier> content) {
this.content = content;
}
/**
* Appends an item at the end of the input.
*
* @param data data to be added
*/
public void add(byte[] data) {
add(BytesSupplier.wrap(data));
}
/**
* Appends an item at the end of the input.
*
* @param data data to be added
*/
public void add(String data) {
add(BytesSupplier.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
/**
* Appends an item at the end of the input.
*
* @param data data to be added
*/
public void add(BytesSupplier data) {
add(null, data);
}
/**
* Adds a key/value pair to the input content.
*
* @param key key with which the specified data is to be added
* @param data data to be added with the specified key
*/
public void add(String key, byte[] data) {
add(key, BytesSupplier.wrap(data));
}
/**
* Adds a key/value pair to the input content.
*
* @param key key with which the specified data is to be added
* @param data data to be added with the specified key
*/
public void add(String key, String data) {
add(key, BytesSupplier.wrap(data));
}
/**
* Adds a key/value pair to the input content.
*
* @param key key with which the specified data is to be added
* @param data data to be added with the specified key
*/
public void add(String key, BytesSupplier data) {
content.add(key, data);
}
/**
* Inserts the specified element at the specified position in the input.
*
* @param index the index at which the specified element is to be inserted
* @param key key with which the specified data is to be added
* @param data data to be added with the specified key
*/
public void add(int index, String key, BytesSupplier data) {
content.add(index, key, data);
}
/**
* Returns the default data item.
*
* @return the default data item
*/
public BytesSupplier getData() {
if (content.isEmpty()) {
return null;
}
BytesSupplier data = get("data");
if (data == null) {
return get(0);
}
return data;
}
/**
* Returns the default data as {@code NDList}.
*
* @param manager {@link NDManager} used to create this {@code NDArray}
* @return the default data as {@code NDList}
*/
public NDList getDataAsNDList(NDManager manager) {
if (content.isEmpty()) {
return null; // NOPMD
}
int index = content.indexOf("data");
if (index < 0) {
index = 0;
}
return getAsNDList(manager, index);
}
/**
* Returns the element for the first key found in the {@code Input}.
*
* @param key the key of the element to get
* @return the element for the first key found in the {@code Input}
*/
public BytesSupplier get(String key) {
return content.get(key);
}
/**
* Returns the element at the specified position in the {@code Input}.
*
* @param index the index of the element to return
* @return the element at the specified position in the {@code Input}
*/
public BytesSupplier get(int index) {
return content.valueAt(index);
}
/**
* Returns the value as {@code byte[]} for the first key found in the {@code Input}.
*
* @param key the key of the element to get
* @return the value as {@code byte[]} for the first key found in the {@code Input}
*/
public byte[] getAsBytes(String key) {
BytesSupplier data = content.get(key);
if (data == null) {
return null; // NOPMD
}
return data.getAsBytes();
}
/**
* Returns the value as {@code byte[]} at the specified position in the {@code Input}.
*
* @param index the index of the element to return
* @return the value as {@code byte[]} at the specified position in the {@code Input}
*/
public byte[] getAsBytes(int index) {
return content.valueAt(index).getAsBytes();
}
/**
* Returns the value as {@code byte[]} for the first key found in the {@code Input}.
*
* @param key the key of the element to get
* @return the value as {@code byte[]} for the first key found in the {@code Input}
*/
public String getAsString(String key) {
BytesSupplier data = content.get(key);
if (data == null) {
return null;
}
return data.getAsString();
}
/**
* Returns the value as {@code byte[]} at the specified position in the {@code Input}.
*
* @param index the index of the element to return
* @return the value as {@code byte[]} at the specified position in the {@code Input}
*/
public String getAsString(int index) {
return content.valueAt(index).getAsString();
}
/**
* Returns the value as {@code NDArray} for the first key found in the {@code Input}.
*
* @param manager {@link NDManager} used to create this {@code NDArray}
* @param key the key of the element to get
* @return the value as {@code NDArray} for the first key found in the {@code Input}
*/
public NDArray getAsNDArray(NDManager manager, String key) {
int index = content.indexOf(key);
if (index < 0) {
return null;
}
return getAsNDArray(manager, index);
}
/**
* Returns the value as {@code NDArray} at the specified position in the {@code Input}.
*
* @param manager {@link NDManager} used to create this {@code NDArray}
* @param index the index of the element to return
* @return the value as {@code NDArray} at the specified position in the {@code Input}
*/
public NDArray getAsNDArray(NDManager manager, int index) {
BytesSupplier data = content.valueAt(index);
if (data instanceof NDArray) {
return (NDArray) data;
}
return NDArray.decode(manager, data.getAsBytes());
}
/**
* Returns the value as {@code NDList} for the first key found in the {@code Input}.
*
* @param manager {@link NDManager} used to create this {@code NDArray}
* @param key the key of the element to get
* @return the value as {@code NDList} for the first key found in the {@code Input}
*/
public NDList getAsNDList(NDManager manager, String key) {
int index = content.indexOf(key);
if (index < 0) {
return null; // NOPMD
}
return getAsNDList(manager, index);
}
/**
* Returns the value as {@code NDList} at the specified position in the {@code Input}.
*
* @param manager {@link NDManager} used to create this {@code NDArray}
* @param index the index of the element to return
* @return the value as {@code NDList} at the specified position in the {@code Input}
*/
public NDList getAsNDList(NDManager manager, int index) {
BytesSupplier data = content.valueAt(index);
if (data instanceof NDList) {
return (NDList) data;
} else if (data instanceof NDArray) {
return new NDList((NDArray) data);
}
return NDList.decode(manager, data.getAsBytes());
}
/**
* Encodes all data in the input to a binary form.
*
* @return the binary encoding
* @throws IOException if it fails to encode part of the data
*/
public byte[] encode() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
DataOutputStream os = new DataOutputStream(baos);
os.writeLong(serialVersionUID);
encodeInputBase(os);
return baos.toByteArray();
}
}
protected void encodeInputBase(DataOutputStream os) throws IOException {
os.writeInt(properties.size());
for (Entry<String, String> property : properties.entrySet()) {
os.writeUTF(property.getKey());
os.writeUTF(property.getValue());
}
os.writeInt(content.size());
for (Pair<String, BytesSupplier> c : content) {
if (c.getKey() != null) {
os.writeBoolean(true);
os.writeUTF(c.getKey());
} else {
os.writeBoolean(false);
}
byte[] cVal = c.getValue().getAsBytes();
os.writeInt(cVal.length);
os.write(cVal);
}
}
/**
* Decodes the input from {@link #encode()}.
*
* @param is the data to decode from
* @return the decoded input
* @throws IOException if it fails to decode part of the input
*/
public static Input decode(InputStream is) throws IOException {
try (DataInputStream dis = new DataInputStream(is)) {
if (serialVersionUID != dis.readLong()) {
throw new IllegalArgumentException("Invalid Input version");
}
Input input = new Input();
decodeInputBase(dis, input);
return input;
}
}
protected static void decodeInputBase(DataInputStream dis, Input input) throws IOException {
int numProperties = dis.readInt();
for (int i = 0; i < numProperties; i++) {
String key = dis.readUTF();
String val = dis.readUTF();
input.addProperty(key, val);
}
int numContent = dis.readInt();
for (int i = 0; i < numContent; i++) {
boolean hasKey = dis.readBoolean();
String key = null;
if (hasKey) {
key = dis.readUTF();
}
int contentLength = dis.readInt();
byte[] contents = new byte[contentLength];
int contentRead = 0;
while (contentRead < contentLength) {
int newRead = dis.read(contents, contentRead, contentLength);
if (newRead < 0) {
throw new IOException("Failed to read Input or Output content");
}
contentRead += newRead;
}
input.add(key, contents);
}
}
/**
* Checks for deep equality with another input.
*
* @param o the other input.
* @return whether they and all properties, content, and data are equal
*/
public boolean deepEquals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Input input = (Input) o;
return properties.equals(input.properties)
&& getContentAsBuffers().equals(input.getContentAsBuffers());
}
/** {@inheritDoc} * */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(1000);
sb.append("Input:\n");
for (Entry<String, String> property : properties.entrySet()) {
sb.append("Property ")
.append(property.getKey())
.append(": ")
.append(property.getValue())
.append('\n');
}
for (Pair<String, BytesSupplier> c : content) {
sb.append("Content ")
.append(c.getKey())
.append(": ")
.append(c.getValue().toString())
.append('\n');
}
sb.append('\n');
return sb.toString();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/Output.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
/** A class stores the generic inference results. */
public class Output extends Input {
private static final long serialVersionUID = 1L;
private int code;
private String message;
/** Constructs a {@code Output} instance. */
public Output() {
this(200, "OK");
}
/**
* Constructs a {@code Output} with specified {@code requestId}, {@code code} and {@code
* message}.
*
* @param code the status code of the output
* @param message the status message of the output
*/
public Output(int code, String message) {
this.code = code;
this.message = message;
}
/**
* Returns the status code of the output.
*
* @return the status code of the output
*/
public int getCode() {
return code;
}
/**
* Sets the status code of the output.
*
* @param code the status code of the output
*/
public void setCode(int code) {
this.code = code;
}
/**
* Returns the status code of the output.
*
* @return the status code of the output
*/
public String getMessage() {
return message;
}
/**
* Sets the status message of the output.
*
* @param message the status message of the output
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Encodes all data in the output to a binary form.
*
* @return the binary encoding
* @throws IOException if it fails to encode part of the data
*/
@Override
public byte[] encode() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
DataOutputStream os = new DataOutputStream(baos);
os.writeLong(serialVersionUID);
encodeInputBase(os);
os.writeInt(code);
os.writeUTF(message);
return baos.toByteArray();
}
}
/**
* Decodes the output from {@link #encode()}.
*
* @param is the data to decode from
* @return the decoded output
* @throws IOException if it fails to decode part of the output
*/
public static Output decode(InputStream is) throws IOException {
try (DataInputStream dis = new DataInputStream(is)) {
if (serialVersionUID != dis.readLong()) {
throw new IllegalArgumentException("Invalid Input version");
}
Output output = new Output();
decodeInputBase(dis, output);
output.code = dis.readInt();
output.message = dis.readUTF();
return output;
}
}
/**
* Checks for deep equality with another output.
*
* @param o the other output.
* @return whether they and all properties, content, and data are equal
*/
@Override
public boolean deepEquals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.deepEquals(o)) {
return false;
}
Output output = (Output) o;
return code == output.code && Objects.equals(message, output.message);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains utility classes for each of the predefined modalities. */
package ai.djl.modality;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/Audio.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.audio;
/**
* {@code Audio} is a container of an audio in DJL. The raw data of the audio is wrapped in a float
* array.
*/
public class Audio {
private float[] data;
private float sampleRate;
private int channels;
/**
* Constructs a new {@code Audio} instance.
*
* @param data the wrapped float array data
*/
public Audio(float[] data) {
this.data = data;
}
/**
* Constructs a new {@code Audio} instance.
*
* @param data the wrapped float array data
* @param sampleRate the sample rate
* @param channels number of channels
*/
public Audio(float[] data, float sampleRate, int channels) {
this.data = data;
this.sampleRate = sampleRate;
this.channels = channels;
}
/**
* Returns the float array data.
*
* @return The float array data.
*/
public float[] getData() {
return data;
}
/**
* Returns the sample rate.
*
* @return sample rate.
*/
public float getSampleRate() {
return sampleRate;
}
/**
* Returns the number of channels of an audio file.
*
* @return the number of channels of an audio file
*/
public int getChannels() {
return channels;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/AudioFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.audio;
import ai.djl.ndarray.NDArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* {@code AudioFactory} contains audio creation mechanism on top of different platforms like PC and
* Android. System will choose appropriate Factory based on the supported audio type.
*/
public abstract class AudioFactory {
private static final Logger logger = LoggerFactory.getLogger(AudioFactory.class);
private static final String[] FACTORIES = {
"ai.djl.audio.FFmpegAudioFactory", "ai.djl.modality.audio.SampledAudioFactory"
};
protected int channels;
protected int sampleRate;
protected int sampleFormat;
/**
* Constructs a new instance of {@code AudioFactory}.
*
* @return a new instance of {@code AudioFactory}
*/
public static AudioFactory newInstance() {
for (String f : FACTORIES) {
try {
Class<? extends AudioFactory> clazz =
Class.forName(f).asSubclass(AudioFactory.class);
return clazz.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
logger.trace("", e);
}
}
throw new IllegalStateException("Failed to create AudioFactory!");
}
/**
* Returns {@link Audio} from file.
*
* @param path the path to the audio
* @return {@link Audio}
* @throws IOException Audio not found or not readable
*/
public abstract Audio fromFile(Path path) throws IOException;
/**
* Returns {@link Audio} from URL.
*
* @param url the URL to load from
* @return {@link Audio}
* @throws IOException URL is not valid.
*/
public Audio fromUrl(URL url) throws IOException {
try (InputStream is = url.openStream()) {
return fromInputStream(is);
}
}
/**
* Returns {@link Audio} from URL.
*
* @param url the String represent URL to load from
* @return {@link Audio}
* @throws IOException URL is not valid.
*/
public Audio fromUrl(String url) throws IOException {
URI uri = URI.create(url);
if (uri.isAbsolute()) {
return fromUrl(uri.toURL());
}
return fromFile(Paths.get(url));
}
/**
* Returns {@link Audio} from {@link InputStream}.
*
* @param is {@link InputStream}
* @return {@link Audio}
* @throws IOException image cannot be read from input stream.
*/
public abstract Audio fromInputStream(InputStream is) throws IOException;
/**
* Returns {@link Audio} from raw data.
*
* @param data the raw data in float array form.
* @return {@link Audio}
*/
public Audio fromData(float[] data) {
return new Audio(data);
}
/**
* Returns {@link Audio} from {@link NDArray}.
*
* @param array the NDArray with CHW format
* @return {@link Audio}
*/
public Audio fromNDArray(NDArray array) {
throw new UnsupportedOperationException("Not supported!");
}
/**
* Sets the number of channels for {@link AudioFactory} to use.
*
* @param channels the number of channels for {@link AudioFactory} to use
* @return this factory
*/
public AudioFactory setChannels(int channels) {
this.channels = channels;
return this;
}
/**
* Returns the channels of this factory.
*
* @return the channels of this factory
*/
public int getChannels() {
return channels;
}
/**
* Sets the sampleRate for {@link AudioFactory} to use.
*
* @param sampleRate the sampleRate for {@link AudioFactory} to use
* @return this factory
*/
public AudioFactory setSampleRate(int sampleRate) {
this.sampleRate = sampleRate;
return this;
}
/**
* Returns the sample rate.
*
* @return the sample rate in integer
*/
public int getSampleRate() {
return sampleRate;
}
/**
* Sets the audio sample format for {@link AudioFactory} to use.
*
* @param sampleFormat the sample format
* @return this factory.
*/
public AudioFactory setSampleFormat(int sampleFormat) {
this.sampleFormat = sampleFormat;
return this;
}
/**
* Returns the sample format name of the audio.
*
* @return the format name of the audio
*/
public int getSampleFormat() {
return sampleFormat;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/SampledAudioFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.audio;
import ai.djl.modality.cv.ImageFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.file.Path;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* {@code SampledAudioFactory} is an implementation of {@link ImageFactory} using the Java Sampled
* Package.
*
* @see <a
* href="http://google.com">https://docs.oracle.com/javase/tutorial/sound/sampled-overview.html</a>
*/
public class SampledAudioFactory extends AudioFactory {
/** {@inheritDoc} */
@Override
public AudioFactory setChannels(int channel) {
if (channel != 0) {
throw new UnsupportedOperationException("SampledAudioFactory only support 1 channel.");
}
return this;
}
/** {@inheritDoc} */
@Override
public AudioFactory setSampleRate(int sampleRate) {
throw new UnsupportedOperationException("Not supported.");
}
/** {@inheritDoc} */
@Override
public AudioFactory setSampleFormat(int sampleFormat) {
throw new UnsupportedOperationException("Not supported.");
}
/** {@inheritDoc} */
@Override
public Audio fromFile(Path path) throws IOException {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(path.toFile())) {
AudioFormat format = ais.getFormat();
byte[] bytes = read(ais);
float[] floats = bytesToFloats(bytes, format.isBigEndian());
return new Audio(floats, format.getSampleRate(), format.getChannels());
} catch (UnsupportedAudioFileException e) {
throw new IOException("Unsupported Audio file", e);
}
}
/** {@inheritDoc} */
@Override
public Audio fromInputStream(InputStream is) throws IOException {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(is))) {
AudioFormat format = ais.getFormat();
byte[] bytes = read(ais);
float[] floats = bytesToFloats(bytes, format.isBigEndian());
return new Audio(floats, format.getSampleRate(), format.getChannels());
} catch (UnsupportedAudioFileException e) {
throw new IOException("Unsupported Audio file", e);
}
}
private byte[] read(AudioInputStream ais) throws IOException {
AudioFormat format = ais.getFormat();
int frameSize = format.getFrameSize();
// Some audio formats may have unspecified frame size
if (frameSize == AudioSystem.NOT_SPECIFIED) {
frameSize = 1;
}
int size = (int) ais.getFrameLength() * frameSize;
byte[] ret = new byte[size];
byte[] buf = new byte[1024];
int offset = 0;
int read;
while ((read = ais.read(buf)) != -1) {
System.arraycopy(buf, 0, ret, offset, read);
offset += read;
}
return ret;
}
private float[] bytesToFloats(byte[] bytes, boolean isBigEndian) {
ByteOrder order = isBigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
ShortBuffer buffer = ByteBuffer.wrap(bytes).order(order).asShortBuffer();
short[] shorts = new short[buffer.capacity()];
buffer.get(shorts);
// Feed in float values between -1.0f and 1.0f.
float[] floats = new float[shorts.length];
for (int i = 0; i < shorts.length; i++) {
floats[i] = ((float) shorts[i]) / (float) Short.MAX_VALUE;
}
return floats;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/package-info.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains utility classes for audio processing. */
package ai.djl.modality.audio;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/translator/SpeechRecognitionTranslator.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.audio.translator;
import ai.djl.modality.audio.Audio;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.NoBatchifyTranslator;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
/**
* A {@link Translator} that post-process the {@link Audio} into {@link String} to get a text
* translation of the audio.
*/
public class SpeechRecognitionTranslator implements NoBatchifyTranslator<Audio, String> {
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Audio input) throws Exception {
float[] data = input.getData();
NDArray array = ctx.getNDManager().create(data, new Shape(1, data.length));
return new NDList(array);
}
/** {@inheritDoc} */
@Override
public String processOutput(TranslatorContext ctx, NDList list) throws Exception {
return list.get(0).toStringArray()[0];
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/translator/SpeechRecognitionTranslatorFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.audio.translator;
import ai.djl.Model;
import ai.djl.modality.audio.Audio;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import ai.djl.util.Pair;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** A {@link TranslatorFactory} that creates a {@link SpeechRecognitionTranslator} instance. */
public class SpeechRecognitionTranslatorFactory implements TranslatorFactory, Serializable {
private static final long serialVersionUID = 1L;
private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>();
static {
SUPPORTED_TYPES.add(new Pair<>(Audio.class, String.class));
}
/** {@inheritDoc} */
@Override
public Set<Pair<Type, Type>> getSupportedTypes() {
return SUPPORTED_TYPES;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <I, O> Translator<I, O> newInstance(
Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) {
if (input == Audio.class && output == String.class) {
return (Translator<I, O>) new SpeechRecognitionTranslator();
}
throw new IllegalArgumentException("Unsupported input/output types.");
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/audio/translator/package-info.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains utility classes for speech recognition processing. */
package ai.djl.modality.audio.translator;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/BufferedImageFactory.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Joints;
import ai.djl.modality.cv.output.Landmark;
import ai.djl.modality.cv.output.Mask;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.util.RandomUtils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;
/** {@code BufferedImageFactory} is the default implementation of {@link ImageFactory}. */
public class BufferedImageFactory extends ImageFactory {
static {
if (System.getProperty("apple.awt.UIElement") == null) {
// disables coffee cup image showing up on macOS
System.setProperty("apple.awt.UIElement", "true");
}
}
/** {@inheritDoc} */
@Override
public Image fromFile(Path path) throws IOException {
BufferedImage image = ImageIO.read(path.toFile());
if (image == null) {
throw new IOException("Failed to read image from: " + path);
}
return new BufferedImageWrapper(image);
}
/** {@inheritDoc} */
@Override
public Image fromInputStream(InputStream is) throws IOException {
BufferedImage image = ImageIO.read(is);
if (image == null) {
throw new IOException("Failed to read image from input stream");
}
return new BufferedImageWrapper(image);
}
/** {@inheritDoc} */
@Override
public Image fromImage(Object image) {
if (!(image instanceof BufferedImage)) {
throw new IllegalArgumentException("only BufferedImage allowed");
}
return new BufferedImageWrapper((BufferedImage) image);
}
/** {@inheritDoc} */
@Override
public Image fromNDArray(NDArray array) {
Shape shape = array.getShape();
if (shape.dimension() == 4) {
throw new UnsupportedOperationException("Batch is not supported");
} else if (shape.get(0) == 1 || shape.get(2) == 1) {
throw new UnsupportedOperationException("Grayscale image is not supported");
}
int[] raw = array.toType(DataType.UINT8, false).toUint8Array();
if (NDImageUtils.isCHW(shape)) {
int height = (int) shape.get(1);
int width = (int) shape.get(2);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
int imageArea = height * width;
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
int index = h * width + w;
int red = raw[index];
int green = raw[imageArea + index];
int blue = raw[imageArea * 2 + index];
pixels[index] = (red << 16) | (green << 8) | blue;
}
}
image.setRGB(0, 0, width, height, pixels, 0, width);
return new BufferedImageWrapper(image);
}
int height = (int) shape.get(0);
int width = (int) shape.get(1);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
int index = h * width + w;
int pos = index * 3;
int red = raw[pos];
int green = raw[pos + 1];
int blue = raw[pos + 2];
pixels[index] = (red << 16) | (green << 8) | blue;
}
}
image.setRGB(0, 0, width, height, pixels, 0, width);
return new BufferedImageWrapper(image);
}
/** {@inheritDoc} */
@Override
public Image fromPixels(int[] pixels, int width, int height) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image.setRGB(0, 0, width, height, pixels, 0, width);
return new BufferedImageWrapper(image);
}
protected void save(BufferedImage image, OutputStream os, String type) throws IOException {
ImageIO.write(image, type, os);
}
private class BufferedImageWrapper implements Image {
private BufferedImage image;
BufferedImageWrapper(BufferedImage image) {
this.image = image;
}
/** {@inheritDoc} */
@Override
public int getWidth() {
return image.getWidth();
}
/** {@inheritDoc} */
@Override
public int getHeight() {
return image.getHeight();
}
/** {@inheritDoc} */
@Override
public BufferedImage getWrappedImage() {
return image;
}
/** {@inheritDoc} */
@Override
public BufferedImageWrapper resize(int width, int height, boolean copy) {
if (!copy && image.getWidth() == width && image.getHeight() == height) {
return this;
}
java.awt.Image img =
image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
BufferedImage scaled = new BufferedImage(width, height, image.getType());
Graphics2D g2d = scaled.createGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
return new BufferedImageWrapper(scaled);
}
/** {@inheritDoc} */
@Override
public Image getSubImage(int x, int y, int w, int h) {
return new BufferedImageWrapper(image.getSubimage(x, y, w, h));
}
/** {@inheritDoc} */
@Override
public Image duplicate() {
BufferedImage copy =
new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
byte[] sourceData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
byte[] biData = ((DataBufferByte) copy.getRaster().getDataBuffer()).getData();
System.arraycopy(sourceData, 0, biData, 0, sourceData.length);
return new BufferedImageWrapper(copy);
}
/** {@inheritDoc} */
@Override
public Image getMask(int[][] mask) {
int w = mask[0].length;
int h = mask.length;
BufferedImageWrapper resized = resize(w, h, true);
BufferedImage img = resized.getWrappedImage();
int[] pixels = new int[w * h];
int index = 0;
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
if (mask[y][x] != 0) {
pixels[index] = img.getRGB(x, y);
}
index++;
}
}
return fromPixels(pixels, w, h);
}
private void convertIdNeeded() {
if (image.getType() == BufferedImage.TYPE_INT_ARGB) {
return;
}
BufferedImage newImage =
new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = newImage;
}
/** {@inheritDoc} */
@Override
public NDArray toNDArray(NDManager manager, Flag flag) {
int width = image.getWidth();
int height = image.getHeight();
int channel;
if (flag == Flag.GRAYSCALE) {
channel = 1;
} else {
channel = 3;
}
ByteBuffer bb = manager.allocateDirect(channel * height * width);
if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) {
int[] data = new int[width * height];
image.getData().getPixels(0, 0, width, height, data);
for (int gray : data) {
byte b = (byte) gray;
bb.put(b);
if (flag != Flag.GRAYSCALE) {
bb.put(b);
bb.put(b);
}
}
} else {
// get an array of integer pixels in the default RGB color mode
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
for (int rgb : pixels) {
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
if (flag == Flag.GRAYSCALE) {
int gray = Math.round(0.299f * red + 0.587f * green + 0.114f * blue);
bb.put((byte) gray);
} else {
bb.put((byte) red);
bb.put((byte) green);
bb.put((byte) blue);
}
}
}
bb.rewind();
return manager.create(bb, new Shape(height, width, channel), DataType.UINT8);
}
/** {@inheritDoc} */
@Override
public void save(OutputStream os, String type) throws IOException {
BufferedImageFactory.this.save(image, os, type);
}
/** {@inheritDoc} */
@Override
public List<BoundingBox> findBoundingBoxes() {
// TODO: Add grayscale conversion and use BoundFinder to implement
throw new UnsupportedOperationException("Not supported for BufferedImage");
}
/** {@inheritDoc} */
@Override
public void drawBoundingBoxes(DetectedObjects detections, float opacity) {
// Make image copy with alpha channel because original image was jpg
convertIdNeeded();
Graphics2D g = (Graphics2D) image.getGraphics();
int stroke = 2;
g.setStroke(new BasicStroke(stroke));
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
List<DetectedObjects.DetectedObject> list = detections.items();
int k = 10;
Map<String, Integer> classNumberTable = new ConcurrentHashMap<>();
for (DetectedObjects.DetectedObject result : list) {
String className = result.getClassName();
BoundingBox box = result.getBoundingBox();
if (classNumberTable.containsKey(className)) {
g.setPaint(new Color(classNumberTable.get(className)));
} else {
g.setPaint(new Color(k));
classNumberTable.put(className, k);
k = (k + 100) % 255;
}
if (!className.isEmpty()) {
Rectangle rectangle = box.getBounds();
int x = (int) (rectangle.getX() * imageWidth);
int y = (int) (rectangle.getY() * imageHeight);
g.drawRect(
x,
y,
(int) (rectangle.getWidth() * imageWidth),
(int) (rectangle.getHeight() * imageHeight));
drawText(g, className, x, y, stroke, 4);
}
// If we have a mask instead of a plain rectangle, draw tha mask
if (box instanceof Mask) {
drawMask((Mask) box, opacity);
} else if (box instanceof Landmark) {
drawLandmarks(box);
}
}
g.dispose();
}
/** {@inheritDoc} */
@Override
public void drawRectangle(Rectangle rect, int rgb, int thickness) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(thickness));
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaint(new Color(rgb));
int x = (int) rect.getX();
int y = (int) rect.getY();
g.drawRect(x, y, (int) rect.getWidth(), (int) rect.getHeight());
}
/** {@inheritDoc} */
@Override
public void drawMarks(List<Point> points, int radius) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(246, 96, 0));
for (Point point : points) {
int[][] star = createStar(point, radius);
g.fillPolygon(star[0], star[1], 10);
}
g.dispose();
}
/** {@inheritDoc} */
@Override
public void drawJoints(Joints joints) {
// Make image copy with alpha channel because original image was jpg
convertIdNeeded();
Graphics2D g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
List<Joints.Joint> list = joints.getJoints();
if (list.size() == 17) {
g.setColor(new Color(224, 255, 37));
g.setStroke(new BasicStroke(3));
drawLine(g, list.get(5), list.get(7), imageWidth, imageHeight);
drawLine(g, list.get(7), list.get(9), imageWidth, imageHeight);
drawLine(g, list.get(6), list.get(8), imageWidth, imageHeight);
drawLine(g, list.get(8), list.get(10), imageWidth, imageHeight);
drawLine(g, list.get(11), list.get(13), imageWidth, imageHeight);
drawLine(g, list.get(12), list.get(14), imageWidth, imageHeight);
drawLine(g, list.get(13), list.get(15), imageWidth, imageHeight);
drawLine(g, list.get(14), list.get(16), imageWidth, imageHeight);
drawLine(g, list.get(5), list.get(6), imageWidth, imageHeight);
drawLine(g, list.get(11), list.get(12), imageWidth, imageHeight);
drawLine(g, list.get(5), list.get(11), imageWidth, imageHeight);
drawLine(g, list.get(6), list.get(12), imageWidth, imageHeight);
}
g.setColor(new Color(37, 150, 190));
g.setStroke(new BasicStroke(2));
for (Joints.Joint joint : list) {
int x = (int) (joint.getX() * imageWidth);
int y = (int) (joint.getY() * imageHeight);
g.fillOval(x - 6, y - 6, 12, 12);
}
g.dispose();
}
/** {@inheritDoc} */
@Override
public void drawImage(Image overlay, boolean resize) {
if (!(overlay.getWrappedImage() instanceof BufferedImage)) {
throw new IllegalArgumentException("Only BufferedImage allowed");
}
if (resize) {
overlay = overlay.resize(getWidth(), getHeight(), false);
}
BufferedImage target =
new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) target.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage((BufferedImage) overlay.getWrappedImage(), 0, 0, null);
g.dispose();
image = target;
}
private void drawLine(
Graphics2D g, Joints.Joint from, Joints.Joint to, int width, int height) {
int x0 = (int) (from.getX() * width);
int y0 = (int) (from.getY() * height);
int x1 = (int) (to.getX() * width);
int y1 = (int) (to.getY() * height);
g.drawLine(x0, y0, x1, y1);
}
private void drawText(Graphics2D g, String text, int x, int y, int stroke, int padding) {
FontMetrics metrics = g.getFontMetrics();
x += stroke / 2;
y += stroke / 2;
int width = metrics.stringWidth(text) + padding * 2 - stroke / 2;
int height = metrics.getHeight() + metrics.getDescent();
int ascent = metrics.getAscent();
java.awt.Rectangle background = new java.awt.Rectangle(x, y, width, height);
g.fill(background);
g.setPaint(Color.WHITE);
g.drawString(text, x + padding, y + ascent);
}
private void drawMask(Mask mask, float ratio) {
float r = RandomUtils.nextFloat();
float g = RandomUtils.nextFloat();
float b = RandomUtils.nextFloat();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
int x = 0;
int y = 0;
int w = imageWidth;
int h = imageHeight;
if (!mask.isFullImageMask()) {
x = (int) (mask.getX() * imageWidth);
y = (int) (mask.getY() * imageHeight);
w = (int) (mask.getWidth() * imageWidth);
h = (int) (mask.getHeight() * imageHeight);
// Correct some coordinates of box when going out of image
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
}
float[][] probDist = mask.getProbDist();
if (ratio < 0 || ratio > 1) {
float max = 0;
for (float[] row : probDist) {
for (float f : row) {
max = Math.max(max, f);
}
}
ratio = 0.5f / max;
}
BufferedImage maskImage =
new BufferedImage(
probDist[0].length, probDist.length, BufferedImage.TYPE_INT_ARGB);
for (int yCor = 0; yCor < probDist.length; yCor++) {
for (int xCor = 0; xCor < probDist[0].length; xCor++) {
float opacity = probDist[yCor][xCor] * ratio;
maskImage.setRGB(xCor, yCor, new Color(r, g, b, opacity).darker().getRGB());
}
}
java.awt.Image scaled = maskImage.getScaledInstance(w, h, java.awt.Image.SCALE_SMOOTH);
Graphics2D gR = (Graphics2D) image.getGraphics();
gR.drawImage(scaled, x, y, null);
gR.dispose();
}
private void drawLandmarks(BoundingBox box) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(new Color(246, 96, 0));
BasicStroke bStroke = new BasicStroke(4, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g.setStroke(bStroke);
for (Point point : box.getPath()) {
g.drawRect((int) point.getX(), (int) point.getY(), 2, 2);
}
g.dispose();
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/Image.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Joints;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* {@code Image} is a container of an image in DJL. The storage type of the image depends on the
* platform you are running on.
*/
public interface Image {
/**
* Gets the width of the image.
*
* @return pixels representing width
*/
int getWidth();
/**
* Gets the height of the image.
*
* @return pixels representing height
*/
int getHeight();
/**
* Gets the wrapped image.
*
* @return the wrapped image object
*/
Object getWrappedImage();
/**
* Creates a new resized image.
*
* @param width the new image's desired width
* @param height the new image's desired height
* @param copy false to return original image if size is the same
* @return the new resized image.
*/
Image resize(int width, int height, boolean copy);
/**
* Returns a new {@code Image} of masked area.
*
* @param mask the mask for each pixel in the image
* @return the mask image.
*/
Image getMask(int[][] mask);
/**
* Gets the subimage defined by a specified rectangular region.
*
* @param x the X coordinate of the upper-left corner of the specified rectangular region
* @param y the Y coordinate of the upper-left corner of the specified rectangular region
* @param w the width of the specified rectangular region
* @param h the height of the specified rectangular region
* @return subimage of this image
*/
Image getSubImage(int x, int y, int w, int h);
/**
* Gets a deep copy of the original image.
*
* @return the copy of the original image.
*/
Image duplicate();
/**
* Converts image to a RGB {@link NDArray}.
*
* @param manager a {@link NDManager} to create the new NDArray with
* @return {@link NDArray}
*/
default NDArray toNDArray(NDManager manager) {
return toNDArray(manager, null);
}
/**
* Converts image to a {@link NDArray}.
*
* @param manager a {@link NDManager} to create the new NDArray with
* @param flag the color mode
* @return {@link NDArray}
*/
NDArray toNDArray(NDManager manager, Flag flag);
/**
* Save the image to file.
*
* @param os {@link OutputStream} to save the image.
* @param type type of the image, such as "png", "jpeg"
* @throws IOException image cannot be saved through output stream
*/
void save(OutputStream os, String type) throws IOException;
/**
* Find bounding boxes from a masked image with 0/1 or 0/255.
*
* @return the List of bounding boxes of the images
*/
List<BoundingBox> findBoundingBoxes();
/**
* Draws the bounding boxes on the image.
*
* @param detections the object detection results
*/
default void drawBoundingBoxes(DetectedObjects detections) {
drawBoundingBoxes(detections, -1);
}
/**
* Draws the bounding boxes on the image.
*
* @param detections the object detection results
*/
void drawBoundingBoxes(DetectedObjects detections, float opacity);
/**
* Draws a rectangle on the image.
*
* @param rect the rectangle to draw
* @param rgb the color
* @param thickness the thickness
*/
void drawRectangle(Rectangle rect, int rgb, int thickness);
/**
* Draws a mark on the image.
*
* @param points as list of {@code Point}
*/
default void drawMarks(List<Point> points) {
int w = getWidth();
int h = getHeight();
int size = Math.min(w, h) / 50;
drawMarks(points, size);
}
/**
* Draws a mark on the image.
*
* @param points as list of {@code Point}
* @param size the radius of the star mark
*/
void drawMarks(List<Point> points, int size);
/**
* Draws all joints of a body on an image.
*
* @param joints the joints of the body
*/
void drawJoints(Joints joints);
/**
* Draws the overlay on the image.
*
* @param overlay the overlay image
* @param resize true to resize the overlay image to match the image
*/
void drawImage(Image overlay, boolean resize);
/**
* Creates a star shape.
*
* @param point the coordinate
* @param radius the radius
* @return the polygon points
*/
default int[][] createStar(Point point, int radius) {
int[][] ret = new int[2][10];
double midX = point.getX();
double midY = point.getY();
double[] ratio = {radius, radius * 0.38196601125};
double delta = Math.PI / 5;
for (int i = 0; i < 10; ++i) {
double angle = i * delta;
double r = ratio[i % 2];
double x = Math.cos(angle) * r;
double y = Math.sin(angle) * r;
ret[0][i] = (int) (x + midX);
ret[1][i] = (int) (y + midY);
}
return ret;
}
/** Flag indicates the color channel options for images. */
enum Flag {
GRAYSCALE,
COLOR;
/**
* Returns the number of channels for this flag.
*
* @return the number of channels for this flag
*/
public int numChannels() {
switch (this) {
case GRAYSCALE:
return 1;
case COLOR:
return 3;
default:
throw new IllegalArgumentException("Invalid FLAG");
}
}
}
/** Interpolation indicates the Interpolation options for resizinig an image. */
enum Interpolation {
NEAREST,
BILINEAR,
AREA,
BICUBIC
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/ImageFactory.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.ndarray.NDArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* {@code ImageFactory} contains image creation mechanism on top of different platforms like PC and
* Android. System will choose appropriate Factory based on the supported image type.
*/
public abstract class ImageFactory {
private static final Logger logger = LoggerFactory.getLogger(ImageFactory.class);
private static final String[] FACTORIES = {
"ai.djl.opencv.OpenCVImageFactory",
"ai.djl.modality.cv.BufferedImageFactory",
"ai.djl.android.core.BitmapImageFactory"
};
private static final Pattern URL_PATTERN = Pattern.compile("^data:image/\\w+;base64,(.+)");
private static ImageFactory factory = newInstance();
private static ImageFactory newInstance() {
int index = 0;
if ("http://www.android.com/".equals(System.getProperty("java.vendor.url"))) {
index = 2;
}
for (int i = index; i < FACTORIES.length; ++i) {
try {
Class<? extends ImageFactory> clazz =
Class.forName(FACTORIES[i]).asSubclass(ImageFactory.class);
return clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException | ExceptionInInitializerError e) {
logger.trace("", e);
}
}
throw new IllegalStateException("Create new ImageFactory failed!");
}
/**
* Gets new instance of Image factory from the provided factory implementation.
*
* @return {@link ImageFactory}
*/
public static ImageFactory getInstance() {
return factory;
}
/**
* Sets a custom instance of {@code ImageFactory}.
*
* @param factory a custom instance of {@code ImageFactory}
*/
public static void setImageFactory(ImageFactory factory) {
ImageFactory.factory = factory;
}
/**
* Gets {@link Image} from file.
*
* @param path the path to the image
* @return {@link Image}
* @throws IOException Image not found or not readable
*/
public abstract Image fromFile(Path path) throws IOException;
/**
* Gets {@link Image} from URL.
*
* @param url the URL to load from
* @return {@link Image}
* @throws IOException URL is not valid.
*/
public Image fromUrl(URL url) throws IOException {
try (InputStream is = url.openStream()) {
return fromInputStream(is);
}
}
/**
* Gets {@link Image} from string representation.
*
* @param url the String represent URL or base64 encoded image to load from
* @return {@link Image}
* @throws IOException URL is not valid.
*/
public Image fromUrl(String url) throws IOException {
Matcher m = URL_PATTERN.matcher(url);
if (m.matches()) {
// url="data:image/png;base64,..."
byte[] buf = Base64.getDecoder().decode(m.group(1));
try (InputStream is = new ByteArrayInputStream(buf)) {
return fromInputStream(is);
}
}
URI uri = URI.create(url);
if (uri.isAbsolute()) {
return fromUrl(uri.toURL());
}
return fromFile(Paths.get(url));
}
/**
* Gets {@link Image} from {@link InputStream}.
*
* @param is {@link InputStream}
* @return {@link Image}
* @throws IOException image cannot be read from input stream.
*/
public abstract Image fromInputStream(InputStream is) throws IOException;
/**
* Gets {@link Image} from varies Java image types.
*
* <p>Image can be BufferedImage or BitMap depends on platform
*
* @param image the image object.
* @return {@link Image}
*/
public abstract Image fromImage(Object image);
/**
* Gets {@link Image} from {@link NDArray}.
*
* @param array the NDArray with CHW format
* @return {@link Image}
*/
public abstract Image fromNDArray(NDArray array);
/**
* Gets {@link Image} from array.
*
* @param pixels the array of ARGB values used to initialize the pixels.
* @param width the width of the image
* @param height the height of the image
* @return {@link Image}
*/
public abstract Image fromPixels(int[] pixels, int width, int height);
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/MultiBoxDetection.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.ndarray.NDList;
/**
* {@code MultiBoxDetection} is the class that takes the output of a multi-box detection model, and
* converts it into an NDList that contains the object detections.
*
* <p>The output from a Single Shot Detection(SSD) network would be class probabilities, box offset
* predictions, and the generated anchor boxes. Once out-of-boundary boxes are eliminated, and boxes
* with scores lower than the threshold are removed, we will ideally have a small number of
* candidates for each object in the image. Since anchor boxes are generated in multiple scales
* around each pixel by {@link MultiBoxPrior}, there are bound to be multiple boxes around each
* object which have a score greater than the threshold. We use Non-Maximum Suppression(NMS) to
* choose one box that is most likely to fit the object in the image.
*
* <p>{@code MultiBoxDetection} handles all of these tasks, and returns an {@link NDList} with a
* single {@link ai.djl.ndarray.NDArray} of {@link ai.djl.ndarray.types.Shape} (batch_size, Number
* of generated anchor boxes, 6). For each generated anchor box, there is an {@link
* ai.djl.ndarray.NDArray} of {@link ai.djl.ndarray.types.Shape} (6,). The values in each of those
* arrays represent the following: {@code [class, score, x_min, y_min, x_max, y_max]}. The {@code
* class} is set to -1 for boxes that are removed or classified as background. The {@code score} is
* the confidence with which the model thinks the box contains an object of the specified {@code
* class}, and the other four values represent the normalised co-ordinates of the box.
*/
public class MultiBoxDetection {
private boolean clip;
private float threshold;
private int backgroundId;
private float nmsThreshold;
private boolean forceSuppress;
private int nmsTopK;
/**
* Creates a new instance of {@code MultiBoxDetection} with the arguments from the given {@link
* Builder}.
*
* @param builder the {@link Builder} with the necessary arguments
*/
public MultiBoxDetection(Builder builder) {
this.clip = builder.clip;
this.threshold = builder.threshold;
this.backgroundId = builder.backgroundId;
this.nmsThreshold = builder.nmsThreshold;
this.forceSuppress = builder.forceSuppress;
this.nmsTopK = builder.nmsTopK;
}
/**
* Converts multi-box detection predictions.
*
* @param inputs a NDList of (class probabilities, box predictions, and anchors) in that order
* @return an {@link NDList} with a single {@link ai.djl.ndarray.NDArray} of {@link
* ai.djl.ndarray.types.Shape} (batch_size, Number of generated anchor boxes, 6). For each
* generated anchor box, there is an {@link ai.djl.ndarray.NDArray} of {@link
* ai.djl.ndarray.types.Shape} (6,). The values in each of those arrays represent the
* following: {@code [class, score, x_min, y_min, x_max, y_max]}
*/
public NDList detection(NDList inputs) {
if (inputs == null || inputs.size() != 3) {
throw new IllegalArgumentException(
"NDList must contain class probabilities, box predictions, and anchors");
}
return inputs.head()
.getNDArrayInternal()
.multiBoxDetection(
inputs,
clip,
threshold,
backgroundId,
nmsThreshold,
forceSuppress,
nmsTopK);
}
/**
* Creates a builder to build a {@code MultiBoxDetection}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/** The Builder to construct a {@link MultiBoxDetection} object. */
public static final class Builder {
boolean clip = true;
private float threshold = 0.01f;
int backgroundId;
private float nmsThreshold = 0.5f;
boolean forceSuppress;
private int nmsTopK = -1;
Builder() {}
/**
* Sets the boolean parameter that indicates whether to clip out-of-boundary boxes. It is
* set to {@code true} by default.
*
* @param clip whether to clip out-of-boundary boxes
* @return this {@code Builder}
*/
public Builder optClip(boolean clip) {
this.clip = clip;
return this;
}
/**
* Sets the boolean parameter that indicates whether to suppress all detections regardless
* of class_id. It is set to {@code false} by default.
*
* @param forceSuppress whether to suppress all detections regardless of class_id
* @return this {@code Builder}
*/
public Builder optForceSuppress(boolean forceSuppress) {
this.forceSuppress = forceSuppress;
return this;
}
/**
* Sets the class ID for the background. Defaults to 0.
*
* @param backgroundId the class ID for the background
* @return this {@code Builder}
*/
public Builder optBackgroundId(int backgroundId) {
this.backgroundId = backgroundId;
return this;
}
/**
* Sets the boolean parameter that indicates whether to clip out-of-boundary boxes. Defaults
* to -1 which implies that there is no limit.
*
* @param nmsTopK whether to clip out-of-boundary boxes
* @return this {@code Builder}
*/
public Builder optNmsTopK(int nmsTopK) {
this.nmsTopK = nmsTopK;
return this;
}
/**
* Sets the threshold score for a detection to be a positive prediction. Defaults to 0.01.
*
* @param threshold the threshold score for a detection to be a positive prediction
* @return this {@code Builder}
*/
public Builder optThreshold(float threshold) {
this.threshold = threshold;
return this;
}
/**
* Sets the non-maximum suppression(NMS) threshold. Defaults to 0.5.
*
* @param nmsThreshold the non-maximum suppression(NMS) threshold
* @return this {@code Builder}
*/
public Builder optNmsThreshold(float nmsThreshold) {
this.nmsThreshold = nmsThreshold;
return this;
}
/**
* Builds a {@link MultiBoxDetection} block.
*
* @return the {@link MultiBoxDetection} block
*/
public MultiBoxDetection build() {
return new MultiBoxDetection(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/MultiBoxPrior.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.ndarray.NDArray;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* {@code MultiBoxPrior} is the class that generates anchor boxes that act as priors for object
* detection.
*
* <p>Object detection algorithms usually sample a large number of regions in the input image,
* determine whether these regions contain objects of interest, and adjust the edges of the regions
* so as to predict the ground-truth bounding box of the target more accurately. Different models
* may use different region sampling methods. These bounding boxes are also called anchor boxes.
*
* <p>{@code MultiBoxPrior} generates these anchor boxes, based on the required sizes and aspect
* ratios and returns an {@link NDArray} of {@link ai.djl.ndarray.types.Shape} (1, Number of anchor
* boxes, 4). Anchor boxes need not be generated separately for the each example in the batch. One
* set of anchor boxes per batch is sufficient.
*
* <p>The number of anchor boxes generated depends on the number of sizes and aspect ratios. If the
* number of sizes is \(n\) and the number of ratios is \(m\), the total number of boxes generated
* per pixel is \(n + m - 1\).
*/
public class MultiBoxPrior {
private List<Float> sizes;
private List<Float> ratios;
private List<Float> steps;
private List<Float> offsets;
private boolean clip;
/**
* Creates a new instance of {@code MultiBoxPrior} with the arguments from the given {@link
* Builder}.
*
* @param builder the {@link Builder} with the necessary arguments
*/
public MultiBoxPrior(Builder builder) {
this.sizes = builder.sizes;
this.ratios = builder.ratios;
this.steps = builder.steps;
this.offsets = builder.offsets;
this.clip = builder.clip;
}
/**
* Generates the anchorBoxes array in the input's manager and device.
*
* @param input the input whose manager and device to put the generated boxes in
* @return the generated boxes
*/
public NDArray generateAnchorBoxes(NDArray input) {
return input.getNDArrayInternal().multiBoxPrior(sizes, ratios, steps, offsets, clip).head();
}
/**
* Creates a builder to build a {@code MultiBoxPrior}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/** The Builder to construct a {@link MultiBoxPrior} object. */
public static final class Builder {
List<Float> sizes = Collections.singletonList(1f);
List<Float> ratios = Collections.singletonList(1f);
List<Float> steps = Arrays.asList(-1f, -1f);
List<Float> offsets = Arrays.asList(0.5f, 0.5f);
boolean clip;
Builder() {}
/**
* Sets the sizes of the anchor boxes to be generated around each pixel.
*
* @param sizes the size of the anchor boxes generated around each pixel
* @return this {@code Builder}
*/
public Builder setSizes(List<Float> sizes) {
this.sizes = sizes;
return this;
}
/**
* Sets the aspect ratios of the anchor boxes to be generated around each pixel.
*
* @param ratios the aspect ratios of the anchor boxes to be generated around each pixel
* @return this {@code Builder}
*/
public Builder setRatios(List<Float> ratios) {
this.ratios = ratios;
return this;
}
/**
* Sets the step across \(x\) and \(y\) dimensions. Defaults to -1 across both dimensions.
*
* @param steps the step across \(x\) and \(y\) dimensions
* @return this {@code Builder}
*/
public Builder optSteps(List<Float> steps) {
this.steps = steps;
return this;
}
/**
* Sets the value of the center-box offsets across \(x\) and \(y\) dimensions. Defaults to
* 0.5 across both dimensions.
*
* @param offsets the value of the center-box offsets across \(x\) and \(y\) dimensions
* @return this {@code Builder}
*/
public Builder optOffsets(List<Float> offsets) {
this.offsets = offsets;
return this;
}
/**
* Sets the boolean parameter that indicates whether to clip out-of-boundary boxes. It is
* set to {@code false} by default.
*
* @param clip whether to clip out-of-boundary boxes
* @return this {@code Builder}
*/
public Builder optClip(boolean clip) {
this.clip = clip;
return this;
}
/**
* Builds a {@link MultiBoxPrior} block.
*
* @return the {@link MultiBoxPrior} block
*/
public MultiBoxPrior build() {
return new MultiBoxPrior(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/MultiBoxTarget.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.ndarray.NDList;
/**
* {@code MultiBoxTarget} is the class that computes the training targets for training a Single Shot
* Detection (SSD) models.
*
* <p>The output from a Single Shot Detection (SSD) network would be class probabilities, box offset
* predictions, and the generated anchor boxes. The labels contain a class label and the bounding
* box for each object in the image. The generated anchor boxes are each a prior, and need loss
* computed for each of them. This requires that we assign a ground truth box to every one of them.
*
* <p>{@code MultiBoxTarget} takes an {@link NDList} containing (anchor boxes, labels, class
* predictions) in that order. It computes the Intersection-over-Union (IoU) of each anchor box
* against every ground-truth box. For every anchor box, it assigns a ground-truth box with maximum
* IoU with respect to the anchor box if the IoU is greater than a given threshold. Once a
* ground-truth box is assigned for each anchor box, it computes the offset of each anchor box with
* respect to it's assigned ground-truth box.
*
* <p>{@code MultiBoxTarget} handles these tasks and returns an {@link NDList} containing (Bounding
* box offsets, bounding box masks, class labels). Bounding box offsets and class labels are
* computed as above. Bounding box masks is a mask array that contains either a 0 or 1, with the 0s
* corresponding to the anchor boxes whose IoUs with the ground-truth boxes were less than the given
* threshold.
*/
public class MultiBoxTarget {
int minNegativeSamples;
private float iouThreshold;
private float negativeMiningRatio;
private float ignoreLabel;
private float negativeMiningThreshold;
/**
* Creates a new instance of {@code MultiBoxTarget} with the arguments from the given {@link
* Builder}.
*
* @param builder the {@link Builder} with the necessary arguments
*/
public MultiBoxTarget(Builder builder) {
this.minNegativeSamples = builder.minNegativeSamples;
this.iouThreshold = builder.iouThreshold;
this.negativeMiningThreshold = builder.negativeMiningThreshold;
this.negativeMiningRatio = builder.negativeMinigRatio;
this.ignoreLabel = builder.ignoreLabel;
}
/**
* Computes multi-box training targets.
*
* @param inputs a NDList of (anchors, labels, and class prediction) in that order
* @return an {@link NDList} containing (Bounding box offsets, bounding box masks, class labels)
*/
public NDList target(NDList inputs) {
if (inputs == null || inputs.size() != 3) {
throw new IllegalArgumentException(
"NDList must contain anchors, labels, and class predictions");
}
return inputs.head()
.getNDArrayInternal()
.multiBoxTarget(
inputs,
iouThreshold,
ignoreLabel,
negativeMiningRatio,
negativeMiningThreshold,
minNegativeSamples);
}
/**
* Creates a builder to build a {@code MultiBoxTarget}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/** The Builder to construct a {@link MultiBoxTarget} object. */
public static final class Builder {
int minNegativeSamples;
float iouThreshold = 0.5f;
float ignoreLabel = -1;
float negativeMiningThreshold = 0.5f;
float negativeMinigRatio = -1;
Builder() {}
/**
* Sets the minimum number of negative samples.
*
* @param minNegativeSamples the minimum number of negative samples
* @return this {@code Builder}
*/
public Builder optMinNegativeSamples(int minNegativeSamples) {
this.minNegativeSamples = minNegativeSamples;
return this;
}
/**
* Sets the anchor-GroundTruth overlap threshold to be regarded as a positive match.
*
* @param iouThreshold the anchor-GroundTruth overlap threshold to be regarded as a positive
* match
* @return this {@code Builder}
*/
public Builder optIouThreshold(float iouThreshold) {
this.iouThreshold = iouThreshold;
return this;
}
/**
* Sets the label for ignored anchors. Defaults to -1.
*
* @param ignoreLabel the label for ignored anchors
* @return this {@code Builder}
*/
public Builder optIgnoreLabel(float ignoreLabel) {
this.ignoreLabel = ignoreLabel;
return this;
}
/**
* Sets the threshold used for negative mining.
*
* @param negativeMiningThreshold the threshold used for negative mining
* @return this {@code Builder}
*/
public Builder optNegativeMiningThreshold(float negativeMiningThreshold) {
this.negativeMiningThreshold = negativeMiningThreshold;
return this;
}
/**
* Sets the max negative to positive samples ratio. Use -1 to disable mining. Defaults to
* -1.
*
* @param negativeMinigRatio the max negative to positive samples ratio
* @return this {@code Builder}
*/
public Builder optNegativeMinigRatio(float negativeMinigRatio) {
this.negativeMinigRatio = negativeMinigRatio;
return this;
}
/**
* Builds a {@link MultiBoxTarget} block.
*
* @return the {@link MultiBoxTarget} block
*/
public MultiBoxTarget build() {
return new MultiBoxTarget(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/VisionLanguageInput.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv;
import ai.djl.modality.Input;
import ai.djl.translate.TranslateException;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
/** The input container for a vision language model. */
public class VisionLanguageInput {
private Image image;
private String text;
@SerializedName("candidate_labels")
private String[] candidates;
@SerializedName("hypothesis_template")
private String hypothesisTemplate;
/**
* Constructs a new {@code ImageTextInput} instance.
*
* @param image the image input
* @param text the prompt
*/
public VisionLanguageInput(Image image, String text) {
this(image, text, null, null);
}
/**
* Constructs a new {@code ImageTextInput} instance.
*
* @param image the image input
* @param candidates the candidate labels
*/
public VisionLanguageInput(Image image, String[] candidates) {
this(image, null, candidates, null);
}
/**
* Constructs a new {@code ImageTextInput} instance.
*
* @param image the image input
* @param text the prompt
* @param candidates the candidate labels
* @param hypothesisTemplate the hypothesis template
*/
public VisionLanguageInput(
Image image, String text, String[] candidates, String hypothesisTemplate) {
this.image = image;
this.text = text;
this.candidates = candidates;
this.hypothesisTemplate = hypothesisTemplate;
}
/**
* Returns the {@code ImageTextInput} from the {@link Input}.
*
* @param input the input object
* @return the {@code ImageTextInput} from the {@link Input}
* @throws TranslateException if the input is invalid
* @throws IOException if failed to load image
*/
public static VisionLanguageInput parseInput(Input input)
throws TranslateException, IOException {
String data = input.getData().getAsString();
try {
JsonObject obj = JsonUtils.GSON.fromJson(data, JsonObject.class);
JsonElement url = obj.get("image");
if (url == null) {
url = obj.get("image_url");
}
if (url == null) {
throw new TranslateException("Missing \"image\" parameter in input.");
}
Image img = ImageFactory.getInstance().fromUrl(url.getAsString());
String text = JsonUtils.GSON.fromJson(obj.get("text"), String.class);
String[] candidates =
JsonUtils.GSON.fromJson(obj.get("candidate_labels"), String[].class);
String hypothesisTemplate =
JsonUtils.GSON.fromJson(obj.get("hypothesis_template"), String.class);
return new VisionLanguageInput(img, text, candidates, hypothesisTemplate);
} catch (JsonParseException e) {
throw new TranslateException("Input is not a valid json.", e);
}
}
/**
* Returns the image input.
*
* @return the image input
*/
public Image getImage() {
return image;
}
/**
* Sets the image input.
*
* @param image the image input
*/
public void setImage(Image image) {
this.image = image;
}
/**
* Returns the prompt text.
*
* @return the prompt text
*/
public String getText() {
return text;
}
/**
* Sets the prompt text.
*
* @param text the prompt text
*/
public void setText(String text) {
this.text = text;
}
/**
* Returns the candidate labels.
*
* @return the candidate labels
*/
public String[] getCandidates() {
return candidates;
}
/**
* Sets the candidate labels.
*
* @param candidates the candidate labels
*/
public void setCandidates(String[] candidates) {
this.candidates = candidates;
}
/**
* Returns the hypothesis template.
*
* @return the hypothesis template
*/
public String getHypothesisTemplate() {
return hypothesisTemplate == null ? "This is a photo of {}." : hypothesisTemplate;
}
/**
* Sets the hypothesis template.
*
* @param hypothesisTemplate the hypothesis template
*/
public void setHypothesisTemplate(String hypothesisTemplate) {
this.hypothesisTemplate = hypothesisTemplate;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains utility classes for computer vision tasks and image processing. */
package ai.djl.modality.cv;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/BoundingBox.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import java.io.Serializable;
/** An interface representing a bounding box around an object inside an image. */
public interface BoundingBox extends Serializable {
/**
* Returns the bounding {@code Rectangle} of this {@code BoundingBox}.
*
* @return a new {@code Rectangle} for this {@code BoundingBox}
*/
Rectangle getBounds();
/**
* Returns an iterator object that iterates along the {@code BoundingBox} boundary and provides
* access to the geometry of the {@code BoundingBox} outline.
*
* @return a {@code Iterable} object, which independently traverses the geometry of the {@code
* BoundingBox}
*/
Iterable<Point> getPath();
/**
* Returns the top left point of the bounding box.
*
* @return the {@link Point} of the top left corner
*/
Point getPoint();
/**
* Returns the Intersection over Union (IoU) value between bounding boxes.
*
* <p>Also known as <a href="https://en.wikipedia.org/wiki/Jaccard_index">Jaccard index</a>
*
* @param box the bounding box to calculate
* @return the IoU value
*/
double getIoU(BoundingBox box);
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/CategoryMask.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.util.JsonSerializable;
import ai.djl.util.JsonUtils;
import ai.djl.util.RandomUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.stream.Collectors;
/**
* A class representing the segmentation result of an image in an {@link
* ai.djl.Application.CV#SEMANTIC_SEGMENTATION} case.
*/
public class CategoryMask implements JsonSerializable {
private static final long serialVersionUID = 1L;
private static final int COLOR_BLACK = 0xFF000000;
@SuppressWarnings("serial")
private List<String> classes;
private int[][] mask;
/**
* Constructs a Mask with the given data.
*
* @param classes the list of classes
* @param mask the category mask for each pixel in the image
*/
public CategoryMask(List<String> classes, int[][] mask) {
this.classes = classes;
this.mask = mask;
}
/**
* Returns the list of classes.
*
* @return list of classes
*/
public List<String> getClasses() {
return classes;
}
/**
* Returns the class for each pixel.
*
* @return the class for each pixel
*/
public int[][] getMask() {
return mask;
}
/** {@inheritDoc} */
@Override
public JsonElement serialize() {
JsonObject ret = new JsonObject();
ret.add("classes", JsonUtils.GSON.toJsonTree(classes));
ret.add("mask", JsonUtils.GSON.toJsonTree(mask));
return ret;
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(4096);
String list = classes.stream().map(s -> '"' + s + '"').collect(Collectors.joining(", "));
sb.append("{\n\t\"classes\": [").append(list).append("],\n\t\"mask\": ");
sb.append(JsonUtils.GSON_COMPACT.toJson(mask));
sb.append("\n}");
return sb.toString();
}
/**
* Extracts the detected objects from the image.
*
* @param image the original image
* @return the detected objects from the image
*/
public Image getMaskImage(Image image) {
return image.getMask(mask);
}
/**
* Extracts the specified object from the image.
*
* @param image the original image
* @param classId the class to extract from the image
* @return the specific object on the image
*/
public Image getMaskImage(Image image, int classId) {
int width = mask[0].length;
int height = mask.length;
int[][] selected = new int[height][width];
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
selected[h][w] = mask[h][w] == classId ? 1 : 0;
}
}
return image.getMask(selected);
}
/**
* Extracts the background from the image.
*
* @param image the original image
* @return the background of the image
*/
public Image getBackgroundImage(Image image) {
return getMaskImage(image, 0);
}
/**
* Highlights the detected object on the image with random colors.
*
* @param image the original image
* @param opacity the opacity of the overlay. Value is between 0 and 255 inclusive, where 0
* means the overlay is completely transparent and 255 means the overlay is completely
* opaque.
*/
public void drawMask(Image image, int opacity) {
drawMask(image, opacity, COLOR_BLACK);
}
/**
* Highlights the detected object on the image with random colors.
*
* @param image the original image
* @param opacity the opacity of the overlay. Value is between 0 and 255 inclusive, where 0
* means the overlay is completely transparent and 255 means the overlay is completely
* opaque.
* @param background replace the background with specified background color, use transparent
* color to remove background
*/
public void drawMask(Image image, int opacity, int background) {
int[] colors = generateColors(background, opacity);
Image maskImage = getColorOverlay(colors);
image.drawImage(maskImage, true);
}
/**
* Highlights the specified object with specific color.
*
* @param image the original image
* @param classId the class to draw on the image
* @param color the rgb color with opacity
* @param opacity the opacity of the overlay. Value is between 0 and 255 inclusive, where 0
* means the overlay is completely transparent and 255 means the overlay is completely
* opaque.
*/
public void drawMask(Image image, int classId, int color, int opacity) {
int[] colors = new int[classes.size()];
colors[classId] = color & 0xFFFFFF | opacity << 24;
Image colorOverlay = getColorOverlay(colors);
image.drawImage(colorOverlay, true);
}
private Image getColorOverlay(int[] colors) {
int height = mask.length;
int width = mask[0].length;
int[] pixels = new int[width * height];
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = mask[h][w];
pixels[h * width + w] = colors[index];
}
}
return ImageFactory.getInstance().fromPixels(pixels, width, height);
}
private int[] generateColors(int background, int opacity) {
int[] colors = new int[classes.size()];
colors[0] = background;
for (int i = 1; i < classes.size(); i++) {
int red = RandomUtils.nextInt(256);
int green = RandomUtils.nextInt(256);
int blue = RandomUtils.nextInt(256);
colors[i] = opacity << 24 | red << 16 | green << 8 | blue;
}
return colors;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/DetectedObjects.java
|
/*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.modality.Classifications;
import java.util.List;
/**
* A class representing the detected objects results for a single image in an {@link
* ai.djl.Application.CV#OBJECT_DETECTION} case.
*/
public class DetectedObjects extends Classifications {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
private List<BoundingBox> boundingBoxes;
/**
* Constructs a DetectedObjects, usually during post-processing.
*
* <p>All three inputs(classNames, probabilities, boundingBoxes) should be parallel lists.
*
* @param classNames the names of the objects that were detected
* @param probabilities the probability of the objects that were detected
* @param boundingBoxes the bounding boxes of the objects that were detected
*/
public DetectedObjects(
List<String> classNames, List<Double> probabilities, List<BoundingBox> boundingBoxes) {
super(classNames, probabilities);
this.boundingBoxes = boundingBoxes;
this.topK = Integer.MAX_VALUE;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <T extends Classification> T item(int index) {
return (T)
new DetectedObject(
classNames.get(index), probabilities.get(index), boundingBoxes.get(index));
}
/**
* Returns the number of objects found in an image.
*
* @return the number of objects found in an image
*/
public int getNumberOfObjects() {
return boundingBoxes.size();
}
/** A {@code DetectedObject} represents a single potential detected Object for an image. */
public static final class DetectedObject extends Classification {
private BoundingBox boundingBox;
/**
* Constructs a bounding box with the given data.
*
* @param className name of the type of object
* @param probability probability that the object is correct
* @param boundingBox the location of the object
*/
public DetectedObject(String className, double probability, BoundingBox boundingBox) {
super(className, probability);
this.boundingBox = boundingBox;
}
/**
* Returns the {@link ai.djl.modality.cv.output.BoundingBox} of the detected object.
*
* @return the {@link ai.djl.modality.cv.output.BoundingBox} of the detected object
*/
public BoundingBox getBoundingBox() {
return boundingBox;
}
/** {@inheritDoc} */
@Override
public String toString() {
double probability = getProbability();
StringBuilder sb = new StringBuilder(200);
sb.append("{\"className\": \"").append(getClassName()).append("\", \"probability\": ");
if (probability < 0.00001) {
sb.append(String.format("%.1e", probability));
} else {
probability = (int) (probability * 100000) / 100000f;
sb.append(String.format("%.5f", probability));
}
if (boundingBox != null) {
sb.append(", \"boundingBox\": ").append(boundingBox);
}
sb.append('}');
return sb.toString();
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/Joints.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.util.JsonUtils;
import java.io.Serializable;
import java.util.List;
/**
* A result of all joints found during Human Pose Estimation on a single image.
*
* @see <a href="https://en.wikipedia.org/wiki/Articulated_body_pose_estimation">Wikipedia</a>
*/
public class Joints implements Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
private List<Joint> joints;
/**
* Constructs the {@code Joints} with the provided joints.
*
* @param joints the joints
*/
public Joints(List<Joint> joints) {
this.joints = joints;
}
/**
* Gets the joints for the image.
*
* @return the list of joints
*/
public List<Joint> getJoints() {
return joints;
}
/** {@inheritDoc} */
@Override
public String toString() {
return JsonUtils.GSON_PRETTY.toJson(this) + "\n";
}
/**
* A joint that was detected using Human Pose Estimation on an image.
*
* @see Joints
*/
public static class Joint extends Point {
private static final long serialVersionUID = 1L;
private double confidence;
/**
* Constructs a Joint with given data.
*
* @param x the x coordinate of the joint
* @param y the y coordinate of the joint
* @param confidence the confidence probability for the joint
*/
public Joint(double x, double y, double confidence) {
super(x, y);
this.confidence = confidence;
}
/**
* Returns the confidence probability for the joint.
*
* @return the confidence
*/
public double getConfidence() {
return confidence;
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/Landmark.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonObject;
import java.util.List;
/** {@code Landmark} is the container that stores the key points for landmark on a single face. */
public class Landmark extends Rectangle {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
private List<Point> points;
/**
* Constructs a {@code Landmark} using a list of points.
*
* @param x the left coordinate of the bounding rectangle
* @param y the top coordinate of the bounding rectangle
* @param width the width of the bounding rectangle
* @param height the height of the bounding rectangle
* @param points the key points for each face
*/
public Landmark(double x, double y, double width, double height, List<Point> points) {
super(x, y, width, height);
this.points = points;
}
/** {@inheritDoc} */
@Override
public Iterable<Point> getPath() {
return points;
}
/** {@inheritDoc} */
@Override
public JsonObject serialize() {
JsonObject ret = super.serialize();
ret.add("landmarks", JsonUtils.GSON.toJsonTree(points));
return ret;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/Mask.java
|
/*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.types.Shape;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* A mask with a probability for each pixel within a bounding rectangle.
*
* <p>This class is usually used to record the results of an Image Segmentation task.
*/
public class Mask extends Rectangle {
private static final long serialVersionUID = 1L;
private float[][] probDist;
private boolean fullImageMask;
/**
* Constructs a Mask with the given data.
*
* @param x the left coordinate of the bounding rectangle
* @param y the top coordinate of the bounding rectangle
* @param width the width of the bounding rectangle
* @param height the height of the bounding rectangle
* @param dist the probability distribution for each pixel in the rectangle
*/
public Mask(double x, double y, double width, double height, float[][] dist) {
this(x, y, width, height, dist, false);
}
/**
* Constructs a Mask with the given data.
*
* @param x the left coordinate of the bounding rectangle
* @param y the top coordinate of the bounding rectangle
* @param width the width of the bounding rectangle
* @param height the height of the bounding rectangle
* @param dist the probability distribution for each pixel in the rectangle
* @param fullImageMask if the mask if for full image
*/
public Mask(
double x,
double y,
double width,
double height,
float[][] dist,
boolean fullImageMask) {
super(x, y, width, height);
this.probDist = dist;
this.fullImageMask = fullImageMask;
}
/**
* Returns the probability for each pixel.
*
* @return the probability for each pixel
*/
public float[][] getProbDist() {
return probDist;
}
/**
* Returns if the mask is for full image.
*
* @return if the mask is for full image
*/
public boolean isFullImageMask() {
return fullImageMask;
}
/** {@inheritDoc} */
@Override
public JsonObject serialize() {
JsonObject ret = super.serialize();
if (fullImageMask) {
ret.add("fullImageMask", new JsonPrimitive(true));
}
ret.add("mask", JsonUtils.GSON.toJsonTree(probDist));
return ret;
}
/**
* Converts the mask tensor to a mask array.
*
* @param array the mask NDArray
* @return the mask array
*/
public static float[][] toMask(NDArray array) {
Shape maskShape = array.getShape();
int height = (int) maskShape.get(0);
int width = (int) maskShape.get(1);
float[] flattened = array.toFloatArray();
float[][] mask = new float[height][width];
for (int i = 0; i < height; i++) {
System.arraycopy(flattened, i * width, mask[i], 0, width);
}
return mask;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/Point.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.util.JsonUtils;
import java.io.Serializable;
/**
* A point representing a location in {@code (x,y)} coordinate space, specified in double precision.
*/
public class Point implements Serializable {
private static final long serialVersionUID = 1L;
private double x;
private double y;
/**
* Constructs and initializes a point at the specified {@code (x,y)} location in the coordinate
* space.
*
* @param x the X coordinate of the newly constructed {@code Point}
* @param y the Y coordinate of the newly constructed {@code Point}
*/
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Returns the X coordinate of this {@code Point} in {@code double} precision.
*
* @return the X coordinate of this {@code Point}
*/
public double getX() {
return x;
}
/**
* Returns the Y coordinate of this {@code Point} in {@code double} precision.
*
* @return the Y coordinate of this {@code Point}
*/
public double getY() {
return y;
}
/** {@inheritDoc} */
@Override
public String toString() {
return JsonUtils.GSON_COMPACT.toJson(this);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/Rectangle.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.output;
import ai.djl.util.JsonSerializable;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
/**
* A {@code Rectangle} specifies an area in a coordinate space that is enclosed by the {@code
* Rectangle} object's upper-left point {@link Point} in the coordinate space, its width, and its
* height.
*
* <p>The rectangle coordinates are usually from 0-1 and are ratios of the image size. For example,
* if you have an image width of 400 pixels and the rectangle starts at 100 pixels, you would use
* .25.
*/
public class Rectangle implements BoundingBox, JsonSerializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
private List<Point> corners;
private double width;
private double height;
/**
* Constructs a new {@code Rectangle} whose upper-left corner is specified as {@code (x,y)} and
* whose width and height are specified by the arguments of the same name.
*
* @param x the specified X coordinate (0-1)
* @param y the specified Y coordinate (0-1)
* @param width the width of the {@code Rectangle} (0-1)
* @param height the height of the {@code Rectangle} (0-1)
*/
public Rectangle(double x, double y, double width, double height) {
this(new Point(x, y), width, height);
}
/**
* Constructs a new {@code Rectangle} whose upper-left corner is specified as coordinate {@code
* point} and whose width and height are specified by the arguments of the same name.
*
* @param point the upper-left corner of the coordinate (0-1)
* @param width the width of the {@code Rectangle} (0-1)
* @param height the height of the {@code Rectangle} (0-1)
*/
public Rectangle(Point point, double width, double height) {
this.width = width;
this.height = height;
corners = new ArrayList<>(4);
corners.add(point);
corners.add(new Point(point.getX() + width, point.getY()));
corners.add(new Point(point.getX() + width, point.getY() + height));
corners.add(new Point(point.getX(), point.getY() + height));
}
/** {@inheritDoc} */
@Override
public Rectangle getBounds() {
return this;
}
/** {@inheritDoc} */
@Override
public Iterable<Point> getPath() {
return corners;
}
/** {@inheritDoc} */
@Override
public Point getPoint() {
return corners.get(0);
}
/** {@inheritDoc} */
@Override
public double getIoU(BoundingBox box) {
Rectangle rect = box.getBounds();
// computing area of each rectangles
double s1 = (width + 1) * (height + 1);
double s2 = (rect.getWidth() + 1) * (rect.getHeight() + 1);
double sumArea = s1 + s2;
// find each edge of intersect rectangle
double left = Math.max(getX(), rect.getX());
double top = Math.max(getY(), rect.getY());
double right = Math.min(getX() + getWidth(), rect.getX() + rect.getWidth());
double bottom = Math.min(getY() + getHeight(), rect.getY() + rect.getHeight());
// judge if there is a intersect
if (left > right || top > bottom) {
return 0.0;
}
double intersect = (right - left + 1) * (bottom - top + 1);
return intersect / (sumArea - intersect);
}
/**
* Returns the left x-coordinate of the Rectangle.
*
* @return the left x-coordinate of the Rectangle (0-1)
*/
public double getX() {
return getPoint().getX();
}
/**
* Returns the top y-coordinate of the Rectangle.
*
* @return the top y-coordinate of the Rectangle (0-1)
*/
public double getY() {
return getPoint().getY();
}
/**
* Returns the width of the Rectangle.
*
* @return the width of the Rectangle (0-1)
*/
public double getWidth() {
return width;
}
/**
* Returns the height of the Rectangle.
*
* @return the height of the Rectangle (0-1)
*/
public double getHeight() {
return height;
}
/**
* Returns the upper left and bottom right coordinates.
*
* @return the upper left and bottom right coordinates
*/
public double[] getCoordinates() {
Point upLeft = corners.get(0);
Point bottomRight = corners.get(2);
return new double[] {upLeft.getX(), upLeft.getY(), bottomRight.getX(), bottomRight.getY()};
}
/** {@inheritDoc} */
@Override
public JsonObject serialize() {
JsonObject ret = new JsonObject();
ret.add("rect", JsonUtils.GSON.toJsonTree(getCoordinates()));
return ret;
}
/** {@inheritDoc} */
@Override
public String toString() {
return toJson();
}
/**
* Applies nms (non-maximum suppression) to the list of rectangles.
*
* @param boxes an list of {@code Rectangle}
* @param scores a list of scores
* @param nmsThreshold the nms threshold
* @return the filtered list with the index of the original list
*/
public static List<Integer> nms(
List<Rectangle> boxes, List<Double> scores, float nmsThreshold) {
List<Integer> ret = new ArrayList<>();
PriorityQueue<Integer> pq =
new PriorityQueue<>(
50,
(lhs, rhs) -> {
// Intentionally reversed to put high confidence at the head of the
// queue.
return Double.compare(scores.get(rhs), scores.get(lhs));
});
for (int i = 0; i < boxes.size(); ++i) {
pq.add(i);
}
// do non maximum suppression
while (!pq.isEmpty()) {
// insert detection with max confidence
int[] detections = pq.stream().mapToInt(Integer::intValue).toArray();
ret.add(detections[0]);
Rectangle box = boxes.get(detections[0]);
pq.clear();
for (int i = 1; i < detections.length; i++) {
int detection = detections[i];
Rectangle location = boxes.get(detection);
if (box.boxIou(location) < nmsThreshold) {
pq.add(detection);
}
}
}
return ret;
}
private double boxIou(Rectangle other) {
double intersection = intersection(other);
double union =
getWidth() * getHeight() + other.getWidth() * other.getHeight() - intersection;
return intersection / union;
}
private double intersection(Rectangle b) {
double w =
overlap(
(getX() * 2 + getWidth()) / 2,
getWidth(),
(b.getX() * 2 + b.getWidth()) / 2,
b.getWidth());
double h =
overlap(
(getY() * 2 + getHeight()) / 2,
getHeight(),
(b.getY() * 2 + b.getHeight()) / 2,
b.getHeight());
if (w < 0 || h < 0) {
return 0;
}
return w * h;
}
private double overlap(double x1, double w1, double x2, double w2) {
double l1 = x1 - w1 / 2;
double l2 = x2 - w2 / 2;
double left = Math.max(l1, l2);
double r1 = x1 + w1 / 2;
double r2 = x2 + w2 / 2;
double right = Math.min(r1, r2);
return right - left;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/output/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains output types used in various computer vision applications. */
package ai.djl.modality.cv.output;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/CenterCrop.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that crops the center of an image. */
public class CenterCrop implements Transform {
private int width;
private int height;
/**
* Creates a {@code CenterCrop} {@link Transform} that crops to size {@code min(width, height)}.
*/
public CenterCrop() {
width = -1;
height = -1;
}
/**
* Creates a {@code CenterCrop} {@link Transform} that crops the given width and height.
*
* @param width the desired width of the cropped image
* @param height the desired height of the cropped image
*/
public CenterCrop(int width, int height) {
this.width = width;
this.height = height;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
if (width < 0) {
return NDImageUtils.centerCrop(array);
}
return NDImageUtils.centerCrop(array, width, height);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/CenterFit.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.Transform;
/** A {@link Transform} that fit the size of an image. */
public class CenterFit implements Transform {
private int width;
private int height;
/**
* Creates a {@code CenterFit} {@link Transform} that fit to the given width and height with
* given interpolation.
*
* @param width the desired width
* @param height the desired height
*/
public CenterFit(int width, int height) {
this.width = width;
this.height = height;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
Shape shape = array.getShape();
int w = (int) shape.get(1);
int h = (int) shape.get(0);
if (w > width || h > height) {
array = NDImageUtils.centerCrop(array, Math.min(w, width), Math.min(h, height));
}
int padW = width - w;
int padH = height - h;
if (padW > 0 || padH > 0) {
padW = Math.max(0, padW);
padH = Math.max(0, padH);
int padW1 = padW / 2;
int padH1 = padH / 2;
Shape padding = new Shape(0, 0, padW1, padW - padW1, padH1, padH - padH1);
array = array.pad(padding, 0);
}
return array;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/Crop.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that crops the image to a given location and size. */
public class Crop implements Transform {
private int x;
private int y;
private int width;
private int height;
/**
* Creates a {@code CenterCrop} {@link Transform}.
*
* @param x the x coordinate of the top-left corner of the crop
* @param y the y coordinate of the top-left corner of the crop
* @param width the width of the cropped image
* @param height the height of the cropped image
*/
public Crop(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.crop(array, x, y, width, height);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/Normalize.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that normalizes an image {@link NDArray} of shape CHW or NCHW. */
public class Normalize implements Transform {
private float[] mean;
private float[] std;
/**
* Creates a {@code Normalize} {@link Transform} that normalizes.
*
* @param mean the mean to normalize with for each channel
* @param std the standard deviation to normalize with for each channel
* @see NDImageUtils#normalize(NDArray, float[], float[])
*/
public Normalize(float[] mean, float[] std) {
this.mean = mean;
this.std = std;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.normalize(array, mean, std);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/OneHot.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that converts the labels {@link NDArray} to one-hot labels. */
public class OneHot implements Transform {
private int numClass;
/**
* Creates a {@code OneHot} {@link Transform} that converts the sparse label to one-hot label.
*
* @param numClass number of classes
*/
public OneHot(int numClass) {
this.numClass = numClass;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return array.oneHot(numClass);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/Pad.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.Transform;
/** A {@link Transform} that pad the image to square. */
public class Pad implements Transform {
private double value;
/**
* Constructs a new {@code Pad} instance.
*
* @param value the padding value
*/
public Pad(double value) {
this.value = value;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
Shape shape = array.getShape();
int w = (int) shape.get(1);
int h = (int) shape.get(0);
if (w == h) {
return array;
}
int max = Math.max(w, h);
int padW = max - w;
int padH = max - h;
Shape padding = new Shape(0, 0, 0, padW, 0, padH);
array = array.pad(padding, value);
return array;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomBrightness.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/**
* A {@link Transform} that randomly jitters image brightness with a factor chosen from [max(0, 1 -
* brightness), 1 + brightness].
*/
public class RandomBrightness implements Transform {
private float brightness;
/**
* Creates a {@code RandomBrightness} {@link Transform}.
*
* @param brightness the brightness factor from 0 to 1
*/
public RandomBrightness(float brightness) {
this.brightness = brightness;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.randomBrightness(array, brightness);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomColorJitter.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/**
* A {@link Transform} that randomly jitters the brightness, contrast, saturation, and hue of an
* image.
*/
public class RandomColorJitter implements Transform {
private float brightness;
private float contrast;
private float saturation;
private float hue;
/**
* Creates a {@code RandomColorJitter} {@link Transform}.
*
* @param brightness the brightness factor from 0 to 1
* @param contrast the contrast factor from 0 to 1
* @param saturation the saturation factor from 0 to 1
* @param hue the hue factor from 0 to 1
*/
public RandomColorJitter(float brightness, float contrast, float saturation, float hue) {
this.brightness = brightness;
this.contrast = contrast;
this.saturation = saturation;
this.hue = hue;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.randomColorJitter(array, brightness, contrast, saturation, hue);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomFlipLeftRight.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
import ai.djl.util.RandomUtils;
/**
* A {@link Transform} that randomly flip the input image left to right with a probability of 0.5.
*/
public class RandomFlipLeftRight implements Transform {
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
if (RandomUtils.nextFloat() > 0.5) {
array.flip(1);
}
return array;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomFlipTopBottom.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
import ai.djl.util.RandomUtils;
/**
* A {@link Transform} that randomly flip the input image top to bottom with a probability of 0.5.
*/
public class RandomFlipTopBottom implements Transform {
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
if (RandomUtils.nextFloat() > 0.5) {
array.flip(0);
}
return array;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomHue.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/**
* A {@link Transform} that randomly jitters image hue with a factor chosen from [max(0, 1 - hue), 1
* + hue].
*/
public class RandomHue implements Transform {
private float hue;
/**
* Creates a {@code RandomHue} {@link Transform}.
*
* @param hue the hue factor from 0 to 1
*/
public RandomHue(float hue) {
this.hue = hue;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.randomHue(array, hue);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/RandomResizedCrop.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that crop the input image with random scale and aspect ratio. */
public class RandomResizedCrop implements Transform {
private int width;
private int height;
private double minAreaScale;
private double maxAreaScale;
private double minAspectRatio;
private double maxAspectRatio;
/**
* Creates a {@code RandomResizedCrop} {@link Transform}.
*
* @param width the output width of the image
* @param height the output height of the image
* @param minAreaScale minimum targetArea/srcArea value
* @param maxAreaScale maximum targetArea/srcArea value
* @param minAspectRatio minimum aspect ratio
* @param maxAspectRatio maximum aspect ratio
*/
public RandomResizedCrop(
int width,
int height,
double minAreaScale,
double maxAreaScale,
double minAspectRatio,
double maxAspectRatio) {
this.width = width;
this.height = height;
this.minAreaScale = minAreaScale;
this.maxAreaScale = maxAreaScale;
this.minAspectRatio = minAspectRatio;
this.maxAspectRatio = maxAspectRatio;
}
/**
* Creates a {@code RandomResizedCrop} {@link Transform}.
*
* @param width the output width of the image
* @param height the output height of the image
*/
public RandomResizedCrop(int width, int height) {
this.width = width;
this.height = height;
this.minAreaScale = 0.08;
this.maxAreaScale = 1.0;
this.minAspectRatio = 3.0 / 4.0;
this.maxAspectRatio = 4.0 / 3.0;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.randomResizedCrop(
array, width, height, minAreaScale, maxAreaScale, minAspectRatio, maxAspectRatio);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/Resize.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/** A {@link Transform} that resizes the image. */
public class Resize implements Transform {
private int width;
private int height;
private Image.Interpolation interpolation;
/**
* Creates a {@code Resize} {@link Transform} that resizes to the given size.
*
* @param size the new size to use for both height and width
*/
public Resize(int size) {
this(size, size, Image.Interpolation.BILINEAR);
}
/**
* Creates a {@code Resize} {@link Transform} that resizes to the given width and height.
*
* @param width the desired width
* @param height the desired height
*/
public Resize(int width, int height) {
this(width, height, Image.Interpolation.BILINEAR);
}
/**
* Creates a {@code Resize} {@link Transform} that resizes to the given width and height with
* given interpolation.
*
* @param width the desired width
* @param height the desired height
* @param interpolation the desired interpolation
*/
public Resize(int width, int height, Image.Interpolation interpolation) {
this.width = width;
this.height = height;
this.interpolation = interpolation;
}
/**
* Returns the width.
*
* @return the width
*/
public int getWidth() {
return width;
}
/**
* Returns the height.
*
* @return the height
*/
public int getHeight() {
return height;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.resize(array, width, height, interpolation);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/ResizeShort.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.Transform;
/** A {@link Transform} that resizes the image and keep aspect ratio. */
public class ResizeShort implements Transform {
private int shortEdge;
private int longEdge;
private Image.Interpolation interpolation;
/**
* Creates a {@code ResizeShort} {@link Transform} that resizes to the given size.
*
* @param shortEdge the length of the short edge
*/
public ResizeShort(int shortEdge) {
this(shortEdge, -1, Image.Interpolation.BILINEAR);
}
/**
* Creates a {@code ResizeShort} {@link Transform} that resizes to the given size and given
* interpolation.
*
* @param shortEdge the length of the short edge
* @param longEdge the length of the long edge
* @param interpolation the desired interpolation
*/
public ResizeShort(int shortEdge, int longEdge, Image.Interpolation interpolation) {
this.shortEdge = shortEdge;
this.longEdge = longEdge;
this.interpolation = interpolation;
}
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
Shape shape = array.getShape();
int width = (int) shape.get(1);
int height = (int) shape.get(0);
int min = Math.min(width, height);
int max = Math.max(width, height);
int newShort;
int newLong;
if (shortEdge < 0) {
newShort = min * longEdge / max;
newLong = longEdge;
} else {
newShort = shortEdge;
newLong = max * shortEdge / min;
if (longEdge > 0 && newLong > longEdge) {
newShort = min * longEdge / max;
newLong = longEdge;
}
}
int rescaledWidth;
int rescaledHeight;
if (width > height) {
rescaledWidth = newLong;
rescaledHeight = newShort;
} else {
rescaledWidth = newShort;
rescaledHeight = newLong;
}
return NDImageUtils.resize(array, rescaledWidth, rescaledHeight, interpolation);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/ToTensor.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.transform;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.Transform;
/**
* A {@link Transform} that converts an image {@link NDArray} from preprocessing format to Neural
* Network format.
*
* @see NDImageUtils#toTensor(NDArray)
*/
public class ToTensor implements Transform {
/** {@inheritDoc} */
@Override
public NDArray transform(NDArray array) {
return NDImageUtils.toTensor(array);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/transform/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/** Contains {@link ai.djl.translate.Transform}s for working with Images. */
package ai.djl.modality.cv.transform;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/BaseImagePreProcessor.java
|
/*
* Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.Image;
import ai.djl.ndarray.NDList;
import ai.djl.translate.TranslatorContext;
/** A {@code BaseImageTranslator} that only handles pre-processing inputs. */
public class BaseImagePreProcessor extends BaseImageTranslator<Void> {
/**
* Constructs an {@code ImageTranslator} with the provided builder.
*
* @param builder the data to build with
*/
public BaseImagePreProcessor(BaseBuilder<?> builder) {
super(builder);
}
/** {@inheritDoc} */
@Override
public Void processOutput(TranslatorContext ctx, NDList list) {
return null;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Image input) {
return super.processInput(ctx, input);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/BaseImageTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.transform.CenterCrop;
import ai.djl.modality.cv.transform.CenterFit;
import ai.djl.modality.cv.transform.Normalize;
import ai.djl.modality.cv.transform.Pad;
import ai.djl.modality.cv.transform.Resize;
import ai.djl.modality.cv.transform.ResizeShort;
import ai.djl.modality.cv.transform.ToTensor;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.Batchifier;
import ai.djl.translate.Pipeline;
import ai.djl.translate.Transform;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import ai.djl.util.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Built-in {@code Translator} that provides default image pre-processing.
*
* @param <T> the output object type
*/
public abstract class BaseImageTranslator<T> implements Translator<Image, T> {
private static final float[] MEAN = {0.485f, 0.456f, 0.406f};
private static final float[] STD = {0.229f, 0.224f, 0.225f};
protected Pipeline pipeline;
private Image.Flag flag;
private Batchifier batchifier;
protected int width;
protected int height;
/**
* Constructs an ImageTranslator with the provided builder.
*
* @param builder the data to build with
*/
public BaseImageTranslator(BaseBuilder<?> builder) {
flag = builder.flag;
pipeline = builder.pipeline;
batchifier = builder.batchifier;
width = builder.width;
height = builder.height;
}
/** {@inheritDoc} */
@Override
public Batchifier getBatchifier() {
return batchifier;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Image input) {
NDArray array = input.toNDArray(ctx.getNDManager(), flag);
NDList list = pipeline.transform(new NDList(array));
Shape shape = list.get(0).getShape();
int processedWidth;
int processedHeight;
long[] dim = shape.getShape();
if (NDImageUtils.isCHW(shape)) {
processedWidth = (int) dim[dim.length - 1];
processedHeight = (int) dim[dim.length - 2];
} else {
processedWidth = (int) dim[dim.length - 2];
processedHeight = (int) dim[dim.length - 3];
}
ctx.setAttachment("width", input.getWidth());
ctx.setAttachment("height", input.getHeight());
ctx.setAttachment("processedWidth", processedWidth);
ctx.setAttachment("processedHeight", processedHeight);
return list;
}
/**
* A builder to extend for all classes extending the {@link BaseImageTranslator}.
*
* @param <T> the concrete builder type
*/
@SuppressWarnings("rawtypes")
public abstract static class BaseBuilder<T extends BaseBuilder> {
protected int width = 224;
protected int height = 224;
protected Image.Flag flag = Image.Flag.COLOR;
protected Pipeline pipeline;
protected Batchifier batchifier = Batchifier.STACK;
/**
* Sets the optional {@link ai.djl.modality.cv.Image.Flag} (default is {@link
* Image.Flag#COLOR}).
*
* @param flag the color mode for the images
* @return this builder
*/
public T optFlag(Image.Flag flag) {
this.flag = flag;
return self();
}
/**
* Sets the {@link Pipeline} to use for pre-processing the image.
*
* @param pipeline the pre-processing pipeline
* @return this builder
*/
public T setPipeline(Pipeline pipeline) {
this.pipeline = pipeline;
return self();
}
/**
* Sets the image size.
*
* @param width the image width
* @param height the image height
* @return this builder
*/
public T setImageSize(int width, int height) {
this.width = width;
this.height = height;
return self();
}
/**
* Adds the {@link Transform} to the {@link Pipeline} use for pre-processing the image.
*
* @param transform the {@link Transform} to be added
* @return this builder
*/
public T addTransform(Transform transform) {
if (pipeline == null) {
pipeline = new Pipeline();
}
pipeline.add(transform);
return self();
}
/**
* Sets the {@link Batchifier} for the {@link Translator}.
*
* @param batchifier the {@link Batchifier} to be set
* @return this builder
*/
public T optBatchifier(Batchifier batchifier) {
this.batchifier = batchifier;
return self();
}
protected abstract T self();
protected void validate() {
if (pipeline == null) {
throw new IllegalArgumentException("pipeline is required.");
}
}
protected void configPreProcess(Map<String, ?> arguments) {
if (pipeline == null) {
pipeline = new Pipeline();
}
width = ArgumentsUtil.intValue(arguments, "width", 224);
height = ArgumentsUtil.intValue(arguments, "height", 224);
if (arguments.containsKey("flag")) {
flag = Image.Flag.valueOf(arguments.get("flag").toString());
}
String pad = ArgumentsUtil.stringValue(arguments, "pad", "false");
if ("true".equals(pad)) {
addTransform(new Pad(0));
} else if (!"false".equals(pad)) {
double padding = Double.parseDouble(pad);
addTransform(new Pad(padding));
}
String resize = ArgumentsUtil.stringValue(arguments, "resize", "false");
if ("true".equals(resize)) {
addTransform(new Resize(width, height));
} else if (!"false".equals(resize)) {
String[] tokens = resize.split("\\s*,\\s*");
int w = (int) Double.parseDouble(tokens[0]);
int h;
Image.Interpolation interpolation;
if (tokens.length > 1) {
h = (int) Double.parseDouble(tokens[1]);
} else {
h = w;
}
if (tokens.length > 2) {
interpolation = Image.Interpolation.valueOf(tokens[2]);
} else {
interpolation = Image.Interpolation.BILINEAR;
}
addTransform(new Resize(w, h, interpolation));
}
String resizeShort = ArgumentsUtil.stringValue(arguments, "resizeShort", "false");
if ("true".equals(resizeShort)) {
int shortEdge = Math.max(width, height);
addTransform(new ResizeShort(shortEdge));
} else if (!"false".equals(resizeShort)) {
String[] tokens = resizeShort.split("\\s*,\\s*");
int shortEdge = (int) Double.parseDouble(tokens[0]);
int longEdge;
Image.Interpolation interpolation;
if (tokens.length > 1) {
longEdge = (int) Double.parseDouble(tokens[1]);
} else {
longEdge = -1;
}
if (tokens.length > 2) {
interpolation = Image.Interpolation.valueOf(tokens[2]);
} else {
interpolation = Image.Interpolation.BILINEAR;
}
addTransform(new ResizeShort(shortEdge, longEdge, interpolation));
}
if (ArgumentsUtil.booleanValue(arguments, "centerCrop", false)) {
addTransform(new CenterCrop(width, height));
}
if (ArgumentsUtil.booleanValue(arguments, "centerFit")) {
addTransform(new CenterFit(width, height));
}
if (ArgumentsUtil.booleanValue(arguments, "toTensor", true)) {
addTransform(new ToTensor());
}
String normalize = ArgumentsUtil.stringValue(arguments, "normalize", "false");
if ("true".equals(normalize)) {
addTransform(new Normalize(MEAN, STD));
} else if (!"false".equals(normalize)) {
String[] tokens = normalize.split("\\s*,\\s*");
if (tokens.length != 6) {
throw new IllegalArgumentException("Invalid normalize value: " + normalize);
}
float[] mean = {
Float.parseFloat(tokens[0]),
Float.parseFloat(tokens[1]),
Float.parseFloat(tokens[2])
};
float[] std = {
Float.parseFloat(tokens[3]),
Float.parseFloat(tokens[4]),
Float.parseFloat(tokens[5])
};
addTransform(new Normalize(mean, std));
}
String range = (String) arguments.get("range");
if ("0,1".equals(range)) {
addTransform(a -> a.div(255f));
} else if ("-1,1".equals(range)) {
addTransform(a -> a.div(128f).sub(1));
}
if (arguments.containsKey("batchifier")) {
batchifier = Batchifier.fromString((String) arguments.get("batchifier"));
}
}
protected void configPostProcess(Map<String, ?> arguments) {}
}
/** A Builder to construct a {@code ImageClassificationTranslator}. */
@SuppressWarnings("rawtypes")
public abstract static class ClassificationBuilder<T extends BaseBuilder>
extends BaseBuilder<T> {
protected SynsetLoader synsetLoader;
/**
* Sets the name of the synset file listing the potential classes for an image.
*
* @param synsetArtifactName a file listing the potential classes for an image
* @return the builder
*/
public T optSynsetArtifactName(String synsetArtifactName) {
synsetLoader = new SynsetLoader(synsetArtifactName);
return self();
}
/**
* Sets the URL of the synset file.
*
* @param synsetUrl the URL of the synset file
* @return the builder
*/
public T optSynsetUrl(String synsetUrl) {
try {
this.synsetLoader = new SynsetLoader(new URL(synsetUrl));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Invalid synsetUrl: " + synsetUrl, e);
}
return self();
}
/**
* Sets the potential classes for an image.
*
* @param synset the potential classes for an image
* @return the builder
*/
public T optSynset(List<String> synset) {
synsetLoader = new SynsetLoader(synset);
return self();
}
/** {@inheritDoc} */
@Override
protected void validate() {
super.validate();
if (synsetLoader == null) {
synsetLoader = new SynsetLoader("synset.txt");
}
boolean hasCrop = false;
boolean sizeMismatch = false;
for (Transform transform : pipeline.getTransforms()) {
if (transform instanceof Resize) {
Resize resize = (Resize) transform;
if (width != resize.getWidth() || height != resize.getHeight()) {
sizeMismatch = true;
}
} else if (transform instanceof CenterCrop || transform instanceof CenterFit) {
hasCrop = true;
}
}
if (sizeMismatch && !hasCrop) {
throw new IllegalArgumentException("resized image has mismatched target size");
}
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
String synset = (String) arguments.get("synset");
if (synset != null) {
optSynset(Arrays.asList(synset.split(",")));
}
String synsetUrl = (String) arguments.get("synsetUrl");
if (synsetUrl != null) {
optSynsetUrl(synsetUrl);
}
String synsetFileName = (String) arguments.get("synsetFileName");
if (synsetFileName != null) {
optSynsetArtifactName(synsetFileName);
}
}
}
protected static final class SynsetLoader {
private String synsetFileName;
private URL synsetUrl;
private List<String> synset;
public SynsetLoader(List<String> synset) {
this.synset = synset;
}
public SynsetLoader(URL synsetUrl) {
this.synsetUrl = synsetUrl;
}
public SynsetLoader(String synsetFileName) {
this.synsetFileName = synsetFileName;
}
public List<String> load(Model model) throws IOException {
if (synset != null) {
return synset;
} else if (synsetUrl != null) {
try (InputStream is = synsetUrl.openStream()) {
return Utils.readLines(is);
}
}
return model.getArtifact(synsetFileName, Utils::readLines);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/BaseImageTranslatorFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.translator.wrapper.FileImagePreProcessor;
import ai.djl.modality.cv.translator.wrapper.InputStreamImagePreProcessor;
import ai.djl.modality.cv.translator.wrapper.StringImagePreProcessor;
import ai.djl.modality.cv.translator.wrapper.UrlImagePreProcessor;
import ai.djl.translate.ExpansionTranslatorFactory;
import ai.djl.translate.PreProcessor;
import ai.djl.util.Pair;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* A helper to create a {@link ai.djl.translate.TranslatorFactory} with the {@link
* BaseImageTranslator}.
*
* @param <O> the output type for the {@link ai.djl.translate.TranslatorFactory}.
*/
public abstract class BaseImageTranslatorFactory<O> extends ExpansionTranslatorFactory<Image, O> {
/** {@inheritDoc} */
@Override
protected Map<Type, Function<PreProcessor<Image>, PreProcessor<?>>>
getPreprocessorExpansions() {
Map<Type, Function<PreProcessor<Image>, PreProcessor<?>>> expansions =
new ConcurrentHashMap<>();
expansions.put(Path.class, FileImagePreProcessor::new);
expansions.put(URL.class, UrlImagePreProcessor::new);
expansions.put(String.class, StringImagePreProcessor::new);
expansions.put(InputStream.class, InputStreamImagePreProcessor::new);
return expansions;
}
/** {@inheritDoc} */
@Override
protected Map<Pair<Type, Type>, TranslatorExpansion<Image, O>> getExpansions() {
Map<Pair<Type, Type>, TranslatorExpansion<Image, O>> expansions = new ConcurrentHashMap<>();
expansions.put(new Pair<>(Input.class, Output.class), ImageServingTranslator::new);
return expansions;
}
/** {@inheritDoc} */
@Override
public Class<Image> getBaseInputType() {
return Image.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/BigGANTranslator.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.NoBatchifyTranslator;
import ai.djl.translate.TranslatorContext;
/** Built-in {@code Translator} that provides preprocessing and postprocessing for BigGAN. */
public final class BigGANTranslator implements NoBatchifyTranslator<int[], Image[]> {
private static final int NUMBER_OF_CATEGORIES = 1000;
private static final int SEED_COLUMN_SIZE = 128;
private float truncation;
/**
* Constructs a translator for BigGAN.
*
* @param truncation value used to scale the normal seed for BigGAN
*/
public BigGANTranslator(float truncation) {
this.truncation = truncation;
}
/** {@inheritDoc} */
@Override
public Image[] processOutput(TranslatorContext ctx, NDList list) {
NDArray output = list.get(0).duplicate().addi(1).muli(128).clip(0, 255);
int sampleSize = (int) output.getShape().get(0);
Image[] images = new Image[sampleSize];
for (int i = 0; i < sampleSize; ++i) {
images[i] = ImageFactory.getInstance().fromNDArray(output.get(i));
}
return images;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, int[] input) throws Exception {
NDManager manager = ctx.getNDManager();
NDArray classes = manager.create(input).oneHot(NUMBER_OF_CATEGORIES);
NDArray seed =
manager.truncatedNormal(new Shape(input.length, SEED_COLUMN_SIZE)).muli(truncation);
return new NDList(seed, classes, manager.create(truncation));
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/BigGANTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import ai.djl.util.Pair;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/** A {@link TranslatorFactory} that creates a {@link BigGANTranslator} instance. */
public class BigGANTranslatorFactory implements TranslatorFactory, Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
public Set<Pair<Type, Type>> getSupportedTypes() {
return Collections.singleton(new Pair<>(int[].class, Image[].class));
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <I, O> Translator<I, O> newInstance(
Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) {
if (!isSupported(input, output)) {
throw new IllegalArgumentException("Unsupported input/output types.");
}
float truncation = ArgumentsUtil.floatValue(arguments, "truncation", 0.5f);
return (Translator<I, O>) new BigGANTranslator(truncation);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ImageClassificationTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.Classifications;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.TranslatorContext;
import ai.djl.translate.TranslatorOptions;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/** A generic {@link ai.djl.translate.Translator} for Image Classification tasks. */
public class ImageClassificationTranslator extends BaseImageTranslator<Classifications> {
private SynsetLoader synsetLoader;
private boolean applySoftmax;
private int topK;
private List<String> classes;
/**
* Constructs an Image Classification using {@link Builder}.
*
* @param builder the data to build with
*/
public ImageClassificationTranslator(Builder builder) {
super(builder);
this.synsetLoader = builder.synsetLoader;
this.applySoftmax = builder.applySoftmax;
this.topK = builder.topK;
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws IOException {
if (classes == null) {
classes = synsetLoader.load(ctx.getModel());
}
}
/** {@inheritDoc} */
@Override
public Classifications processOutput(TranslatorContext ctx, NDList list) {
NDArray probabilitiesNd = list.singletonOrThrow();
if (applySoftmax) {
probabilitiesNd = probabilitiesNd.softmax(0);
}
return new Classifications(classes, probabilitiesNd, topK);
}
/** {@inheritDoc} */
@Override
public TranslatorOptions getExpansions() {
return new ImageClassificationTranslatorFactory().withTranslator(this);
}
/**
* Creates a builder to build a {@code ImageClassificationTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code ImageClassificationTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** A Builder to construct a {@code ImageClassificationTranslator}. */
public static class Builder extends ClassificationBuilder<Builder> {
private boolean applySoftmax;
private int topK = 5;
Builder() {}
/**
* Set the topK number of classes to be displayed.
*
* @param topK the number of top classes to return
* @return the builder
*/
public Builder optTopK(int topK) {
this.topK = topK;
return this;
}
/**
* Sets whether to apply softmax when processing output. Some models already include softmax
* in the last layer, so don't apply softmax when processing model output.
*
* @param applySoftmax boolean whether to apply softmax
* @return the builder
*/
public Builder optApplySoftmax(boolean applySoftmax) {
this.applySoftmax = applySoftmax;
return this;
}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
super.configPostProcess(arguments);
applySoftmax = ArgumentsUtil.booleanValue(arguments, "applySoftmax");
topK = ArgumentsUtil.intValue(arguments, "topK", 5);
}
/**
* Builds the {@link ImageClassificationTranslator} with the provided data.
*
* @return an {@link ImageClassificationTranslator}
*/
public ImageClassificationTranslator build() {
validate();
return new ImageClassificationTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ImageClassificationTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.Classifications;
import ai.djl.modality.cv.Image;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** A {@link TranslatorFactory} that creates an {@link ImageClassificationTranslator}. */
public class ImageClassificationTranslatorFactory
extends BaseImageTranslatorFactory<Classifications> implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, Classifications> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return ImageClassificationTranslator.builder(arguments).build();
}
/** {@inheritDoc} */
@Override
public Class<Classifications> getBaseOutputType() {
return Classifications.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ImageFeatureExtractor.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.DataType;
import ai.djl.translate.TranslatorContext;
import java.util.Map;
/**
* A generic {@link ai.djl.translate.Translator} for Image Classification feature extraction tasks.
*/
public class ImageFeatureExtractor extends BaseImageTranslator<float[]> {
/**
* Constructs an Image Classification using {@link Builder}.
*
* @param builder the data to build with
*/
ImageFeatureExtractor(Builder builder) {
super(builder);
}
/** {@inheritDoc} */
@Override
public float[] processOutput(TranslatorContext ctx, NDList list) {
return list.get(0).toType(DataType.FLOAT32, false).toFloatArray();
}
/**
* Creates a builder to build a {@code ImageFeatureExtractor}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code ImageFeatureExtractor} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
return builder;
}
/** A Builder to construct a {@code ImageFeatureExtractor}. */
public static class Builder extends BaseBuilder<Builder> {
Builder() {}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/**
* Builds the {@link ImageFeatureExtractor} with the provided data.
*
* @return an {@link ImageFeatureExtractor}
*/
public ImageFeatureExtractor build() {
validate();
return new ImageFeatureExtractor(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ImageFeatureExtractorFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** A {@link TranslatorFactory} that creates an {@link ImageClassificationTranslator}. */
public class ImageFeatureExtractorFactory extends BaseImageTranslatorFactory<float[]>
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, float[]> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return ImageFeatureExtractor.builder(arguments).build();
}
/** {@inheritDoc} */
@Override
public Class<float[]> getBaseOutputType() {
return float[].class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ImageServingTranslator.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.ndarray.BytesSupplier;
import ai.djl.ndarray.NDList;
import ai.djl.translate.Batchifier;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import ai.djl.util.JsonSerializable;
import ai.djl.util.JsonUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/** A {@link Translator} that can handle generic CV {@link Input} and {@link Output}. */
public class ImageServingTranslator implements Translator<Input, Output> {
private Translator<Image, ?> translator;
private ImageFactory factory;
/**
* Constructs a new {@code ImageServingTranslator} instance.
*
* @param translator a {@code Translator} processes Image input
*/
public ImageServingTranslator(Translator<Image, ?> translator) {
this.translator = translator;
factory = ImageFactory.getInstance();
}
/** {@inheritDoc} */
@Override
public Batchifier getBatchifier() {
return translator.getBatchifier();
}
/** {@inheritDoc} */
@Override
public Output processOutput(TranslatorContext ctx, NDList list) throws Exception {
Output output = new Output();
Object obj = translator.processOutput(ctx, list);
if (obj instanceof JsonSerializable) {
output.add((JsonSerializable) obj);
output.addProperty("Content-Type", "application/json");
} else if (obj instanceof Image) {
Image img = (Image) obj;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
img.save(bos, "png");
output.add(bos.toByteArray());
}
output.addProperty("Content-Type", "image/png");
} else {
output.add(BytesSupplier.wrapAsJson(obj));
output.addProperty("Content-Type", "application/json");
}
return output;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Input input) throws Exception {
BytesSupplier data = input.getData();
try {
if (data == null) {
throw new TranslateException("Input data is empty.");
}
String contentType = input.getProperty("Content-Type", null);
if (contentType != null) {
int pos = contentType.indexOf(';');
if (pos > 0) {
contentType = contentType.substring(0, pos);
}
}
Image image;
if ("application/json".equalsIgnoreCase(contentType)) {
try {
JsonElement element =
JsonUtils.GSON.fromJson(data.getAsString(), JsonElement.class);
if (element == null || !element.isJsonObject()) {
throw new TranslateException("Invalid JsonObject input.");
}
JsonObject obj = element.getAsJsonObject();
JsonPrimitive url = obj.getAsJsonPrimitive("image_url");
if (url == null) {
throw new TranslateException("Missing \"image_url\" in json.");
}
image = factory.fromUrl(url.getAsString());
} catch (JsonParseException e) {
throw new TranslateException("Input is not a valid json.", e);
}
} else {
image = factory.fromInputStream(new ByteArrayInputStream(data.getAsBytes()));
}
return translator.processInput(ctx, image);
} catch (IOException e) {
throw new TranslateException("Input is not an Image data type", e);
}
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws Exception {
translator.prepare(ctx);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/InstanceSegmentationTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Mask;
import ai.djl.modality.cv.transform.ResizeShort;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.TranslatorContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A {@link BaseImageTranslator} that post-process the {@link NDArray} into {@link DetectedObjects}
* with boundaries at the detailed pixel level.
*/
public class InstanceSegmentationTranslator extends BaseImageTranslator<DetectedObjects> {
private SynsetLoader synsetLoader;
private float threshold;
private List<String> classes;
/**
* Creates the Instance Segmentation translator from the given builder.
*
* @param builder the builder for the translator
*/
public InstanceSegmentationTranslator(Builder builder) {
super(builder);
this.synsetLoader = builder.synsetLoader;
this.threshold = builder.threshold;
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws IOException {
if (classes == null) {
classes = synsetLoader.load(ctx.getModel());
}
}
/** {@inheritDoc} */
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
int rescaledWidth = (Integer) ctx.getAttachment("processedWidth");
int rescaledHeight = (Integer) ctx.getAttachment("processedHeight");
float[] ids = list.get(0).toFloatArray();
float[] scores = list.get(1).toFloatArray();
NDArray boundingBoxes = list.get(2);
NDArray masks = list.get(3);
List<String> retNames = new ArrayList<>();
List<Double> retProbs = new ArrayList<>();
List<BoundingBox> retBB = new ArrayList<>();
for (int i = 0; i < ids.length; ++i) {
int classId = (int) ids[i];
double probability = scores[i];
if (classId >= 0 && probability > threshold) {
if (classId >= classes.size()) {
throw new AssertionError("Unexpected index: " + classId);
}
String className = classes.get(classId);
float[] box = boundingBoxes.get(i).toFloatArray();
double x = box[0] / rescaledWidth;
double y = box[1] / rescaledHeight;
double w = box[2] / rescaledWidth - x;
double h = box[3] / rescaledHeight - y;
// Reshape mask to actual image bounding box shape.
NDArray array = masks.get(i);
float[][] maskFloat = Mask.toMask(array);
Mask mask = new Mask(x, y, w, h, maskFloat);
retNames.add(className);
retProbs.add(probability);
retBB.add(mask);
}
}
return new DetectedObjects(retNames, retProbs, retBB);
}
/**
* Creates a builder to build a {@code InstanceSegmentationTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code InstanceSegmentationTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for Instance Segmentation translator. */
public static class Builder extends ClassificationBuilder<Builder> {
float threshold = 0.3f;
int shortEdge = 600;
int maxEdge = 1000;
Builder() {}
/**
* Sets the threshold for prediction accuracy.
*
* <p>Predictions below the threshold will be dropped.
*
* @param threshold the threshold for prediction accuracy
* @return the builder
*/
public Builder optThreshold(float threshold) {
this.threshold = threshold;
return this;
}
/**
* Sets the shorter edge length of the rescaled image.
*
* @param shortEdge the length of the short edge
* @return the builder
*/
public Builder optShortEdge(int shortEdge) {
this.shortEdge = shortEdge;
return this;
}
/**
* Sets the maximum edge length of the rescaled image.
*
* @param maxEdge the length of the longest edge
* @return the builder
*/
public Builder optMaxEdge(int maxEdge) {
this.maxEdge = maxEdge;
return this;
}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
super.configPostProcess(arguments);
threshold = ArgumentsUtil.floatValue(arguments, "threshold", 0.3f);
shortEdge = ArgumentsUtil.intValue(arguments, "shortEdge", 600);
maxEdge = ArgumentsUtil.intValue(arguments, "maxEdge", 1000);
}
/**
* Builds the translator.
*
* @return the new translator
*/
public InstanceSegmentationTranslator build() {
validate();
ResizeShort resize = new ResizeShort(shortEdge, maxEdge, Image.Interpolation.BILINEAR);
pipeline.insert(0, null, resize);
return new InstanceSegmentationTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/InstanceSegmentationTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** A {@link TranslatorFactory} that creates a {@link InstanceSegmentationTranslator} instance. */
public class InstanceSegmentationTranslatorFactory extends ObjectDetectionTranslatorFactory
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, DetectedObjects> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return InstanceSegmentationTranslator.builder(arguments).build();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ObjectDetectionTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.ndarray.NDArray;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.TranslatorContext;
import java.util.List;
import java.util.Map;
/**
* A {@link BaseImageTranslator} that post-process the {@link NDArray} into {@link DetectedObjects}
* with boundaries.
*/
public abstract class ObjectDetectionTranslator extends BaseImageTranslator<DetectedObjects> {
protected float threshold;
private SynsetLoader synsetLoader;
protected List<String> classes;
protected boolean applyRatio;
protected boolean removePadding;
/**
* Creates the {@link ObjectDetectionTranslator} from the given builder.
*
* @param builder the builder for the translator
*/
protected ObjectDetectionTranslator(ObjectDetectionBuilder<?> builder) {
super(builder);
this.threshold = builder.threshold;
this.synsetLoader = builder.synsetLoader;
this.applyRatio = builder.applyRatio;
this.removePadding = builder.removePadding;
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws Exception {
if (classes == null) {
classes = synsetLoader.load(ctx.getModel());
}
}
/** The base builder for the object detection translator. */
@SuppressWarnings("rawtypes")
public abstract static class ObjectDetectionBuilder<T extends ObjectDetectionBuilder>
extends ClassificationBuilder<T> {
protected float threshold = 0.2f;
protected boolean applyRatio;
protected boolean removePadding;
/**
* Sets the threshold for prediction accuracy.
*
* <p>Predictions below the threshold will be dropped.
*
* @param threshold the threshold for the prediction accuracy
* @return this builder
*/
public T optThreshold(float threshold) {
this.threshold = threshold;
return self();
}
/**
* Determine Whether to divide output object width/height on the inference result. Default
* false.
*
* <p>DetectedObject value should always bring a ratio based on the width/height instead of
* actual width/height. Most of the model will produce ratio as the inference output. This
* function is aimed to cover those who produce the pixel value. Make this to true to divide
* the width/height in postprocessing in order to get ratio in detectedObjects.
*
* @param value whether to apply ratio
* @return this builder
*/
public T optApplyRatio(boolean value) {
this.applyRatio = value;
return self();
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
super.configPostProcess(arguments);
if (ArgumentsUtil.booleanValue(arguments, "optApplyRatio")
|| ArgumentsUtil.booleanValue(arguments, "applyRatio")) {
optApplyRatio(true);
}
threshold = ArgumentsUtil.floatValue(arguments, "threshold", 0.2f);
String centerFit = ArgumentsUtil.stringValue(arguments, "centerFit", "false");
removePadding = "true".equals(centerFit);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ObjectDetectionTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.TranslatorFactory;
/**
* An abstract {@link TranslatorFactory} that creates a {@link ObjectDetectionTranslator} instance.
*/
public abstract class ObjectDetectionTranslatorFactory
extends BaseImageTranslatorFactory<DetectedObjects> {
/** {@inheritDoc} */
@Override
public Class<DetectedObjects> getBaseOutputType() {
return DetectedObjects.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/Sam2ServingTranslator.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.modality.cv.translator.Sam2Translator.Sam2Input;
import ai.djl.ndarray.BytesSupplier;
import ai.djl.ndarray.NDList;
import ai.djl.translate.Batchifier;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import org.apache.commons.codec.binary.Base64OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
/** A {@link Translator} that can serve SAM2 model. */
public class Sam2ServingTranslator implements Translator<Input, Output> {
private Sam2Translator translator;
/**
* Constructs a new {@code Sam2ServingTranslator} instance.
*
* @param translator a {@code Sam2Translator}
*/
public Sam2ServingTranslator(Sam2Translator translator) {
this.translator = translator;
}
/** {@inheritDoc} */
@Override
public Batchifier getBatchifier() {
return translator.getBatchifier();
}
/** {@inheritDoc} */
@Override
public Output processOutput(TranslatorContext ctx, NDList list) throws IOException {
Output output = new Output();
Sam2Input sam2 = (Sam2Input) ctx.getAttachment("input");
output.addProperty("Content-Type", "application/json");
DetectedObjects detection = translator.processOutput(ctx, list);
Map<String, Object> ret = new LinkedHashMap<>(); // NOPMD
ret.put("result", detection);
if (sam2.isVisualize()) {
Image img = sam2.getImage();
img.drawBoundingBoxes(detection, 0.8f);
img.drawMarks(sam2.getPoints());
for (Rectangle rect : sam2.getBoxes()) {
img.drawRectangle(rect, 0xff0000, 6);
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write("data:image/png;base64,".getBytes(StandardCharsets.UTF_8));
Base64OutputStream bos = new Base64OutputStream(os, true, 0, null);
img.save(bos, "png");
bos.close();
os.close();
ret.put("image", os.toString(StandardCharsets.UTF_8.name()));
}
output.add(BytesSupplier.wrapAsJson(ret));
return output;
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Input input) throws Exception {
BytesSupplier data = input.getData();
try {
if (data == null) {
throw new TranslateException("Input data is empty.");
}
Sam2Input sam2 = Sam2Input.fromJson(data.getAsString());
ctx.setAttachment("input", sam2);
return translator.processInput(ctx, sam2);
} catch (IOException e) {
throw new TranslateException("Input is not an Image data type", e);
}
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws Exception {
translator.prepare(ctx);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/Sam2Translator.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.ModelException;
import ai.djl.inference.Predictor;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Mask;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.modality.cv.transform.Normalize;
import ai.djl.modality.cv.transform.Resize;
import ai.djl.modality.cv.transform.ToTensor;
import ai.djl.modality.cv.translator.Sam2Translator.Sam2Input;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.NoBatchifyTranslator;
import ai.djl.translate.NoopTranslator;
import ai.djl.translate.Pipeline;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import ai.djl.util.JsonUtils;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/** A {@link Translator} that handles mask generation task. */
public class Sam2Translator implements NoBatchifyTranslator<Sam2Input, DetectedObjects> {
private static final float[] MEAN = {0.485f, 0.456f, 0.406f};
private static final float[] STD = {0.229f, 0.224f, 0.225f};
private Pipeline pipeline;
private Predictor<NDList, NDList> predictor;
private String encoderPath;
private String encodeMethod;
/** Constructs a {@code Sam2Translator} instance. */
public Sam2Translator(Builder builder) {
pipeline = new Pipeline();
pipeline.add(new Resize(1024, 1024));
pipeline.add(new ToTensor());
pipeline.add(new Normalize(MEAN, STD));
this.encoderPath = builder.encoderPath;
this.encodeMethod = builder.encodeMethod;
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws IOException, ModelException {
if (encoderPath == null) {
// PyTorch model
if (encodeMethod != null) {
Model model = ctx.getModel();
predictor = model.newPredictor(new NoopTranslator(null));
model.getNDManager().attachInternal(NDManager.nextUid(), predictor);
}
return;
}
Model model = ctx.getModel();
Path path = Paths.get(encoderPath);
if (!path.isAbsolute() && Files.notExists(path)) {
path = model.getModelPath().resolve(encoderPath);
}
if (!Files.exists(path)) {
throw new IOException("encoder model not found: " + encoderPath);
}
NDManager manager = ctx.getNDManager();
Model encoder = manager.getEngine().newModel("encoder", manager.getDevice());
encoder.load(path);
predictor = encoder.newPredictor(new NoopTranslator(null));
model.getNDManager().attachInternal(NDManager.nextUid(), predictor);
model.getNDManager().attachInternal(NDManager.nextUid(), encoder);
}
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Sam2Input input) throws Exception {
Image image = input.getImage();
int width = image.getWidth();
int height = image.getHeight();
ctx.setAttachment("width", width);
ctx.setAttachment("height", height);
float[] buf = input.toLocationArray(width, height);
NDManager manager = ctx.getNDManager();
NDArray array = image.toNDArray(manager, Image.Flag.COLOR);
array = pipeline.transform(new NDList(array)).get(0).expandDims(0);
NDArray locations = manager.create(buf, new Shape(1, buf.length / 2, 2));
NDArray labels = manager.create(input.getLabels());
if (predictor == null) {
return new NDList(array, locations, labels);
}
NDList embeddings;
if (encodeMethod == null) {
embeddings = predictor.predict(new NDList(array));
} else {
NDArray placeholder = manager.create("");
placeholder.setName("module_method:" + encodeMethod);
embeddings = predictor.predict(new NDList(placeholder, array));
}
NDArray mask = manager.zeros(new Shape(1, 1, 256, 256));
NDArray hasMask = manager.zeros(new Shape(1));
for (NDArray arr : embeddings) {
arr.setName(null);
}
return new NDList(
embeddings.get(2),
embeddings.get(0),
embeddings.get(1),
locations,
labels,
mask,
hasMask);
}
/** {@inheritDoc} */
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
NDArray logits = list.get(0);
NDArray scores = list.get(1).squeeze(0);
long best = scores.argMax().getLong();
int width = (Integer) ctx.getAttachment("width");
int height = (Integer) ctx.getAttachment("height");
long[] size = {height, width};
int mode = Image.Interpolation.BILINEAR.ordinal();
logits = logits.getNDArrayInternal().interpolation(size, mode, false);
NDArray masks = logits.gt(0f).squeeze(0);
float[][] dist = Mask.toMask(masks.get(best).toType(DataType.FLOAT32, true));
Mask mask = new Mask(0, 0, width, height, dist, true);
double probability = scores.getFloat(best);
List<String> classes = Collections.singletonList("");
List<Double> probabilities = Collections.singletonList(probability);
List<BoundingBox> boxes = Collections.singletonList(mask);
return new DetectedObjects(classes, probabilities, boxes);
}
/**
* Creates a builder to build a {@code Sam2Translator}.
*
* @return a new builder
*/
public static Builder builder() {
return builder(Collections.emptyMap());
}
/**
* Creates a builder to build a {@code Sam2Translator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
return new Builder(arguments);
}
/** The builder for Sam2Translator. */
public static class Builder {
String encoderPath;
String encodeMethod;
Builder(Map<String, ?> arguments) {
encoderPath = ArgumentsUtil.stringValue(arguments, "encoder");
encodeMethod = ArgumentsUtil.stringValue(arguments, "encode_method");
}
/**
* Sets the encoder model path.
*
* @param encoderPath the encoder model path
* @return the builder
*/
public Builder optEncoderPath(String encoderPath) {
this.encoderPath = encoderPath;
return this;
}
/**
* Sets the module name for encode method.
*
* @param encodeMethod the module name for encode method
* @return the builder
*/
public Builder optEncodeMethod(String encodeMethod) {
this.encodeMethod = encodeMethod;
return this;
}
/**
* Builds the translator.
*
* @return the new translator
*/
public Sam2Translator build() {
return new Sam2Translator(this);
}
}
/** A class represents the segment anything input. */
public static final class Sam2Input {
private Image image;
private Point[] points;
private int[] labels;
private boolean visualize;
/**
* Constructs a {@code Sam2Input} instance.
*
* @param image the image
* @param points the locations on the image
* @param labels the labels for the locations (0: background, 1: foreground)
*/
public Sam2Input(Image image, Point[] points, int[] labels) {
this(image, points, labels, false);
}
/**
* Constructs a {@code Sam2Input} instance.
*
* @param image the image
* @param points the locations on the image
* @param labels the labels for the locations (0: background, 1: foreground)
* @param visualize true if output visualized image
*/
public Sam2Input(Image image, Point[] points, int[] labels, boolean visualize) {
this.image = image;
this.points = points;
this.labels = labels;
this.visualize = visualize;
}
/**
* Returns the image.
*
* @return the image
*/
public Image getImage() {
return image;
}
/**
* Returns {@code true} if output visualized image.
*
* @return {@code true} if output visualized image
*/
public boolean isVisualize() {
return visualize;
}
/**
* Returns the locations.
*
* @return the locations
*/
public List<Point> getPoints() {
List<Point> list = new ArrayList<>();
for (int i = 0; i < labels.length; ++i) {
if (labels[i] < 2) {
list.add(points[i]);
}
}
return list;
}
/**
* Returns the box.
*
* @return the box
*/
public List<Rectangle> getBoxes() {
List<Rectangle> list = new ArrayList<>();
for (int i = 0; i < labels.length; ++i) {
if (labels[i] == 2) {
double width = points[i + 1].getX() - points[i].getX();
double height = points[i + 1].getY() - points[i].getY();
list.add(new Rectangle(points[i], width, height));
}
}
return list;
}
float[] toLocationArray(int width, int height) {
float[] ret = new float[points.length * 2];
int i = 0;
for (Point point : points) {
ret[i++] = (float) point.getX() / width * 1024;
ret[i++] = (float) point.getY() / height * 1024;
}
return ret;
}
float[][] getLabels() {
float[][] buf = new float[1][labels.length];
for (int i = 0; i < labels.length; ++i) {
buf[0][i] = labels[i];
}
return buf;
}
/**
* Constructs a {@code Sam2Input} instance from json string.
*
* @param input the json input
* @return a {@code Sam2Input} instance
* @throws IOException if failed to load the image
*/
public static Sam2Input fromJson(String input) throws IOException {
Prompt prompt = JsonUtils.GSON.fromJson(input, Prompt.class);
if (prompt.image == null) {
throw new IllegalArgumentException("Missing image_url value");
}
if (prompt.prompt == null || prompt.prompt.length == 0) {
throw new IllegalArgumentException("Missing prompt value");
}
Image image = ImageFactory.getInstance().fromUrl(prompt.image);
Builder builder = builder(image);
if (prompt.visualize) {
builder.visualize();
}
for (Location location : prompt.prompt) {
int[] data = location.data;
if ("point".equals(location.type)) {
builder.addPoint(data[0], data[1], location.label);
} else if ("rectangle".equals(location.type)) {
builder.addBox(data[0], data[1], data[2], data[3]);
}
}
return builder.build();
}
/**
* Creates a builder to build a {@code Sam2Input} with the image.
*
* @param image the image
* @return a new builder
*/
public static Builder builder(Image image) {
return new Builder(image);
}
/** The builder for {@code Sam2Input}. */
public static final class Builder {
private Image image;
private List<Point> points;
private List<Integer> labels;
private boolean visualize;
Builder(Image image) {
this.image = image;
points = new ArrayList<>();
labels = new ArrayList<>();
}
/**
* Adds a point to the {@code Sam2Input}.
*
* @param x the X coordinate
* @param y the Y coordinate
* @return the builder
*/
public Builder addPoint(int x, int y) {
return addPoint(x, y, 1);
}
/**
* Adds a point to the {@code Sam2Input}.
*
* @param x the X coordinate
* @param y the Y coordinate
* @param label the label of the point, 0 for background, 1 for foreground
* @return the builder
*/
public Builder addPoint(int x, int y, int label) {
return addPoint(new Point(x, y), label);
}
/**
* Adds a point to the {@code Sam2Input}.
*
* @param point the point on image
* @param label the label of the point, 0 for background, 1 for foreground
* @return the builder
*/
public Builder addPoint(Point point, int label) {
points.add(point);
labels.add(label);
return this;
}
/**
* Adds a box area to the {@code Sam2Input}.
*
* @param x the left coordinate
* @param y the top coordinate
* @param right the right coordinate
* @param bottom the bottom coordinate
* @return the builder
*/
public Builder addBox(int x, int y, int right, int bottom) {
addPoint(new Point(x, y), 2);
addPoint(new Point(right, bottom), 3);
return this;
}
/**
* Sets the visualize for the {@code Sam2Input}.
*
* @return the builder
*/
public Builder visualize() {
visualize = true;
return this;
}
/**
* Builds the {@code Sam2Input}.
*
* @return the new {@code Sam2Input}
*/
public Sam2Input build() {
Point[] location = points.toArray(new Point[0]);
int[] array = labels.stream().mapToInt(Integer::intValue).toArray();
return new Sam2Input(image, location, array, visualize);
}
}
private static final class Location {
String type;
int[] data;
int label;
public void setType(String type) {
this.type = type;
}
public void setData(int[] data) {
this.data = data;
}
public void setLabel(int label) {
this.label = label;
}
}
private static final class Prompt {
@SerializedName("image_url")
String image;
Location[] prompt;
boolean visualize;
public void setImage(String image) {
this.image = image;
}
public void setPrompt(Location[] prompt) {
this.prompt = prompt;
}
public void setVisualize(boolean visualize) {
this.visualize = visualize;
}
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/Sam2TranslatorFactory.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.translator.Sam2Translator.Sam2Input;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import ai.djl.util.Pair;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** A {@link TranslatorFactory} that creates a {@link Sam2Translator} instance. */
public class Sam2TranslatorFactory implements TranslatorFactory, Serializable {
private static final long serialVersionUID = 1L;
private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>();
static {
SUPPORTED_TYPES.add(new Pair<>(Sam2Input.class, DetectedObjects.class));
SUPPORTED_TYPES.add(new Pair<>(Input.class, Output.class));
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <I, O> Translator<I, O> newInstance(
Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) {
if (input == Sam2Input.class && output == DetectedObjects.class) {
return (Translator<I, O>) Sam2Translator.builder(arguments).build();
} else if (input == Input.class && output == Output.class) {
Sam2Translator translator = Sam2Translator.builder(arguments).build();
return (Translator<I, O>) new Sam2ServingTranslator(translator);
}
throw new IllegalArgumentException("Unsupported input/output types.");
}
/** {@inheritDoc} */
@Override
public Set<Pair<Type, Type>> getSupportedTypes() {
return SUPPORTED_TYPES;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SemanticSegmentationTranslator.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.CategoryMask;
import ai.djl.modality.cv.transform.ResizeShort;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* A {@link Translator} that post-process the {@link Image} into {@link CategoryMask} with output
* mask representing the class that each pixel in the original image belong to.
*/
public class SemanticSegmentationTranslator extends BaseImageTranslator<CategoryMask> {
private SynsetLoader synsetLoader;
private List<String> classes;
/**
* Creates the Semantic Segmentation translator from the given builder.
*
* @param builder the builder for the translator
*/
public SemanticSegmentationTranslator(Builder builder) {
super(builder);
this.synsetLoader = builder.synsetLoader;
}
/** {@inheritDoc} */
@Override
public void prepare(TranslatorContext ctx) throws IOException {
if (classes == null) {
classes = synsetLoader.load(ctx.getModel());
}
}
/** {@inheritDoc} */
@Override
public CategoryMask processOutput(TranslatorContext ctx, NDList list) {
// scores contains the probabilities of each pixel being a certain object
float[] scores = list.get(1).toFloatArray();
Shape shape = list.get(1).getShape();
int width = (int) shape.get(2);
int height = (int) shape.get(1);
int[][] mask = new int[height][width];
int imageSize = width * height;
// Build mask array
int numOfClasses = classes.size();
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = h * width + w;
int maxi = 0;
double maxnum = -Double.MAX_VALUE;
for (int i = 0; i < numOfClasses; ++i) {
// get score for each i at the h,w pixel of the image
float score = scores[i * imageSize + index];
if (score > maxnum) {
maxnum = score;
maxi = i;
}
}
mask[h][w] = maxi;
}
}
return new CategoryMask(classes, mask);
}
/**
* Creates a builder to build a {@code SemanticSegmentationTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code SemanticSegmentationTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for Semantic Segmentation translator. */
public static class Builder extends ClassificationBuilder<Builder> {
int shortEdge = 600;
int maxEdge = 1000;
Builder() {}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
super.configPostProcess(arguments);
shortEdge = ArgumentsUtil.intValue(arguments, "shortEdge", 600);
maxEdge = ArgumentsUtil.intValue(arguments, "maxEdge", 1000);
}
/**
* Builds the translator.
*
* @return the new translator
*/
public SemanticSegmentationTranslator build() {
validate();
ResizeShort resize = new ResizeShort(shortEdge, maxEdge, Image.Interpolation.BILINEAR);
pipeline.insert(0, null, resize);
return new SemanticSegmentationTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SemanticSegmentationTranslatorFactory.java
|
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.CategoryMask;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** A {@link TranslatorFactory} that creates a {@link SemanticSegmentationTranslator} instance. */
public class SemanticSegmentationTranslatorFactory extends BaseImageTranslatorFactory<CategoryMask>
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, CategoryMask> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return SemanticSegmentationTranslator.builder(arguments).build();
}
/** {@inheritDoc} */
@Override
public Class<CategoryMask> getBaseOutputType() {
return CategoryMask.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SimplePoseTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.Joints;
import ai.djl.modality.cv.output.Joints.Joint;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.index.NDIndex;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A {@link BaseImageTranslator} that post-process the {@link NDArray} into human {@link Joints}.
*/
public class SimplePoseTranslator extends BaseImageTranslator<Joints> {
private float threshold;
/**
* Creates the Pose Estimation translator from the given builder.
*
* @param builder the builder for the translator
*/
public SimplePoseTranslator(Builder builder) {
super(builder);
this.threshold = builder.threshold;
}
/** {@inheritDoc} */
@Override
public Joints processOutput(TranslatorContext ctx, NDList list) {
NDArray pred = list.singletonOrThrow();
int numJoints = (int) pred.getShape().get(0);
int height = (int) pred.getShape().get(1);
int width = (int) pred.getShape().get(2);
NDArray predReshaped = pred.reshape(new Shape(1, numJoints, -1));
NDArray maxIndices =
predReshaped
.argMax(2)
.reshape(new Shape(1, numJoints, -1))
.toType(DataType.FLOAT32, false);
NDArray maxValues = predReshaped.max(new int[] {2}, true);
NDArray result = maxIndices.tile(2, 2);
result.set(new NDIndex(":, :, 0"), result.get(":, :, 0").mod(width));
result.set(new NDIndex(":, :, 1"), result.get(":, :, 1").div(width).floor());
// TODO remove asType
NDArray predMask =
maxValues
.gt(0.0)
// current boolean NDArray operator didn't support majority of ops
// need to cast to int
.toType(DataType.UINT8, false)
.tile(2, 2)
.toType(DataType.BOOLEAN, false);
float[] flattened = result.get(predMask).toFloatArray();
float[] flattenedConfidence = maxValues.toFloatArray();
List<Joint> joints = new ArrayList<>(numJoints);
for (int i = 0; i < numJoints; ++i) {
if (flattenedConfidence[i] > threshold) {
joints.add(
new Joint(
flattened[i * 2] / width,
flattened[i * 2 + 1] / height,
flattenedConfidence[i]));
}
}
return new Joints(joints);
}
/**
* Creates a builder to build a {@code SimplePoseTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code SimplePoseTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for Pose Estimation translator. */
public static class Builder extends BaseBuilder<Builder> {
float threshold = 0.2f;
Builder() {}
/**
* Sets the threshold for prediction accuracy.
*
* <p>Predictions below the threshold will be dropped.
*
* @param threshold the threshold for prediction accuracy
* @return the builder
*/
public Builder optThreshold(float threshold) {
this.threshold = threshold;
return self();
}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
threshold = ArgumentsUtil.floatValue(arguments, "threshold", 0.2f);
}
/**
* Builds the translator.
*
* @return the new translator
*/
public SimplePoseTranslator build() {
validate();
return new SimplePoseTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SimplePoseTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.Joints;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** An {@link TranslatorFactory} that creates a {@link SimplePoseTranslator} instance. */
public class SimplePoseTranslatorFactory extends BaseImageTranslatorFactory<Joints>
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, Joints> buildBaseTranslator(Model model, Map<String, ?> arguments) {
return SimplePoseTranslator.builder(arguments).build();
}
/** {@inheritDoc} */
@Override
public Class<Joints> getBaseOutputType() {
return Joints.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SingleShotDetectionTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A {@link BaseImageTranslator} that post-process the {@link NDArray} into {@link DetectedObjects}
* with boundaries.
*/
public class SingleShotDetectionTranslator extends ObjectDetectionTranslator {
/**
* Creates the SSD translator from the given builder.
*
* @param builder the builder for the translator
*/
public SingleShotDetectionTranslator(Builder builder) {
super(builder);
}
/** {@inheritDoc} */
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
float[] classIds = list.get(0).toFloatArray();
float[] probabilities = list.get(1).toFloatArray();
NDArray boundingBoxes = list.get(2);
List<String> retNames = new ArrayList<>();
List<Double> retProbs = new ArrayList<>();
List<BoundingBox> retBB = new ArrayList<>();
for (int i = 0; i < classIds.length; ++i) {
int classId = (int) classIds[i];
double probability = probabilities[i];
// classId starts from 0, -1 means background
if (classId >= 0 && probability > threshold) {
if (classId >= classes.size()) {
throw new AssertionError("Unexpected index: " + classId);
}
String className = classes.get(classId);
float[] box = boundingBoxes.get(i).toFloatArray();
// rescale box coordinates by width and height
double x = width > 0 ? box[0] / width : box[0];
double y = height > 0 ? box[1] / height : box[1];
double w = width > 0 ? box[2] / width - x : box[2] - x;
double h = height > 0 ? box[3] / height - y : box[3] - y;
Rectangle rect;
if (applyRatio) {
rect = new Rectangle(x / width, y / height, w / width, h / height);
} else {
rect = new Rectangle(x, y, w, h);
}
retNames.add(className);
retProbs.add(probability);
retBB.add(rect);
}
}
return new DetectedObjects(retNames, retProbs, retBB);
}
/**
* Creates a builder to build a {@code SingleShotDetectionTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code SingleShotDetectionTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for SSD translator. */
public static class Builder extends ObjectDetectionBuilder<Builder> {
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/**
* Builds the translator.
*
* @return the new translator
*/
public SingleShotDetectionTranslator build() {
validate();
return new SingleShotDetectionTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/SingleShotDetectionTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** An {@link TranslatorFactory} that creates a {@link SingleShotDetectionTranslator} instance. */
public class SingleShotDetectionTranslatorFactory extends ObjectDetectionTranslatorFactory
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, DetectedObjects> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return SingleShotDetectionTranslator.builder(arguments).build();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/StyleTransferTranslator.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDArrays;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.DataType;
import ai.djl.translate.NoBatchifyTranslator;
import ai.djl.translate.TranslatorContext;
/** Built-in {@code Translator} that provides preprocessing and postprocessing for StyleTransfer. */
public class StyleTransferTranslator implements NoBatchifyTranslator<Image, Image> {
/** {@inheritDoc} */
@Override
public NDList processInput(TranslatorContext ctx, Image input) {
NDArray image = switchFormat(input.toNDArray(ctx.getNDManager())).expandDims(0);
return new NDList(image.toType(DataType.FLOAT32, false));
}
/** {@inheritDoc} */
@Override
public Image processOutput(TranslatorContext ctx, NDList list) {
NDArray output = list.get(0).duplicate().addi(1).muli(128);
return ImageFactory.getInstance().fromNDArray(output.squeeze());
}
private NDArray switchFormat(NDArray array) {
return NDArrays.stack(array.split(3, 2)).squeeze();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/StyleTransferTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** A {@link TranslatorFactory} that creates a {@link StyleTransferTranslator} instance. */
public class StyleTransferTranslatorFactory extends BaseImageTranslatorFactory<Image>
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, Image> buildBaseTranslator(Model model, Map<String, ?> arguments) {
return new StyleTransferTranslator();
}
/** {@inheritDoc} */
@Override
public Class<Image> getBaseOutputType() {
return Image.class;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloPoseTranslator.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.Joints;
import ai.djl.modality.cv.output.Joints.Joint;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.translate.ArgumentsUtil;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** A translator for Yolov8 pose estimation models. */
public class YoloPoseTranslator extends BaseImageTranslator<Joints[]> {
private static final int MAX_DETECTION = 300;
private float threshold;
private float nmsThreshold;
/**
* Creates the Pose Estimation translator from the given builder.
*
* @param builder the builder for the translator
*/
public YoloPoseTranslator(Builder builder) {
super(builder);
this.threshold = builder.threshold;
this.nmsThreshold = builder.nmsThreshold;
}
/** {@inheritDoc} */
@Override
public Joints[] processOutput(TranslatorContext ctx, NDList list) {
NDArray pred = list.singletonOrThrow();
NDArray candidates = pred.get(4).gt(threshold);
pred = pred.transpose();
NDArray sub = pred.get("..., :4");
sub = YoloTranslator.xywh2xyxy(sub);
pred = sub.concat(pred.get("..., 4:"), -1);
pred = pred.get(candidates);
NDList split = pred.split(new long[] {4, 5}, 1);
NDArray box = split.get(0);
int numBox = Math.toIntExact(box.getShape().get(0));
float[] buf = box.toFloatArray();
float[] confidences = split.get(1).toFloatArray();
float[] mask = split.get(2).toFloatArray();
List<Rectangle> boxes = new ArrayList<>(numBox);
List<Double> scores = new ArrayList<>(numBox);
for (int i = 0; i < numBox; ++i) {
float xPos = buf[i * 4];
float yPos = buf[i * 4 + 1];
float w = buf[i * 4 + 2] - xPos;
float h = buf[i * 4 + 3] - yPos;
Rectangle rect = new Rectangle(xPos, yPos, w, h);
boxes.add(rect);
scores.add((double) confidences[i]);
}
List<Integer> nms = Rectangle.nms(boxes, scores, nmsThreshold);
if (nms.size() > MAX_DETECTION) {
nms = nms.subList(0, MAX_DETECTION);
}
Joints[] ret = new Joints[nms.size()];
for (int i = 0; i < ret.length; ++i) {
List<Joint> joints = new ArrayList<>();
ret[i] = new Joints(joints);
int index = nms.get(i);
int pos = index * 51;
for (int j = 0; j < 17; ++j) {
joints.add(
new Joints.Joint(
mask[pos + j * 3] / width,
mask[pos + j * 3 + 1] / height,
mask[pos + j * 3 + 2]));
}
}
return ret;
}
/**
* Creates a builder to build a {@code YoloPoseTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code YoloPoseTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for Pose Estimation translator. */
public static class Builder extends BaseBuilder<Builder> {
float threshold = 0.25f;
float nmsThreshold = 0.7f;
Builder() {}
/**
* Sets the threshold for prediction accuracy.
*
* <p>Predictions below the threshold will be dropped.
*
* @param threshold the threshold for prediction accuracy
* @return the builder
*/
public Builder optThreshold(float threshold) {
this.threshold = threshold;
return self();
}
/**
* Sets the NMS threshold.
*
* @param nmsThreshold the NMS threshold
* @return this builder
*/
public Builder optNmsThreshold(float nmsThreshold) {
this.nmsThreshold = nmsThreshold;
return this;
}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
protected void configPostProcess(Map<String, ?> arguments) {
optThreshold(ArgumentsUtil.floatValue(arguments, "threshold", threshold));
optNmsThreshold(ArgumentsUtil.floatValue(arguments, "nmsThreshold", nmsThreshold));
}
/**
* Builds the translator.
*
* @return the new translator
*/
public YoloPoseTranslator build() {
validate();
return new YoloPoseTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloPoseTranslatorFactory.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.Input;
import ai.djl.modality.Output;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.Joints;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import ai.djl.util.Pair;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** An {@link TranslatorFactory} that creates a {@link YoloPoseTranslator} instance. */
public class YoloPoseTranslatorFactory implements TranslatorFactory, Serializable {
private static final long serialVersionUID = 1L;
private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>();
static {
SUPPORTED_TYPES.add(new Pair<>(Image.class, Joints[].class));
SUPPORTED_TYPES.add(new Pair<>(Input.class, Output.class));
}
/** {@inheritDoc} */
@Override
public Set<Pair<Type, Type>> getSupportedTypes() {
return SUPPORTED_TYPES;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public <I, O> Translator<I, O> newInstance(
Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) {
YoloPoseTranslator translator = YoloPoseTranslator.builder(arguments).build();
if (input == Image.class && output == Joints[].class) {
return (Translator<I, O>) translator;
} else if (input == Input.class && output == Output.class) {
return (Translator<I, O>) new ImageServingTranslator(translator);
}
throw new IllegalArgumentException("Unsupported input/output types.");
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloSegmentationTranslator.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Mask;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.DataType;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** A translator for Yolov8 instance segmentation models. */
public class YoloSegmentationTranslator extends YoloV5Translator {
private static final int[] AXIS_0 = {0};
private static final int[] AXIS_1 = {1};
private float threshold;
private float nmsThreshold;
/**
* Creates the instance segmentation translator from the given builder.
*
* @param builder the builder for the translator
*/
public YoloSegmentationTranslator(Builder builder) {
super(builder);
this.threshold = builder.threshold;
this.nmsThreshold = builder.nmsThreshold;
}
/** {@inheritDoc} */
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
NDArray pred = list.get(0);
NDArray protos = list.get(1);
int maskIndex = classes.size() + 4;
NDArray candidates = pred.get("4:" + maskIndex).max(AXIS_0).gt(threshold);
pred = pred.transpose();
NDArray sub = pred.get("..., :4");
sub = YoloTranslator.xywh2xyxy(sub);
pred = sub.concat(pred.get("..., 4:"), -1);
pred = pred.get(candidates);
NDList split = pred.split(new long[] {4, maskIndex}, 1);
NDArray box = split.get(0);
int numBox = Math.toIntExact(box.getShape().get(0));
float[] buf = box.toFloatArray();
float[] confidences = split.get(1).max(AXIS_1).toFloatArray();
long[] ids = split.get(1).argMax(1).toLongArray();
List<Rectangle> boxes = new ArrayList<>(numBox);
List<Double> scores = new ArrayList<>(numBox);
for (int i = 0; i < numBox; ++i) {
float xPos = buf[i * 4];
float yPos = buf[i * 4 + 1];
float w = buf[i * 4 + 2] - xPos;
float h = buf[i * 4 + 3] - yPos;
Rectangle rect = new Rectangle(xPos, yPos, w, h);
boxes.add(rect);
scores.add((double) confidences[i]);
}
List<Integer> nms = Rectangle.nms(boxes, scores, nmsThreshold);
long[] idx = nms.stream().mapToLong(Integer::longValue).toArray();
NDArray selected = box.getManager().create(idx);
NDArray masks = split.get(2).get(selected);
int maskW = Math.toIntExact(protos.getShape().get(2));
int maskH = Math.toIntExact(protos.getShape().get(1));
protos = protos.reshape(32, (long) maskH * maskW);
masks =
masks.matMul(protos)
.reshape(nms.size(), maskH, maskW)
.gt(0f)
.toType(DataType.FLOAT32, true);
float[] maskArray = masks.toFloatArray();
box = box.get(selected);
buf = box.toFloatArray();
List<String> retClasses = new ArrayList<>();
List<Double> retProbs = new ArrayList<>();
List<BoundingBox> retBB = new ArrayList<>();
for (int i = 0; i < idx.length; ++i) {
float x = buf[i * 4] / width;
float y = buf[i * 4 + 1] / height;
float w = buf[i * 4 + 2] / width - x;
float h = buf[i * 4 + 3] / width - y;
int id = nms.get(i);
retClasses.add(classes.get((int) ids[id]));
retProbs.add((double) confidences[id]);
float[][] maskFloat = new float[maskH][maskW];
for (int j = 0; j < maskH; j++) {
System.arraycopy(maskArray, j * maskW, maskFloat[j], 0, maskW);
}
Mask bb = new Mask(x, y, w, h, maskFloat, true);
retBB.add(bb);
}
return new DetectedObjects(retClasses, retProbs, retBB);
}
/**
* Creates a builder to build a {@code YoloSegmentationTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code YoloSegmentationTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for instance segmentation translator. */
public static class Builder extends YoloV5Translator.Builder {
Builder() {}
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/** {@inheritDoc} */
@Override
public YoloSegmentationTranslator build() {
validate();
return new YoloSegmentationTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloSegmentationTranslatorFactory.java
|
/*
* Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.Translator;
import java.io.Serializable;
import java.util.Map;
/** A translatorFactory that creates a {@link YoloSegmentationTranslator} instance. */
public class YoloSegmentationTranslatorFactory extends ObjectDetectionTranslatorFactory
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, DetectedObjects> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return YoloSegmentationTranslator.builder(arguments).build();
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloTranslator.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.types.DataType;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** A translator for yolo models. */
public class YoloTranslator extends ObjectDetectionTranslator {
/**
* Constructs an ImageTranslator with the provided builder.
*
* @param builder the data to build with
*/
public YoloTranslator(Builder builder) {
super(builder);
}
/** {@inheritDoc} */
@Override
public DetectedObjects processOutput(TranslatorContext ctx, NDList list) {
int[] classIndices = list.get(0).toType(DataType.INT32, true).flatten().toIntArray();
double[] probs = list.get(1).toType(DataType.FLOAT64, true).flatten().toDoubleArray();
NDArray boundingBoxes = list.get(2);
int detected = Math.toIntExact(probs.length);
NDArray xMin = boundingBoxes.get(":, 0").clip(0, width).div(width);
NDArray yMin = boundingBoxes.get(":, 1").clip(0, height).div(height);
NDArray xMax = boundingBoxes.get(":, 2").clip(0, width).div(width);
NDArray yMax = boundingBoxes.get(":, 3").clip(0, height).div(height);
float[] boxX = xMin.toFloatArray();
float[] boxY = yMin.toFloatArray();
float[] boxWidth = xMax.sub(xMin).toFloatArray();
float[] boxHeight = yMax.sub(yMin).toFloatArray();
List<String> retClasses = new ArrayList<>(detected);
List<Double> retProbs = new ArrayList<>(detected);
List<BoundingBox> retBB = new ArrayList<>(detected);
for (int i = 0; i < detected; i++) {
if (classIndices[i] < 0 || probs[i] < threshold) {
continue;
}
retClasses.add(classes.get(classIndices[i]));
retProbs.add(probs[i]);
Rectangle rect;
if (applyRatio) {
rect =
new Rectangle(
boxX[i] / width,
boxY[i] / height,
boxWidth[i] / width,
boxHeight[i] / height);
} else {
rect = new Rectangle(boxX[i], boxY[i], boxWidth[i], boxHeight[i]);
}
retBB.add(rect);
}
return new DetectedObjects(retClasses, retProbs, retBB);
}
static NDArray xywh2xyxy(NDArray array) {
NDArray xy = array.get("..., :2");
NDArray wh = array.get("..., 2:").div(2);
return xy.sub(wh).concat(xy.add(wh), -1);
}
/**
* Creates a builder to build a {@link YoloTranslator}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build a {@code YoloTranslator} with specified arguments.
*
* @param arguments arguments to specify builder options
* @return a new builder
*/
public static Builder builder(Map<String, ?> arguments) {
Builder builder = new Builder();
builder.configPreProcess(arguments);
builder.configPostProcess(arguments);
return builder;
}
/** The builder for {@link YoloTranslator}. */
public static class Builder extends ObjectDetectionBuilder<Builder> {
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/**
* Builds the translator.
*
* @return the new translator
*/
public YoloTranslator build() {
validate();
return new YoloTranslator(this);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
|
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloTranslatorFactory.java
|
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.djl.modality.cv.translator;
import ai.djl.Model;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorFactory;
import java.io.Serializable;
import java.util.Map;
/** An {@link TranslatorFactory} that creates a {@link YoloTranslator} instance. */
public class YoloTranslatorFactory extends ObjectDetectionTranslatorFactory
implements Serializable {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
protected Translator<Image, DetectedObjects> buildBaseTranslator(
Model model, Map<String, ?> arguments) {
return YoloTranslator.builder(arguments).build();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.