From c3bb8f4aa406b4be8d3617d8858b2f73ad0583e1 Mon Sep 17 00:00:00 2001 From: Sam Wachspress Date: Tue, 14 Sep 2021 15:32:04 -0500 Subject: [PATCH] migrate cloud function to separate repo --- .gcloudignore | 12 ++++++++++++ README.md | 2 ++ main.py | 26 ++++++++++++++++++++++++++ requirements.txt | 2 ++ 4 files changed, 42 insertions(+) create mode 100644 .gcloudignore create mode 100644 README.md create mode 100644 main.py create mode 100644 requirements.txt diff --git a/.gcloudignore b/.gcloudignore new file mode 100644 index 00000000..a55ed18e --- /dev/null +++ b/.gcloudignore @@ -0,0 +1,12 @@ +# This file specifies files that are *not* uploaded to Google Cloud Platform +# using gcloud. It follows the same syntax as .gitignore, with the addition of +# "#!include" directives (which insert the entries of the given .gitignore-style +# file at that point). +# +# For more information, run: +# $ gcloud topic gcloudignore +# +.gcloudignore +# If you would like to upload your .git directory, .gitignore file or files +# from your .gitignore file, remove the corresponding line +# below: diff --git a/README.md b/README.md new file mode 100644 index 00000000..20d41b33 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Generate Thumbnails +Google Cloud Function to monitor photo directory of site content bucket and generate thumbnails when new images are added diff --git a/main.py b/main.py new file mode 100644 index 00000000..c8634d05 --- /dev/null +++ b/main.py @@ -0,0 +1,26 @@ +import re +from wand.image import Image +from google.cloud import storage + +client = storage.Client() + +def generate_thumbnails(data, context): + thumbnail_regex = "^photos\/Celegans\/.*\.thumb.(jpg|jpeg)$" + image_regex = "^photos\/Celegans\/.*\.(jpg|jpeg)$" + + # Only generate thumbnails for matching paths + is_image = re.search(image_regex, data['name']) + is_thumbnail = re.search(thumbnail_regex, data['name']) + + if (is_image and not is_thumbnail): + # Download the image and resize it + bucket = client.get_bucket(data['bucket']) + thumbnail = Image(blob=bucket.get_blob(data['name']).download_as_string()) + thumbnail.transform(resize='x200') + + # Upload the thumbnail with modified name + path = data['name'].rsplit('.', 1) + blob_name = path[0] + ".thumb." + path[1] + thumbnail_blob = bucket.blob(blob_name) + thumbnail_blob.upload_from_string(thumbnail.make_blob()) + \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..b7a466da --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +google-cloud-storage +wand \ No newline at end of file