forked from smooth80/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
136 lines (103 loc) · 4.02 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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 datetime import datetime
import logging
import os
from flask import Flask, redirect, render_template, request
from google.cloud import datastore
from google.cloud import storage
from google.cloud import vision
CLOUD_STORAGE_BUCKET = os.environ.get("CLOUD_STORAGE_BUCKET")
app = Flask(__name__)
@app.route("/")
def homepage():
# Create a Cloud Datastore client.
datastore_client = datastore.Client()
# Use the Cloud Datastore client to fetch information from Datastore about
# each photo.
query = datastore_client.query(kind="Faces")
image_entities = list(query.fetch())
# Return a Jinja2 HTML template and pass in image_entities as a parameter.
return render_template("homepage.html", image_entities=image_entities)
@app.route("/upload_photo", methods=["GET", "POST"])
def upload_photo():
photo = request.files["file"]
# Create a Cloud Storage client.
storage_client = storage.Client()
# Get the bucket that the file will be uploaded to.
bucket = storage_client.get_bucket(CLOUD_STORAGE_BUCKET)
# Create a new blob and upload the file's content.
blob = bucket.blob(photo.filename)
blob.upload_from_string(photo.read(), content_type=photo.content_type)
# Make the blob publicly viewable.
blob.make_public()
# Create a Cloud Vision client.
vision_client = vision.ImageAnnotatorClient()
# Use the Cloud Vision client to detect a face for our image.
source_uri = "gs://{}/{}".format(CLOUD_STORAGE_BUCKET, blob.name)
image = vision.Image(source=vision.ImageSource(gcs_image_uri=source_uri))
faces = vision_client.face_detection(image=image).face_annotations
# If a face is detected, save to Datastore the likelihood that the face
# displays 'joy,' as determined by Google's Machine Learning algorithm.
if len(faces) > 0:
face = faces[0]
# Convert the likelihood string.
likelihoods = [
"Unknown",
"Very Unlikely",
"Unlikely",
"Possible",
"Likely",
"Very Likely",
]
face_joy = likelihoods[face.joy_likelihood]
else:
face_joy = "Unknown"
# Create a Cloud Datastore client.
datastore_client = datastore.Client()
# Fetch the current date / time.
current_datetime = datetime.now()
# The kind for the new entity.
kind = "Faces"
# The name/ID for the new entity.
name = blob.name
# Create the Cloud Datastore key for the new entity.
key = datastore_client.key(kind, name)
# Construct the new entity using the key. Set dictionary values for entity
# keys blob_name, storage_public_url, timestamp, and joy.
entity = datastore.Entity(key)
entity["blob_name"] = blob.name
entity["image_public_url"] = blob.public_url
entity["timestamp"] = current_datetime
entity["joy"] = face_joy
# Save the new entity to Datastore.
datastore_client.put(entity)
# Redirect to the home page.
return redirect("/")
@app.errorhandler(500)
def server_error(e):
logging.exception("An error occurred during a request.")
return (
"""
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(
e
),
500,
)
if __name__ == "__main__":
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host="127.0.0.1", port=8080, debug=True)