Pic-a-daily: Lab 1—Store and analyse pictures (Java)

1. Overview

In the first code lab, you will upload pictures in a bucket. This will generate a file creation event that will be handled by a function. The function will make a call to Vision API to do image analysis and save results in a datastore.

d650ca5386ea71ad.png

What you'll learn

  • Cloud Storage
  • Cloud Functions
  • Cloud Vision API
  • Cloud Firestore

2. Setup and Requirements

Self-paced environment setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.

b35bf95b8bf3d5d8.png

a99b7ace416376c4.png

bd84a6d3004737c5.png

  • The Project name is the display name for this project's participants. It is a character string not used by Google APIs. You can update it at any time.
  • The Project ID must be unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference the Project ID (it is typically identified as PROJECT_ID). If you don't like the generated ID, you may generate another random one. Alternatively, you can try your own and see if it's available. It cannot be changed after this step and will remain for the duration of the project.
  • For your information, there is a third value, a Project Number which some APIs use. Learn more about all three of these values in the documentation.
  1. Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab shouldn't cost much, if anything at all. To shut down resources so you don't incur billing beyond this tutorial, you can delete the resources you created or delete the whole project. New users of Google Cloud are eligible for the $300 USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the Google Cloud Console, click the Cloud Shell icon on the top right toolbar:

55efc1aaa7a4d3ad.png

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

7ffe5cbb04455448.png

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this codelab can be done within a browser. You do not need to install anything.

3. Enable APIs

For this lab, you will be using Cloud Functions and Vision API but first they need to be enabled either in Cloud Console or with gcloud.

To enable Vision API in Cloud Console, search for Cloud Vision API in the search bar:

cf48b1747ba6a6fb.png

You will land on the Cloud Vision API page:

ba4af419e6086fbb.png

Click the ENABLE button.

Alternatively, you can also enable it Cloud Shell using the gcloud command line tool.

Inside Cloud Shell, run the following command:

gcloud services enable vision.googleapis.com

You should see the operation to finish successfully:

Operation "operations/acf.12dba18b-106f-4fd2-942d-fea80ecc5c1c" finished successfully.

Enable Cloud Functions as well:

gcloud services enable cloudfunctions.googleapis.com

4. Create the bucket (console)

Create a storage bucket for the pictures. You can do this from Google Cloud Platform console ( console.cloud.google.com) or with gsutil command line tool from Cloud Shell or your local development environment.

From the "hamburger" (☰) menu, navigate to the Storage page.

1930e055d138150a.png

Name your bucket

Click on the CREATE BUCKET button.

34147939358517f8.png

Click CONTINUE.

Choose Location

197817f20be07678.png

Create a multi-regional bucket in the region of your choice (here Europe).

Click CONTINUE.

Choose default storage class

53cd91441c8caf0e.png

Choose the Standard storage class for your data.

Click CONTINUE.

Set Access Control

8c2b3b459d934a51.png

As you will be working with publicly accessible images, you want all our pictures stored in this bucket to have the same uniform access control.

Choose the Uniform access control option.

Click CONTINUE.

Set Protection/Encryption

d931c24c3e705a68.png

Keep default (Google-managed key), as you won't use your own encryption keys.

Click CREATE, to eventually finalize our bucket creation.

Add allUsers as storage viewer

Go to the Permissions tab:

d0ecfdcff730ea51.png

Add an allUsers member to the bucket, with a role of Storage > Storage Object Viewer, as follows:

e9f25ec1ea0b6cc6.png

Click SAVE.

5. Create the bucket (gsutil)

You can also use the gsutil command line tool in Cloud Shell to create buckets.

In Cloud Shell, set a variable for the unique bucket name. Cloud Shell already has GOOGLE_CLOUD_PROJECT set to your unique project id. You can append that to the bucket name.

For example:

export BUCKET_PICTURES=uploaded-pictures-${GOOGLE_CLOUD_PROJECT}

Create a standard multi-region zone in Europe:

gsutil mb -l EU gs://${BUCKET_PICTURES}

Ensure uniform bucket level access:

gsutil uniformbucketlevelaccess set on gs://${BUCKET_PICTURES}

Make the bucket public:

