Skip to content

Commit fadc7d3

Browse files
committed
Added DJL Tensorflow Lite sample
1 parent 2197dcd commit fadc7d3

File tree

13 files changed

+421
-0
lines changed

13 files changed

+421
-0
lines changed

.gitignore

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,23 @@ tensorflow-train-in-sagemaker-deploy-with-lambda/container/model/model.tar.gz
310310
tensorflow-train-in-sagemaker-deploy-with-lambda/.aws-sam/build.toml
311311
scikit-learn-inference-docker-lambda/.aws-sam/build.toml
312312
scikit-learn-inference-docker-lambda/samconfig.toml
313+
djl-tensorflow-lite-inference-docker-lambda/.aws-sam/build.toml
314+
djl-tensorflow-lite-inference-docker-lambda/.gradle/5.1.1/executionHistory/executionHistory.bin
315+
djl-tensorflow-lite-inference-docker-lambda/.gradle/5.1.1/executionHistory/executionHistory.lock
316+
djl-tensorflow-lite-inference-docker-lambda/.gradle/5.1.1/fileChanges/last-build.bin
317+
djl-tensorflow-lite-inference-docker-lambda/.gradle/5.1.1/fileHashes/fileHashes.lock
318+
djl-tensorflow-lite-inference-docker-lambda/.gradle/5.1.1/gc.properties
319+
djl-tensorflow-lite-inference-docker-lambda/.gradle/buildOutputCleanup/buildOutputCleanup.lock
320+
djl-tensorflow-lite-inference-docker-lambda/.gradle/buildOutputCleanup/cache.properties
321+
djl-tensorflow-lite-inference-docker-lambda/.gradle/vcs-1/gc.properties
322+
djl-tensorflow-lite-inference-docker-lambda/.idea/compiler.xml
323+
djl-tensorflow-lite-inference-docker-lambda/.idea/djl-tensorflow-lite-inference-docker-lambda.iml
324+
djl-tensorflow-lite-inference-docker-lambda/.idea/gradle.xml
325+
djl-tensorflow-lite-inference-docker-lambda/.idea/jarRepositories.xml
326+
djl-tensorflow-lite-inference-docker-lambda/.idea/misc.xml
327+
djl-tensorflow-lite-inference-docker-lambda/.idea/vcs.xml
328+
djl-tensorflow-lite-inference-docker-lambda/gradle/lambda-build-init.gradle
329+
djl-tensorflow-lite-inference-docker-lambda/gradle/wrapper/gradle-wrapper.jar
330+
djl-tensorflow-lite-inference-docker-lambda/gradle/wrapper/gradle-wrapper.properties
331+
djl-tensorflow-lite-inference-docker-lambda/gradlew
332+
djl-tensorflow-lite-inference-docker-lambda/gradlew.bat

djl-object-detection-inference-docker-lambda/.idea/.gitignore

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

