Google Cloud Vision

Since Camel 4.19

Only producer is supported

The Google Cloud Vision component provides access to Google Cloud Vision API via the Google Cloud Vision Client for Java.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-google-vision</artifactId>
    <!-- use the same version as your Camel core version -->
    <version>x.x.x</version>
</dependency>

Authentication Configuration

Google Cloud Vision component authentication is targeted for use with the GCP Service Accounts. For more information, please refer to Google Cloud Authentication.

When you have the service account key, you can provide authentication credentials to your application code. Google security credentials can be set through the component endpoint:

String endpoint = "google-vision://labelDetection?serviceAccountKey=/home/user/Downloads/my-key.json";

Or by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS :

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

URI Format

google-vision://operation[?options]

You can append query options to the URI in the following format, ?options=value&option2=value&…​

For example, in order to perform label detection on an image, use the following snippet:

from("direct:start")
    .to("google-vision://labelDetection?serviceAccountKey=/home/user/Downloads/my-key.json");

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Google Cloud Vision component supports 2 options, which are listed below.

Name Description Default Type

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

Endpoint Options

The Google Cloud Vision endpoint is configured using URI syntax:

google-vision:operation

With the following path and query parameters:

Path Parameters (1 parameters)

Name Description Default Type

operation (common)

Required The operation name.

String

Query Parameters (5 parameters)

Name Description Default Type

serviceAccountKey (common)

Service account key to authenticate an application as a service account.

String

maxResults (producer)

The max number of results to return per feature type. Default is unset (API default).

Integer

pojoRequest (producer)

Specifies if the request is a pojo request.

false

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

client (advanced)

Autowired The client to use during service invocation.

ImageAnnotatorClient

Message Headers

The Google Cloud Vision component supports 2 message header(s), which is/are listed below:

Name Description Default Type

GoogleCloudVisionOperation (producer)

Constant: OPERATION

The operation to perform.

Enum values:

  • labelDetection

  • textDetection

  • faceDetection

  • landmarkDetection

  • logoDetection

  • safeSearchDetection

  • imagePropertiesDetection

  • webDetection

  • objectLocalization

  • cropHintsDetection

  • documentTextDetection

GoogleCloudVisionOperations

GoogleCloudVisionResponseObject (producer)

Constant: RESPONSE_OBJECT

The response object resulting from the Google Cloud Vision API invocation.

AnnotateImageResponse

Usage

Message body

The message body should contain the image data as a byte[].

When pojoRequest=true, the body should be a com.google.cloud.vision.v1.AnnotateImageRequest instance instead.

Google Cloud Vision Producer operations

Google Cloud Vision component provides the following operation on the producer side:

  • labelDetection

  • textDetection

  • documentTextDetection

  • faceDetection

  • landmarkDetection

  • logoDetection

  • safeSearchDetection

  • imagePropertiesDetection

  • webDetection

  • objectLocalization

  • cropHintsDetection

The operation is specified as part of the endpoint URI (e.g., google-vision://labelDetection). You can override the operation at runtime by setting the GoogleCloudVisionOperation message header.

Advanced component configuration

If you need to have more control over the ImageAnnotatorClient instance configuration, you can create your own instance and refer to it in your Camel google-vision component configuration:

from("direct:start")
    .to("google-vision://labelDetection?client=#myVisionClient");

Google Cloud Vision Producer Operation examples

  • labelDetection: this operation detects labels in an image

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/image.jpg"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://labelDetection?serviceAccountKey=/home/user/Downloads/my-key.json&maxResults=10")
    .log("body:${body}")
    .to("mock:result");

This operation will return a List<EntityAnnotation> with the detected labels.

  • textDetection: this operation extracts text from an image (OCR)

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/document.png"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://textDetection?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

This operation will return a List<EntityAnnotation> with the detected text.

  • faceDetection: this operation detects faces in an image

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/photo.jpg"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://faceDetection?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

This operation will return a List<FaceAnnotation> with the detected faces.

  • safeSearchDetection: this operation detects explicit content

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/image.jpg"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://safeSearchDetection?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

This operation will return a SafeSearchAnnotation with likelihood ratings for adult, spoof, medical, violence and racy content.

  • objectLocalization: this operation detects and localizes objects

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/image.jpg"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://objectLocalization?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

This operation will return a List<LocalizedObjectAnnotation> with detected objects and their bounding polygons.

  • webDetection: this operation finds web references and visually similar images

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/image.jpg"));
        exchange.getIn().setBody(imageData);
    })
    .to("google-vision://webDetection?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

This operation will return a WebDetection with matching pages, images and best guess labels.

  • Using POJO request for full control:

from("direct:start")
    .process(exchange -> {
        Image image = Image.newBuilder()
            .setContent(ByteString.copyFrom(imageData))
            .build();
        Feature feature = Feature.newBuilder()
            .setType(Feature.Type.LABEL_DETECTION)
            .setMaxResults(5)
            .build();
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
            .addFeatures(feature)
            .setImage(image)
            .build();
        exchange.getIn().setBody(request);
    })
    .to("google-vision://labelDetection?serviceAccountKey=/home/user/Downloads/my-key.json&pojoRequest=true")
    .log("body:${body}")
    .to("mock:result");

When using pojoRequest=true, the body should be an AnnotateImageRequest and the full AnnotateImageResponse is returned.

  • Overriding the operation at runtime via header:

from("direct:start")
    .process(exchange -> {
        byte[] imageData = Files.readAllBytes(Path.of("/path/to/image.jpg"));
        exchange.getIn().setBody(imageData);
        exchange.getIn().setHeader(GoogleCloudVisionConstants.OPERATION, GoogleCloudVisionOperations.logoDetection);
    })
    .to("google-vision://labelDetection?serviceAccountKey=/home/user/Downloads/my-key.json")
    .log("body:${body}")
    .to("mock:result");

Spring Boot Auto-Configuration

When using google-vision with Spring Boot make sure to use the following Maven dependency to have support for auto configuration:

<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-google-vision-starter</artifactId>
  <version>x.x.x</version>
  <!-- use the same version as your Camel core version -->
</dependency>

The component supports 3 options, which are listed below.

Name Description Default Type

camel.component.google-vision.autowired-enabled

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

Boolean

camel.component.google-vision.enabled

Whether to enable auto configuration of the google-vision component. This is enabled by default.

Boolean

camel.component.google-vision.lazy-start-producer

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

Boolean