gsutil iam ch allUsers:objectViewer gs://${BUCKET_PICTURES}

If you go to Cloud Storage section of the console, you should have a public uploaded-pictures bucket:

a98ed4ba17873e40.png

Test that you can upload pictures to the bucket and the uploaded pictures are publicly available, as explained in the previous step.

6. Test public access to the bucket

Going back to the storage browser, you'll see your bucket in the list, with "Public" access (including a warning sign reminding you that anyone has access to the content of that bucket).

89e7a4d2c80a0319.png

Your bucket is now ready to receive pictures.

If you click on the bucket name, you'll see the bucket details.

131387f12d3eb2d3.png

There, you can try the Upload files button, to test that you can add a picture to the bucket. A file chooser popup will ask you to select a file. Once selected, it'll be uploaded to your bucket, and you will see again the public access that has been automatically attributed to this new file.

e87584471a6e9c6d.png

Along the Public access label, you will also see a little link icon. When clicking on it, your browser will navigate to the public URL of that image, which will be of the form:

https://storage.googleapis.com/BUCKET_NAME/PICTURE_FILE.png

With BUCKET_NAME being the globally unique name you have chosen for your bucket, and then the file name of your picture.

By clicking on the check box along the picture name, the DELETE button will be enabled, and you can delete this first image.

7. Create the function

In this step, you create a function that reacts to picture upload events.

Visit the Cloud Functions section of the Google Cloud console. By visiting it, the Cloud Functions service will be automatically enabled.

9d29e8c026a7a53f.png

Click on Create function.

Choose a name (eg. picture-uploaded) and the Region (remember to be consistent with the region choice for the bucket):

4bb222633e6f278.png

There are two kinds of functions:

  • HTTP functions which can be invoked via a URL (ie. a web API),
  • Background functions which can be triggered by some event.

You want to create a background function that is triggered when a new file is uploaded to our Cloud Storage bucket:

d9a12fcf58f4813c.png

You are interested in the Finalize/Create event type, which is the event that is triggered when a file is created or updated in the bucket:

b30c8859b07dc4cb.png

Select the bucket created before, to tell Cloud Functions to be notified when a file is created / updated in this particular bucket:

cb15a1f4c7a1ca5f.png

Click Select to choose the bucket you created earlier, and then Save

c1933777fac32c6a.png

Before you click Next, you can expand and modify the defaults (256 MB memory) under Runtime, build, connections and security settings and update it to 1GB.

83d757e6c38e10.png

After clicking Next, you can tune the Runtime, Source code and entry point.

Keep the Inline editor for this function:

b6646ec646082b32.png

Select one of the Java runtimes, for example Java 11:

f85b8a6f951f47a7.png

The source code consists of an Java file, and a pom.xml Maven file that provides various metadata and dependencies.

Leave the default snippet of code: it logs the file name of the uploaded picture:

9b7b9801b42f6ca6.png

For now, keep the name of the function to execute to Example, for testing purposes.

Click on Deploy to create and deploy the function. Once the deployment succeeded, you should see a green-circled check mark in the list of functions:

3732fdf409eefd1a.png

8. Test the function

In this step, test that the function responds to storage events.

From the "hamburger" (☰) menu, navigate back to the Storage page.

Click on the images bucket, and then on Upload files to upload an image.

21767ec3cb8b18de.png

Navigate again within the cloud console to go to the Logging > Logs Explorer page.

In the Log Fields selector, select Cloud Function to see the logs dedicated to your functions. Scroll down through the Log Fields and you can even select a specific function to have a finer-grained view of the functions related logs. Select the picture-uploaded function.

You should see the log items mentioning the creation of the function, the start and end times of the function, and our actual log statement:

e8ba7d39c36df36c.png

Our log statement reads: Processing file: pic-a-daily-architecture-events.png, meaning that the event related to the creation and storage of this picture has indeed been triggered as expected.

9. Prepare the database

You will store information about the picture given by the Vision API into the Cloud Firestore database, a fast, fully managed, serverless, cloud-native NoSQL document database. Prepare your database by going to the Firestore section of the Cloud Console:

9e4708d2257de058.png

Two options are offered: Native mode or Datastore mode. Use the native mode, which offers extra features like offline support and real-time synchronization.

Click on SELECT NATIVE MODE.

9449ace8cc84de43.png

Pick a multi-region (here in Europe, but ideally at least the same region your function and storage bucket are).

Click the CREATE DATABASE button.

Once the database is created, you should see the following:

56265949a124819e.png

Create a new collection by clicking the + START COLLECTION button.

Name collection pictures.

75806ee24c4e13a7.png

You don't need to create a document. You'll add them programmatically as new pictures are stored in Cloud Storage and analysed by the Vision API.

Click Save.

Firestore creates a first default document in the newly created collection, you can safely delete that document as it doesn't contain any useful information:

5c2f1e17ea47f48f.png

The documents that will be created programmatically in our collection will contain 4 fields:

  • name (string): the file name of the uploaded picture, which is also he key of the document
  • labels (array of strings): the labels of recognised items by the Vision API
  • color (string): the hexadecimal color code of the dominant color (ie. #ab12ef)
  • created (date): the timestamp of when this image's metadata was stored
  • thumbnail (boolean): an optional field that will be present and be true if a thumbnail image has been generated for this picture

As we will be searching in Firestore to find pictures that have thumbnails available, and sorting along the creation date, we'll need to create a search index.

You can create the index with the following command in Cloud Shell:

gcloud firestore indexes composite create \
  --collection-group=pictures \
  --field-config field-path=thumbnail,order=descending \
  --field-config field-path=created,order=descending

Or you can also do it from the Cloud Console, by clicking on Indexes, in the navigation column on the left, and then creating a composite index as shown below:

ecb8b95e3c791272.png

Click Create. Index creation can take a few minutes.

10. Update the function

Move back to the Functions page, to update the function to invoke the Vision API to analyze our pictures, and to store the metadata in Firestore.

From the "hamburger" (☰) menu, navigate to the Cloud Functions section, click on the function name, select the Source tab, and then click the EDIT button.

First, edit the pom.xml file which lists the dependencies of our Java function. Update the code to add the Cloud Vision API Maven dependency:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cloudfunctions</groupId>
  <artifactId>gcs-function</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>26.1.1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.0.4</version>
      <type>jar</type>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-firestore</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-vision</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-storage</artifactId>
    </dependency>
  </dependencies>

  <!-- Required for Java 11 functions in the inline editor -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <excludes>
            <exclude>.google/</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Now that the dependencies are up-to-date, you are going to work on the code of our function, by updating the Example.java file with our custom code.

Move the mouse over the Example.java file and click the pencil. Replace the package name and file name to src/main/java/fn/ImageAnalysis.java.

Replace the code in ImageAnalysis.java with the code below. It will be explained in the next step.

package fn;

import com.google.cloud.functions.*;
import com.google.cloud.vision.v1.*;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.firestore.*;
import com.google.api.core.ApiFuture;

import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.util.concurrent.*;
import java.util.logging.Logger;

import fn.ImageAnalysis.GCSEvent;

public class ImageAnalysis implements BackgroundFunction<GCSEvent> {
    private static final Logger logger = Logger.getLogger(ImageAnalysis.class.getName());

    @Override
    public void accept(GCSEvent event, Context context) 
            throws IOException, InterruptedException, ExecutionException {
        String fileName = event.name;
        String bucketName = event.bucket;

        logger.info("New picture uploaded " + fileName);

        try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
            List<AnnotateImageRequest> requests = new ArrayList<>();
            
            ImageSource imageSource = ImageSource.newBuilder()
                .setGcsImageUri("gs://" + bucketName + "/" + fileName)
                .build();

            Image image = Image.newBuilder()
                .setSource(imageSource)
                .build();

            Feature featureLabel = Feature.newBuilder()
                .setType(Type.LABEL_DETECTION)
                .build();
            Feature featureImageProps = Feature.newBuilder()
                .setType(Type.IMAGE_PROPERTIES)
                .build();
            Feature featureSafeSearch = Feature.newBuilder()
                .setType(Type.SAFE_SEARCH_DETECTION)
                .build();
                
            AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
                .addFeatures(featureLabel)
                .addFeatures(featureImageProps)
                .addFeatures(featureSafeSearch)
                .setImage(image)
                .build();
            
            requests.add(request);

            logger.info("Calling the Vision API...");
            BatchAnnotateImagesResponse result = vision.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = result.getResponsesList();

            if (responses.size() == 0) {
                logger.info("No response received from Vision API.");
                return;
            }

            AnnotateImageResponse response = responses.get(0);
            if (response.hasError()) {
                logger.info("Error: " + response.getError().getMessage());
                return;
            }

            List<String> labels = response.getLabelAnnotationsList().stream()
                .map(annotation -> annotation.getDescription())
                .collect(Collectors.toList());
            logger.info("Annotations found:");
            for (String label: labels) {
                logger.info("- " + label);
            }

            String mainColor = "#FFFFFF";
            ImageProperties imgProps = response.getImagePropertiesAnnotation();
            if (imgProps.hasDominantColors()) {
                DominantColorsAnnotation colorsAnn = imgProps.getDominantColors();
                ColorInfo colorInfo = colorsAnn.getColors(0);

                mainColor = rgbHex(
                    colorInfo.getColor().getRed(), 
                    colorInfo.getColor().getGreen(), 
                    colorInfo.getColor().getBlue());

                logger.info("Color: " + mainColor);
            }

            boolean isSafe = false;
            if (response.hasSafeSearchAnnotation()) {
                SafeSearchAnnotation safeSearch = response.getSafeSearchAnnotation();

                isSafe = Stream.of(
                    safeSearch.getAdult(), safeSearch.getMedical(), safeSearch.getRacy(),
                    safeSearch.getSpoof(), safeSearch.getViolence())
                .allMatch( likelihood -> 
                    likelihood != Likelihood.LIKELY && likelihood != Likelihood.VERY_LIKELY
                );

                logger.info("Safe? " + isSafe);
            }

            // Saving result to Firestore
            if (isSafe) {
                FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance();
                Firestore pictureStore = firestoreOptions.getService();

                DocumentReference doc = pictureStore.collection("pictures").document(fileName);

                Map<String, Object> data = new HashMap<>();
                data.put("labels", labels);
                data.put("color", mainColor);
                data.put("created", new Date());

                ApiFuture<WriteResult> writeResult = doc.set(data, SetOptions.merge());

                logger.info("Picture metadata saved in Firestore at " + writeResult.get().getUpdateTime());
            }
        }
    }

    private static String rgbHex(float red, float green, float blue) {
        return String.format("#%02x%02x%02x", (int)red, (int)green, (int)blue);
    }

    public static class GCSEvent {
        String bucket;
        String name;
    }
}

