Search in sources :

Example 1 with GcsEvent

use of functions.eventpojos.GcsEvent in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagick method accept.

// [END functions_imagemagick_setup]
// [START functions_imagemagick_analyze]
@Override
public // Blurs uploaded images that are flagged as Adult or Violence.
void accept(CloudEvent event) {
    // Extract the GCS Event data from the CloudEvent's data payload.
    GcsEvent data = getEventData(event);
    // Validate parameters
    if (data.getBucket() == null || data.getName() == null) {
        logger.severe("Error: Malformed GCS event.");
        return;
    }
    BlobInfo blobInfo = BlobInfo.newBuilder(data.getBucket(), data.getName()).build();
    // Construct URI to GCS bucket and file.
    String gcsPath = String.format("gs://%s/%s", data.getBucket(), data.getName());
    logger.info(String.format("Analyzing %s", data.getName()));
    // Construct request.
    ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
    List<AnnotateImageRequest> requests = List.of(request);
    // Send request to the Vision API.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                logger.info(String.format("Error: %s", res.getError().getMessage()));
                return;
            }
            // Get Safe Search Annotations
            SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
            if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
                logger.info(String.format("Detected %s as inappropriate.", data.getName()));
                blur(blobInfo);
            } else {
                logger.info(String.format("Detected %s as OK.", data.getName()));
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
    }
}
Also used : SafeSearchAnnotation(com.google.cloud.vision.v1.SafeSearchAnnotation) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) BlobInfo(com.google.cloud.storage.BlobInfo) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) GcsEvent(functions.eventpojos.GcsEvent) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 2 with GcsEvent

use of functions.eventpojos.GcsEvent in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagickTest method functionsImagemagickAnalyze_shouldHandleMissingImages.

@Test
public void functionsImagemagickAnalyze_shouldHandleMissingImages() {
    String imageName = "missing.jpg";
    GcsEvent gcsEvent = new GcsEvent();
    gcsEvent.setBucket(BUCKET_NAME);
    gcsEvent.setName(imageName);
    Gson gson = new Gson();
    CloudEvent event = CloudEventBuilder.v1().withId("0").withType("gcs.event").withSource(URI.create("https://example.com")).withData(gson.toJson(gcsEvent).getBytes()).build();
    new ImageMagick().accept(event);
    assertThat(LOG_HANDLER.getStoredLogRecords().get(1).getMessage()).contains("Error opening file");
}
Also used : Gson(com.google.gson.Gson) GcsEvent(functions.eventpojos.GcsEvent) CloudEvent(io.cloudevents.CloudEvent) Test(org.junit.Test)

Example 3 with GcsEvent

use of functions.eventpojos.GcsEvent in project java-docs-samples by GoogleCloudPlatform.

the class HelloGcs method accept.

@Override
public void accept(CloudEvent event) {
    logger.info("Event: " + event.getId());
    logger.info("Event Type: " + event.getType());
    if (event.getData() != null) {
        String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
        Gson gson = new Gson();
        GcsEvent gcsEvent = gson.fromJson(cloudEventData, GcsEvent.class);
        logger.info("Bucket: " + gcsEvent.getBucket());
        logger.info("File: " + gcsEvent.getName());
        logger.info("Metageneration: " + gcsEvent.getMetageneration());
        logger.info("Created: " + gcsEvent.getTimeCreated());
        logger.info("Updated: " + gcsEvent.getUpdated());
    }
}
Also used : Gson(com.google.gson.Gson) GcsEvent(functions.eventpojos.GcsEvent)

Example 4 with GcsEvent

use of functions.eventpojos.GcsEvent in project java-docs-samples by GoogleCloudPlatform.

the class OcrProcessImageTest method functionsOcrProcess_shouldDetectText.

@Test
public void functionsOcrProcess_shouldDetectText() throws IOException {
    GcsEvent gcsEvent = new GcsEvent();
    gcsEvent.setBucket(FUNCTIONS_BUCKET);
    gcsEvent.setName("wakeupcat.jpg");
    sampleUnderTest.accept(gcsEvent, null);
    List<LogRecord> logs = LOG_HANDLER.getStoredLogRecords();
    Truth.assertThat(logs.get(1).getMessage()).contains("Extracted text from image: Wake up human!");
    Truth.assertThat(logs.get(2).getMessage()).contains("Detected language en for file wakeupcat.jpg");
}
Also used : LogRecord(java.util.logging.LogRecord) GcsEvent(functions.eventpojos.GcsEvent) Test(org.junit.Test)

Example 5 with GcsEvent

use of functions.eventpojos.GcsEvent in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagick method getEventData.

// [END functions_imagemagick_blur]
// Converts CloudEvent data payload to a GcsEvent
private static GcsEvent getEventData(CloudEvent event) {
    if (event.getData() != null) {
        // Extract Cloud Event data and convert to GcsEvent
        String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
        Gson gson = new Gson();
        return gson.fromJson(cloudEventData, GcsEvent.class);
    }
    return new GcsEvent();
}
Also used : Gson(com.google.gson.Gson) GcsEvent(functions.eventpojos.GcsEvent)

Aggregations

GcsEvent (functions.eventpojos.GcsEvent)8 Gson (com.google.gson.Gson)6 Test (org.junit.Test)5 CloudEvent (io.cloudevents.CloudEvent)4 LogRecord (java.util.logging.LogRecord)2 BlobInfo (com.google.cloud.storage.BlobInfo)1 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)1 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)1 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)1 Feature (com.google.cloud.vision.v1.Feature)1 Image (com.google.cloud.vision.v1.Image)1 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)1 ImageSource (com.google.cloud.vision.v1.ImageSource)1 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)1 IOException (java.io.IOException)1 Date (java.util.Date)1