-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapp.py
102 lines (83 loc) · 2.79 KB
/
app.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
import os
from flask import (
Flask,
flash,
request,
redirect,
url_for,
send_from_directory,
after_this_request,
)
from werkzeug.utils import secure_filename
from logodetect import constants
from logodetect.recognizer import append_to_file_name, Recognizer
if "LOCAL" == os.environ:
LOCAL = os.environ["LOCAL"]
else:
LOCAL = True
PATH_EXEMPLARS = constants.PATH_EXEMPLARS
UPLOAD_FOLDER = "."
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "mp4"}
app = Flask(__name__)
app.secret_key = "logodetect key"
if LOCAL:
print("applying CORS headers")
from flask_cors import CORS
cors = CORS(app)
app.config["CORS_HEADERS"] = "Content-Type"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
RECOGNIZER = Recognizer(exemplars_path=PATH_EXEMPLARS)
def allowed_file(filename):
"""Check if this is an allowed file extension.
:param filename: name of the file to upload
:return: boolean
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/", methods=["GET", "POST"])
def predict_image():
"""HTTP request for either rendering the upload form (GET) or
sending the request form data to the logo detector and returning
the resulting image (POST).
:return:
"""
if request.method == "POST":
if "image" not in request.files:
flash("No file part")
return redirect(request.url)
image = request.files["image"]
if image.filename == "":
flash("No selected file")
return redirect(request.url)
if image and allowed_file(image.filename):
filename = secure_filename(image.filename)
local_file = os.path.join(app.config["UPLOAD_FOLDER"], filename)
image.save(local_file)
RECOGNIZER.predict_image(local_file)
os.remove(local_file)
prediction = append_to_file_name(filename, "_output")
return redirect(url_for("processed_image", image=prediction))
return """
<!doctype html>
<title>Upload image file for detection</title>
<h1>Upload image file for detection</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=image>
<input type=submit value=Upload>
</form>
"""
@app.route("/<image>")
def processed_image(image: str):
"""Return prediction and clean up temp file after sending.
:param image: predicted image file name
:return: the image itself
"""
@after_this_request
def remove_file(response):
try:
os.remove(image)
except Exception as error:
app.logger.error("Error removing downloaded file", error)
return response
return send_from_directory(app.config["UPLOAD_FOLDER"], image)
if __name__ == "__main__":
app.run(host="0.0.0.0")