-
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
Changes from 3 commits
16a674b
bba4ff8
17d860f
fb919df
ae0ccb8
e5dbac0
a2b458c
ca26a77
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| # 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 | ||
| import subprocess | ||
|
|
||
| from google.cloud import storage, vision | ||
|
|
||
|
|
||
| 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 | ||
|
|
||
| # Exit if this is a deletion or a deploy event. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are these the best canonical ways of determine what kind of event it is? It seems a little haphazard to check for a name or state in this way as the only method.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Given that we can configure triggers to fire only on certain events (e.g. file writes), probably not. We can delete this code from the Node sample as well - but we'll want to explicitly specify which event to use in the docs.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you want to do in this situation then, leave it or change it somehow? We should be careful to follow the most straightforward, best-documented practice we can in either this or the Node case.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, I see it's been changed in the latest revision. Never mind. Thanks! |
||
| if 'name' not in file: | ||
| print('This is a deploy event.') | ||
| return | ||
| elif file.get('resource_state', None) == 'not_exists': | ||
| print('This is a deletion event.') | ||
| return | ||
|
|
||
| file_name = file['name'] | ||
| blob = storage_client.bucket(file['bucket']).get_blob(file_name) | ||
| blob_uri = 'gs://%s/%s' % (file['bucket'], file_name) | ||
|
andrewsg marked this conversation as resolved.
Outdated
|
||
| 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): | ||
| print(blob) | ||
|
ace-n marked this conversation as resolved.
Outdated
|
||
|
|
||
| file_name = blob.name | ||
| temp_local_filename = '/tmp/%s' % os.path.basename(file_name) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rather than hardcoding /tmp, can we use
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (One reason is to avoid filename conflicts or race conditions.)
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done (with |
||
|
|
||
| # 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. | ||
| subprocess.check_call([ | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there any in-Python way to do this, for instance by using Pillow or an ImageMagick binding for Python, that doesn't involve a subprocess call?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great, |
||
| 'convert', temp_local_filename, | ||
| '-channel', 'RGBA', | ||
| '-blur', '0x24', | ||
| 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] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # 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. | ||
|
|
||
| import uuid | ||
|
|
||
| from mock import MagicMock, patch | ||
|
|
||
| import main | ||
|
|
||
|
|
||
| class DictObject(dict): | ||
|
ace-n marked this conversation as resolved.
Outdated
|
||
| pass | ||
|
|
||
|
|
||
| @patch('main.__blur_image') | ||
| def test_do_nothing_on_delete(__blur_image, capsys): | ||
| __blur_image = MagicMock() | ||
| data = { | ||
| 'resource_state': 'not_exists', | ||
| 'name': '' | ||
| } | ||
|
|
||
| main.blur_offensive_images(data, None) | ||
|
|
||
| out, _ = capsys.readouterr() | ||
| assert 'This is a deletion event.' in out | ||
| assert __blur_image.called is False | ||
|
|
||
|
|
||
| @patch('main.__blur_image') | ||
| def test_do_nothing_on_deploy(__blur_image, capsys): | ||
| __blur_image = MagicMock() | ||
|
|
||
| main.blur_offensive_images({}, None) | ||
|
|
||
| out, _ = capsys.readouterr() | ||
| assert 'This is a deploy event.' in out | ||
| assert __blur_image.called is False | ||
|
|
||
|
|
||
| @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 = DictObject() | ||
| result.safe_search_annotation = DictObject() | ||
| 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 = { | ||
| 'resource_state': '', | ||
| '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 = DictObject() | ||
| result.safe_search_annotation = DictObject() | ||
| 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 = { | ||
| 'resource_state': '', | ||
| '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.subprocess') | ||
| def test_blur_image(subprocess_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)) | ||
|
|
||
| subprocess_mock.check_call = MagicMock() | ||
|
|
||
| blob = DictObject() | ||
| 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 subprocess_mock.check_call.called | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| google-cloud-vision==0.33.0 | ||
| google-cloud-storage==1.11.0 |
Uh oh!
There was an error while loading. Please reload this page.