968749236c3f01da.png

11. Explore the function

Let's have a closer look at the various interesting parts.

First, we're including the specific dependencies in the Maven pom.xml file. Google Java Client Libraries publishes a Bill-of-Materials(BOM), to eliminate any dependency conflicts. By using it, you do not have to specify any version for the individual Google client Libraries

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>26.1.1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

Then, we prepare a client for the Vision API:

...
try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
...

Now comes the structure of our function. We capture from the incoming event the fields we are interested in and map them to the GCSEvent structure we define:

...
public class ImageAnalysis implements BackgroundFunction<GCSEvent> {
    @Override
    public void accept(GCSEvent event, Context context) 
            throws IOException, InterruptedException,     
    ExecutionException {
...

    public static class GCSEvent {
        String bucket;
        String name;
    }

Notice the signature, but also how we retrieve the name of the file and bucket which triggered the Cloud Function.

For reference, here's what the event payload looks like:

{
  "bucket":"uploaded-pictures",
  "contentType":"image/png",
  "crc32c":"efhgyA==",
  "etag":"CKqB956MmucCEAE=",
  "generation":"1579795336773802",
  "id":"uploaded-pictures/Screenshot.png/1579795336773802",
  "kind":"storage#object",
  "md5Hash":"PN8Hukfrt6C7IyhZ8d3gfQ==",
  "mediaLink":"https://www.googleapis.com/download/storage/v1/b/uploaded-pictures/o/Screenshot.png?generation=1579795336773802&alt=media",
  "metageneration":"1",
  "name":"Screenshot.png",
  "selfLink":"https://www.googleapis.com/storage/v1/b/uploaded-pictures/o/Screenshot.png",
  "size":"173557",
  "storageClass":"STANDARD",
  "timeCreated":"2020-01-23T16:02:16.773Z",
  "timeStorageClassUpdated":"2020-01-23T16:02:16.773Z",
  "updated":"2020-01-23T16:02:16.773Z"
}

We prepare a request to send via the Vision client:

ImageSource imageSource = ImageSource.newBuilder()
    .setGcsImageUri("gs://" + bucketName + "/" + fileName)
    .build();

Image image = Image.newBuilder()
    .setSource(imageSource)
    .build();

Feature featureLabel = Feature.newBuilder()
    .setType(Type.LABEL_DETECTION)
    .build();
Feature featureImageProps = Feature.newBuilder()
    .setType(Type.IMAGE_PROPERTIES)
    .build();
Feature featureSafeSearch = Feature.newBuilder()
    .setType(Type.SAFE_SEARCH_DETECTION)
    .build();
    
AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
    .addFeatures(featureLabel)
    .addFeatures(featureImageProps)
    .addFeatures(featureSafeSearch)
    .setImage(image)
    .build();

We're asking for 3 key capabilities of the Vision API:

  • Label detection: to understand what's in those pictures
  • Image properties: to give interesting attributes of the picture (we're interested in the dominant color of the picture)
  • Safe search: to know if the image is safe to show (it shouldn't contain adult / medical / racy / violent content)

At this point, we can make the call to the Vision API:

...
logger.info("Calling the Vision API...");
BatchAnnotateImagesResponse result = 
                            vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = result.getResponsesList();
...

For reference, here's what the response from the Vision API looks like:

{
  "faceAnnotations": [],
  "landmarkAnnotations": [],
  "logoAnnotations": [],
  "labelAnnotations": [
    {
      "locations": [],
      "properties": [],
      "mid": "/m/01yrx",
      "locale": "",
      "description": "Cat",
      "score": 0.9959855675697327,
      "confidence": 0,
      "topicality": 0.9959855675697327,
      "boundingPoly": null
    },
     - - - 
  ],
  "textAnnotations": [],
  "localizedObjectAnnotations": [],
  "safeSearchAnnotation": {
    "adult": "VERY_UNLIKELY",
    "spoof": "UNLIKELY",
    "medical": "VERY_UNLIKELY",
    "violence": "VERY_UNLIKELY",
    "racy": "VERY_UNLIKELY",
    "adultConfidence": 0,
    "spoofConfidence": 0,
    "medicalConfidence": 0,
    "violenceConfidence": 0,
    "racyConfidence": 0,
    "nsfwConfidence": 0
  },
  "imagePropertiesAnnotation": {
    "dominantColors": {
      "colors": [
        {
          "color": {
            "red": 203,
            "green": 201,
            "blue": 201,
            "alpha": null
          },
          "score": 0.4175916016101837,
          "pixelFraction": 0.44456374645233154
        },
         - - - 
      ]
    }
  },
  "error": null,
  "cropHintsAnnotation": {
    "cropHints": [
      {
        "boundingPoly": {
          "vertices": [
            { "x": 0, "y": 118 },
            { "x": 1177, "y": 118 },
            { "x": 1177, "y": 783 },
            { "x": 0, "y": 783 }
          ],
          "normalizedVertices": []
        },
        "confidence": 0.41695669293403625,
        "importanceFraction": 1
      }
    ]
  },
  "fullTextAnnotation": null,
  "webDetection": null,
  "productSearchResults": null,
  "context": null
}

If there's no error returned, we can move on, hence why we have this if block:

AnnotateImageResponse response = responses.get(0);
if (response.hasError()) {
     logger.info("Error: " + response.getError().getMessage());
     return;
}

We are going to get the labels of the things, categories or themes recognised in the picture:

List<String> labels = response.getLabelAnnotationsList().stream()
    .map(annotation -> annotation.getDescription())
    .collect(Collectors.toList());

logger.info("Annotations found:");
for (String label: labels) {
    logger.info("- " + label);
}

We're interested in knowing the dominant color of the picture:

String mainColor = "#FFFFFF";
ImageProperties imgProps = response.getImagePropertiesAnnotation();
if (imgProps.hasDominantColors()) {
    DominantColorsAnnotation colorsAnn = 
                               imgProps.getDominantColors();
    ColorInfo colorInfo = colorsAnn.getColors(0);

    mainColor = rgbHex(
        colorInfo.getColor().getRed(), 
        colorInfo.getColor().getGreen(), 
        colorInfo.getColor().getBlue());

    logger.info("Color: " + mainColor);
}

We're also using a utility function to transform the red / green / blue values into an hexadecimal color code that we can use in CSS stylesheets.

Let's check if the picture is safe to show:

boolean isSafe = false;
if (response.hasSafeSearchAnnotation()) {
    SafeSearchAnnotation safeSearch = 
                      response.getSafeSearchAnnotation();

    isSafe = Stream.of(
        safeSearch.getAdult(), safeSearch.getMedical(), safeSearch.getRacy(),
        safeSearch.getSpoof(), safeSearch.getViolence())
    .allMatch( likelihood -> 
        likelihood != Likelihood.LIKELY && likelihood != Likelihood.VERY_LIKELY
    );

    logger.info("Safe? " + isSafe);
}

We're checking the adult / spoof / medical / violence / racy attributes to see if they are not likely or very likely.

If the result of the safe search is okay, we can store metadata in Firestore:

if (isSafe) {
    FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance();
    Firestore pictureStore = firestoreOptions.getService();

    DocumentReference doc = pictureStore.collection("pictures").document(fileName);

    Map<String, Object> data = new HashMap<>();
    data.put("labels", labels);
    data.put("color", mainColor);
    data.put("created", new Date());

    ApiFuture<WriteResult> writeResult = doc.set(data, SetOptions.merge());

    logger.info("Picture metadata saved in Firestore at " + writeResult.get().getUpdateTime());
}

12. Deploy the function

Time to deploy the function.

604f47aa11fbf8e.png

Hit DEPLOY button and the new version will be deployed, you can see the progress:

13da63f23e4dbbdd.png

13. Test the function again

Once the function is successfully deployed, you will post a picture to Cloud Storage, see if our function is invoked, what the Vision API returns, and if metadata is stored in Firestore.

Navigate back to Cloud Storage, and click on the bucket we created at the beginning of the lab:

d44c1584122311c7.png

Once in the bucket details page, click on the Upload files button to upload a picture.

26bb31d35fb6aa3d.png

From the "hamburger" (☰) menu, navigate to the Logging > Logs Explorer.

In the Log Fields selector, select Cloud Function to see the logs dedicated to your functions. Scroll down through the Log Fields and you can even select a specific function to have a finer-grained view of the functions related logs. Select the picture-uploaded function.

b651dca7e25d5b11.png

And indeed, in the list of logs, I can see that our function was invoked:

d22a7f24954e4f63.png

The logs indicate the start and end of the function execution. And in between, we can see the logs we put in our function with the console.log() statements. We see:

  • The details of the event triggering our function,
  • The raw results from the Vision API call,
  • The labels that were found in the picture we uploaded,
  • The dominant colors information,
  • Whether the picture is safe to show,
  • And eventually those metadata about the picture have been stored in Firestore.

9ff7956a215c15da.png

Again from the "hamburger" (☰) menu, go to the Firestore section. In the Data subsection (shown by default), you should see the pictures collection with a new document added, corresponding to the picture you just uploaded:

a6137ab9687da370.png

14. Clean up (Optional)

If you don't intend to continue with the other labs in the series, you can clean up resources to save costs and to be an overall good cloud citizen. You can clean up resources individually as follows.

Delete the bucket:

gsutil rb gs://${BUCKET_PICTURES}

Delete the function:

gcloud functions delete picture-uploaded --region europe-west1 -q

Delete the Firestore collection by selecting Delete collection from the collection:

410b551c3264f70a.png

Alternatively, you can delete the whole project:

gcloud projects delete ${GOOGLE_CLOUD_PROJECT} 

15. Congratulations!

Congratulations! You've successfully implemented the first key service of the project!

What we've covered

  • Cloud Storage
  • Cloud Functions
  • Cloud Vision API
  • Cloud Firestore

Next Steps