ImageMagick implements BackgroundFunction<GcsEvent> { @Override public void accept(GcsEvent gcsEvent, Context context) { if (gcsEvent.getBucket() == null || gcsEvent.getName() == null) { logger.severe("Error: Malformed GCS event."); return; } BlobInfo blobInfo = BlobInfo.newBuilder(gcsEvent.getBucket(), gcsEvent.getName()).build(); String gcsPath = String.format("gs: logger.info(String.format("Analyzing %s", gcsEvent.getName())); 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); 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; } SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) { logger.info(String.format("Detected %s as inappropriate.", gcsEvent.getName())); blur(blobInfo); } else { logger.info(String.format("Detected %s as OK.", gcsEvent.getName())); } } } catch (IOException e) { logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e); } }  @Override // Blurs uploaded images that are flagged as Adult or Violence. void accept(GcsEvent gcsEvent, Context context);  }
@Test public void functionsImagemagickAnalyze_shouldBlurOffensiveImages() { String imageName = "zombie.jpg"; GcsEvent event = new GcsEvent(); event.setBucket(BUCKET_NAME); event.setName(imageName); new ImageMagick().accept(event, new MockContext()); List<LogRecord> logs = LOG_HANDLER.getStoredLogRecords(); String uploadedMessage = String.format( "Blurred image uploaded to: gs: assertThat(logs.get(2).getMessage()).isEqualTo(uploadedMessage); }
@Test public void functionsImagemagickAnalyze_shouldHandleSafeImages() { GcsEvent event = new GcsEvent(); event.setBucket(BUCKET_NAME); event.setName("wakeupcat.jpg"); new ImageMagick().accept(event, new MockContext()); assertThat(LOG_HANDLER.getStoredLogRecords().get(1).getMessage()).isEqualTo( "Detected wakeupcat.jpg as OK."); }
@Test public void functionsImagemagickAnalyze_shouldHandleMissingImages() { GcsEvent event = new GcsEvent(); event.setBucket(BUCKET_NAME); event.setName("missing.jpg"); new ImageMagick().accept(event, new MockContext()); assertThat(LOG_HANDLER.getStoredLogRecords().get(1).getMessage()).contains( "Error opening file"); }