-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
74 lines (57 loc) · 2.26 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
import os
import base64
import tempfile
from werkzeug.utils import secure_filename
from ingredients_parser import ingredients_vision
from flask import jsonify, render_template, Flask, request
# Helper function that computes the filepath to save files to
def get_file_path(filename):
# Note: tempfile.gettempdir() points to an in-memory file system
# on GCF. Thus, any files in it must fit in the instance's memory.
file_name = secure_filename(filename)
return os.path.join(tempfile.gettempdir(), file_name)
app = Flask(__name__)
@app.route("/")
def upload_file():
return render_template("index.html")
@app.route("/ingredients", methods=["GET", "POST"])
def ingredients_parser():
""" Parses a 'multipart/form-data' upload request
Args:
request (flask.Request): The request object.
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
"""
# This code will process each non-file field in the form
fields = {}
data = request.form.to_dict()
for field in data:
fields[field] = data[field]
print("Processed field: %s" % field)
# This code will process each file uploaded
files = request.files.to_dict()
result_dict = {}
for file_name, file in files.items():
file_path = get_file_path(file_name)
file.save(file_path)
response = ingredients_vision.detect_document(file_path)
ingredients, allergens = ingredients_vision.extract_ingredients_and_allergens(
response
)
file_dict = {"ingredients": ingredients, "allergens": allergens}
print("Processed file: %s" % file_name)
# Clear temporary directory
for file_name in files:
file_path = get_file_path(file_name)
with open(file_path, "rb") as image_file:
encoded_image = base64.b64encode(image_file.read())
return render_template(
"ingredients.html",
ingredients=file_dict.get("ingredients") or "",
allergens=file_dict.get("allergens") or "",
image_data=encoded_image.decode("utf-8"),
)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0")