Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions functions/imagemagick/README.md
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
73 changes: 73 additions & 0 deletions functions/imagemagick/main.py
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)
Copy link
Member

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.mkdtemp to get a random, guaranteed-temporary directory? (note, we should clean this up afterwards as well)

Copy link
Member

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.)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done (with mkstemp instead.)


# 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]
104 changes: 104 additions & 0 deletions functions/imagemagick/main_test.py
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
3 changes: 3 additions & 0 deletions functions/imagemagick/requirements.txt
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