-
Notifications
You must be signed in to change notification settings - Fork 6.7k
Add GCF imagemagick samples #1684
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
16a674b
Initial commit of imagemagick sample
bba4ff8
Add unit tests + get them passing
17d860f
Get sample working on GCF
fb919df
Address comments, pt 1
ae0ccb8
Address comments, pt 2
e5dbac0
Use UserDict instead of DictObject
a2b458c
Address comments
ca26a77
Use format strings + make function idempotent
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| <img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/> | ||
|
|
||
| # Google Cloud Functions ImageMagick sample | ||
|
|
||
| This sample shows you how to blur an image using ImageMagick in a | ||
| Storage-triggered Cloud Function. | ||
|
|
||
| View the [source code][code]. | ||
|
|
||
| [code]: main.py | ||
|
|
||
| ## Deploy and Test | ||
|
|
||
| 1. Follow the [Cloud Functions quickstart guide][quickstart] to setup Cloud | ||
| Functions for your project. | ||
|
|
||
| 1. Clone this repository: | ||
|
|
||
| git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git | ||
| cd python-docs-samples/functions/imagemagick | ||
|
|
||
| 1. Create a Cloud Storage Bucket: | ||
|
|
||
| gsutil mb gs://YOUR_BUCKET_NAME | ||
|
|
||
| This storage bucket is used to upload images for the function to check. | ||
|
|
||
| 1. Deploy the `blur_offensive_images` function with a Storage trigger: | ||
|
|
||
| gcloud functions deploy blur_offensive_images --trigger-bucket=YOUR_BUCKET_NAME --runtime python37 | ||
|
|
||
| * Replace `YOUR_BUCKET_NAME` with the name of the Cloud Storage Bucket you created earlier. | ||
|
|
||
| 1. Upload an offensive image to the Storage bucket, such as this image of | ||
| a flesh-eating zombie: https://cdn.pixabay.com/photo/2015/09/21/14/24/zombie-949916_1280.jpg | ||
|
|
||
| 1. Check the logs for the `blur_offensive_images` function: | ||
|
|
||
| gcloud functions get-logs blur_offensive_images | ||
|
|
||
| You should see something like this in your console: | ||
|
|
||
| D ... User function triggered, starting execution | ||
| I ... `The image zombie.jpg has been detected as inappropriate.` | ||
| D ... Execution took 1 ms, user function completed successfully | ||
|
|
||
| [quickstart]: https://cloud.google.com/functions/quickstart |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| # Copyright 2018 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the 'License'); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an 'AS IS' BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
|
|
||
| # [START functions_imagemagick_setup] | ||
| import os | ||
|
|
||
| from google.cloud import storage, vision | ||
| from wand.image import Image | ||
|
|
||
| storage_client = storage.Client() | ||
| vision_client = vision.ImageAnnotatorClient() | ||
| # [END functions_imagemagick_setup] | ||
|
|
||
|
|
||
| # [START functions_imagemagick_analyze] | ||
| # Blurs uploaded images that are flagged as Adult or Violence. | ||
| def blur_offensive_images(data, context): | ||
| file_data = data | ||
|
|
||
| file_name = file_data['name'] | ||
| blob = storage_client.bucket(file_data['bucket']).get_blob(file_name) | ||
| blob_uri = 'gs://%s/%s' % (file_data['bucket'], file_name) | ||
| blob_source = {'source': {'image_uri': blob_uri}} | ||
|
|
||
| print('Analyzing %s.' % file_name) | ||
|
|
||
| result = vision_client.safe_search_detection(blob_source) | ||
| detected = result.safe_search_annotation | ||
|
|
||
| if detected.adult == 5 or detected.violence == 5: | ||
| print('The image %s was detected as inappropriate.' % file_name) | ||
| return __blur_image(blob) | ||
| else: | ||
| print('The image %s was detected as OK.' % file_name) | ||
| # [END functions_imagemagick_analyze] | ||
|
|
||
|
|
||
| # [START functions_imagemagick_blur] | ||
| # Blurs the given file using ImageMagick. | ||
| def __blur_image(blob): | ||
| file_name = blob.name | ||
| temp_local_filename = '/tmp/%s' % os.path.basename(file_name) | ||
|
|
||
| # Download file from bucket. | ||
| blob.download_to_filename(temp_local_filename) | ||
| print('Image %s was downloaded to %s.' % (file_name, temp_local_filename)) | ||
|
|
||
| # Blur the image using ImageMagick. | ||
| with Image(filename=temp_local_filename) as image: | ||
| image.resize(*image.size, blur=16, filter='hamming') | ||
| image.save(filename=temp_local_filename) | ||
|
|
||
| print('Image %s was blurred.' % file_name) | ||
|
|
||
| # Upload the Blurred image back into the bucket. | ||
| blob.upload_from_filename(temp_local_filename) | ||
| print('Blurred image was uploaded to %s.' % file_name) | ||
|
|
||
| # Delete the temporary file. | ||
| os.remove(temp_local_filename) | ||
| # [END functions_imagemagick_blur] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # Copyright 2018 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the 'License'); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an 'AS IS' BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from collections import UserDict | ||
| import uuid | ||
|
|
||
| from mock import MagicMock, patch | ||
|
|
||
| import main | ||
|
|
||
|
|
||
| @patch('main.__blur_image') | ||
| @patch('main.vision_client') | ||
| @patch('main.storage_client') | ||
| def test_process_offensive_image( | ||
| __blur_image, | ||
| vision_client, | ||
| storage_client, | ||
| capsys): | ||
| result = UserDict() | ||
| result.safe_search_annotation = UserDict() | ||
| result.safe_search_annotation.adult = 5 | ||
| result.safe_search_annotation.violence = 5 | ||
| vision_client.safe_search_detection = MagicMock(return_value=result) | ||
|
|
||
| filename = str(uuid.uuid4()) | ||
| data = { | ||
| 'bucket': 'my-bucket', | ||
| 'name': filename | ||
| } | ||
|
|
||
| main.blur_offensive_images(data, None) | ||
|
|
||
| out, _ = capsys.readouterr() | ||
| assert 'Analyzing %s.' % filename in out | ||
| assert 'The image %s was detected as inappropriate.' % filename in out | ||
| assert main.__blur_image.called | ||
|
|
||
|
|
||
| @patch('main.__blur_image') | ||
| @patch('main.vision_client') | ||
| @patch('main.storage_client') | ||
| def test_process_safe_image( | ||
| __blur_image, | ||
| vision_client, | ||
| storage_client, | ||
| capsys): | ||
| result = UserDict() | ||
| result.safe_search_annotation = UserDict() | ||
| result.safe_search_annotation.adult = 1 | ||
| result.safe_search_annotation.violence = 1 | ||
| vision_client.safe_search_detection = MagicMock(return_value=result) | ||
|
|
||
| filename = str(uuid.uuid4()) | ||
| data = { | ||
| 'bucket': 'my-bucket', | ||
| 'name': filename | ||
| } | ||
|
|
||
| main.blur_offensive_images(data, None) | ||
|
|
||
| out, _ = capsys.readouterr() | ||
| assert 'Analyzing %s.' % filename in out | ||
| assert 'The image %s was detected as OK.' % filename in out | ||
| assert __blur_image.called is False | ||
|
|
||
|
|
||
| @patch('main.os') | ||
| @patch('main.Image') | ||
| def test_blur_image(image_mock, os_mock, capsys): | ||
| filename = str(uuid.uuid4()) | ||
|
|
||
| os_mock.remove = MagicMock() | ||
| os_mock.path = MagicMock() | ||
| os_mock.path.basename = MagicMock(side_effect=(lambda x: x)) | ||
|
|
||
| image_mock.return_value = image_mock | ||
| image_mock.__enter__.return_value = image_mock | ||
|
|
||
| blob = UserDict() | ||
| blob.name = filename | ||
| blob.download_to_filename = MagicMock() | ||
| blob.upload_from_filename = MagicMock() | ||
|
|
||
| main.__blur_image(blob) | ||
|
|
||
| out, _ = capsys.readouterr() | ||
|
|
||
| assert 'Image %s was downloaded to /tmp/%s.' % (filename, filename) in out | ||
| assert 'Image %s was blurred.' % filename in out | ||
| assert 'Blurred image was uploaded to %s.' % filename in out | ||
| assert os_mock.remove.called | ||
| assert image_mock.resize.called |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| google-cloud-vision==0.33.0 | ||
| google-cloud-storage==1.11.0 | ||
| Wand==0.4.4 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rather than hardcoding /tmp, can we use
tempfile.mkdtempto get a random, guaranteed-temporary directory? (note, we should clean this up afterwards as well)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(One reason is to avoid filename conflicts or race conditions.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done (with
mkstempinstead.)