djl-tensorflow-lite-inference-docker-lambda/.idea/.gitignore

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
FROM openjdk:8 as build-image
2+
3+
ARG SCRATCH_DIR=/var/task/build
4+
WORKDIR /var/task
5+
6+
COPY src/ src/
7+
COPY gradle/ gradle/
8+
COPY build.gradle gradlew ./
9+
10+
RUN mkdir build
11+
COPY gradle/lambda-build-init.gradle ./build
12+
13+
RUN echo $SCRATCH_DIR
14+
15+
RUN ./gradlew --project-cache-dir $SCRATCH_DIR/gradle-cache -Dsoftware.amazon.aws.lambdabuilders.scratch-dir=$SCRATCH_DIR --init-script $SCRATCH_DIR/lambda-build-init.gradle build
16+
RUN rm -r $SCRATCH_DIR/gradle-cache
17+
RUN rm -r $SCRATCH_DIR/lambda-build-init.gradle
18+
RUN cp -r $SCRATCH_DIR/*/build/distributions/lambda-build/* .
19+
20+
FROM public.ecr.aws/lambda/java:8
21+
22+
COPY --from=build-image /var/task/META-INF ./
23+
COPY --from=build-image /var/task/com ./com
24+
COPY --from=build-image /var/task/lib/ ./lib
25+
# Command can be overwritten by providing a different command in the template directly.
26+
CMD ["com.example.App::handleRequest"]
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
## Serverless Tensorflow Lite Image Classification Model Serving with Deep Java Library (DJL)
2+
3+
This example illustrates how to serve TensorFlow Lite Image Classification model on Lambda Function using [Deep Java Library (DJL)](http://djl.ai).
4+
5+
This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
6+
7+
- src/main - Code for the application's Lambda function.
8+
- events - Invocation events that you can use to invoke the function.
9+
- src/test - Unit tests for the application code.
10+
- template.yaml - A template that defines the application's AWS resources.
11+
12+
The application uses several AWS resources, including Lambda functions. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
13+
14+
## Deploy the sample application
15+
16+
The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
17+
18+
To use the SAM CLI, you need the following tools.
19+
20+
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
21+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
22+
23+
You may need the following for local testing.
24+
* Java8 - [Install the Java SE Development Kit 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
25+
26+
To build and deploy your application for the first time, run the following in your shell:
27+
28+
```bash
29+
sam build
30+
sam deploy --guided
31+
```
32+
33+
The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts:
34+
35+
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
36+
* **AWS Region**: The AWS region you want to deploy your app to.
37+
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
38+
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modified IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
39+
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
40+
41+
## Use the SAM CLI to build and test locally
42+
43+
Build your application with the `sam build` command.
44+
45+
```bash
46+
djl-tensorflow-lite-inference-docker-lambda$ sam build
47+
```
48+
49+
The SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `build.gradle` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder.
50+
51+
Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
52+
53+
Run functions locally and invoke them with the `sam local invoke` command.
54+
55+
```bash
56+
djl-tensorflow-lite-inference-docker-lambda$ sam local invoke DjlTFLiteInferenceFunction --event events/event.json
57+
```
58+
59+
## Testing your Lambda function in the Cloud
60+
61+
1. In the [Lambda Console](https://console.aws.amazon.com/lambda/), select Configure test events from the Test events dropdown.
62+
2. For Event Name, enter InferenceTestEvent.
63+
3. Copy the event JSON from [here](./events/event.json) and paste in the dialog box.
64+
4. Choose _**Create**_.
65+
66+
![Configure test event](../img/djl_object_detection_configure_test_event.png)
67+
68+
After saving, you see InferenceTestEvent in the Test list. Now choose _**Test**_.
69+
70+
You see the Lambda function inference result, log output, and duration:
71+
72+
![Lambda execution result](../img/djl_object_detection_execution_result.png)
73+
74+
## Fetch, tail, and filter Lambda function logs
75+
76+
To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
77+
78+
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
79+
80+
```bash
81+
djl-tensorflow-lite-inference-docker-lambda$ sam logs -n DjlTFLiteInferenceFunction --stack-name djl-tensorflow-lite-inference-docker-lambda --tail
82+
```
83+
84+
You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
85+
86+
## Unit tests
87+
88+
Tests are defined in the `src/test` folder in this project.
89+
90+
```bash
91+
djl-tensorflow-lite-inference-docker-lambda$ gradle test
92+
```
93+
94+
## Cleanup
95+
96+
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
97+
98+
```bash
99+
aws cloudformation delete-stack --stack-name djl-tensorflow-lite-inference-docker-lambda
100+
```
101+
102+
## Resources
103+
104+
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
105+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
plugins {
2+
id 'java'
3+
}
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
implementation 'com.amazonaws:aws-lambda-java-core:1.2.1'
11+
implementation 'com.amazonaws:aws-lambda-java-events:3.1.0'
12+
13+
implementation 'ai.djl:api:0.10.0'
14+
implementation 'ai.djl:model-zoo:0.10.0'
15+
implementation 'ai.djl.tflite:tflite-engine:0.10.0'
16+
implementation 'org.slf4j:slf4j-api:1.7.26'
17+
implementation 'org.slf4j:slf4j-simple:1.7.26'
18+
implementation 'net.java.dev.jna:jna:5.3.0'
19+
20+
implementation 'ai.djl.tflite:tflite-native-auto:2.4.1'
21+
22+
testImplementation 'org.testng:testng:6.14.3'
23+
24+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"inputImageUrl": "https://resources.djl.ai/images/sachertorte.jpg"
3+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.example;
2+
3+
import ai.djl.ModelException;
4+
import ai.djl.inference.Predictor;
5+
import ai.djl.modality.Classifications;
6+
import ai.djl.modality.cv.Image;
7+
import ai.djl.modality.cv.ImageFactory;
8+
import ai.djl.repository.zoo.Criteria;
9+
import ai.djl.repository.zoo.ModelZoo;
10+
import ai.djl.repository.zoo.ZooModel;
11+
import ai.djl.translate.TranslateException;
12+
import ai.djl.util.Utils;
13+
import com.amazonaws.services.lambda.runtime.Context;
14+
import com.amazonaws.services.lambda.runtime.LambdaLogger;
15+
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
16+
import com.google.gson.Gson;
17+
import com.google.gson.GsonBuilder;
18+
19+
import java.io.IOException;
20+
import java.io.InputStream;
21+
import java.io.OutputStream;
22+
import java.nio.charset.StandardCharsets;
23+
24+
/**
25+
* Handler for requests to Lambda function.
26+
*/
27+
public class App implements RequestStreamHandler {
28+
29+
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
30+
31+
static {
32+
// DJL saves model and native libraries in cache folder.
33+
// In AWS-Lambda only /tmp folder is writable.
34+
System.setProperty("DJL_CACHE_DIR", "/tmp/djl_cache");
35+
}
36+
37+
public void handleRequest(InputStream is, OutputStream os, Context context) throws IOException {
38+
LambdaLogger logger = context.getLogger();
39+
String input = Utils.toString(is);
40+
41+
Request request = GSON.fromJson(input, Request.class);
42+
String inputImageUrl = request.getInputImageUrl();
43+
logger.log("inputImageUrl: " + inputImageUrl);
44+
45+
try {
46+
47+
Criteria<Image, Classifications> criteria = Criteria.builder()
48+
.setTypes(Image.class, Classifications.class)
49+
.optEngine("TFLite")
50+
.optFilter("dataset", "aiyDish")
51+
.build();
52+
ZooModel<Image, Classifications> model = ModelZoo.loadModel(criteria);
53+
54+
Predictor<Image, Classifications> predictor = model.newPredictor();
55+
56+
Image image = ImageFactory.getInstance().fromUrl(inputImageUrl);
57+
58+
Classifications classifications = predictor.predict(image);
59+
60+
logger.log("classifications: " + classifications);
61+
os.write(GSON.toJson(classifications.best()).getBytes(StandardCharsets.UTF_8));
62+
63+
} catch (RuntimeException | ModelException | TranslateException e) {
64+
logger.log("Failed handle input: " + input);
65+
logger.log(e.toString());
66+
String msg = "{\"status\": \"invoke failed: " + e.toString() + "\"}";
67+
os.write(msg.getBytes(StandardCharsets.UTF_8));
68+
}
69+
}
70+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.example;
2+
3+
public class Request {
4+
5+
private String inputImageUrl;
6+
7+
public String getInputImageUrl() {
8+
return inputImageUrl;
9+
}
10+
11+
public void setInputImageUrl(String inputImageUrl) {
12+
this.inputImageUrl = inputImageUrl;
13+
}
14+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.example;
2+
3+
import ai.djl.modality.Classifications;
4+
import com.amazonaws.services.lambda.runtime.Context;
5+
import com.google.gson.Gson;
6+
import com.google.gson.reflect.TypeToken;
7+
import java.io.ByteArrayInputStream;
8+
import java.io.ByteArrayOutputStream;
9+
import java.io.IOException;
10+
import java.io.InputStream;
11+
import java.lang.reflect.Type;
12+
import java.nio.charset.StandardCharsets;
13+
import java.util.List;
14+
import org.testng.Assert;
15+
import org.testng.annotations.Test;
16+
17+
public class AppTest {
18+
19+
@Test
20+
public void invokeTest() throws IOException {
21+
Context context = new MockContext();
22+
App app = new App();
23+
24+
Request request = new Request();
25+
request.setInputImageUrl("https://resources.djl.ai/images/sachertorte.jpg");
26+
Gson gson = new Gson();
27+
byte[] buf = gson.toJson(request).getBytes(StandardCharsets.UTF_8);
28+
29+
InputStream is = new ByteArrayInputStream(buf);
30+
ByteArrayOutputStream os = new ByteArrayOutputStream();
31+
app.handleRequest(is, os, context);
32+
String result = os.toString(StandardCharsets.UTF_8.name());
33+
34+
Assert.assertNotNull(result);
35+
}
36+
}

0 commit comments

Comments
 (0)