Created
October 27, 2023 21:24
-
-
Save hselbie/fde69b900c4c719656ab42cdfb897b88 to your computer and use it in GitHub Desktop.
Cloud Function Safe Search
This file contains 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
import urllib.request | |
import flask | |
import functions_framework | |
from google.cloud import vision | |
def create_safe_dict(results): | |
response = { | |
"adult": results.adult, | |
"medical": results.medical, | |
"spoofed": results.spoof, | |
"violence": results.violence, | |
"racy": results.racy} | |
return response | |
@functions_framework.http | |
def safe_search(request: flask.Request) -> flask.Response: | |
"""BigQuery remote function to label input images. | |
Args: | |
request: HTTP request from BigQuery | |
https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#input_format | |
Returns: | |
HTTP response to BigQuery | |
https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#output_format | |
""" | |
try: | |
client = vision.ImageAnnotatorClient() | |
calls = request.get_json()["calls"] | |
replies = [] | |
for call in calls: | |
content = urllib.request.urlopen(call[0]).read() | |
image = vision.Image(content=content) | |
response = client.safe_search_detection(image=image) | |
safe = response.safe_search_annotation | |
# Names of likelihood from google.cloud.vision.enums | |
likelihood_name = ( | |
"UNKNOWN", | |
"VERY_UNLIKELY", | |
"UNLIKELY", | |
"POSSIBLE", | |
"LIKELY", | |
"VERY_LIKELY", | |
) | |
container = create_safe_dict(safe) | |
replies.append(container) | |
return flask.make_response(flask.jsonify({"replies": replies})) | |
except Exception as e: | |
return flask.make_response(flask.jsonify({"errorMessage": str(e)}), 400) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment