-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
227 lines (205 loc) · 7.28 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import os
import re
from flask import Flask, request, Response, jsonify, safe_join
from flask_cors import CORS
from bson import json_util
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
from app.utils.helpers import getConfig, getFilePath, nl2br, isAuthorizedRequest
from app.ImageSearcher import ImageSearcher
from app.ColorPicker import ColorPicker
from app.ImageProcessor import ImageProcessor
from app.Poet import Poet
from app.Tweeter import Tweeter
from app.Model import Model
def create_app():
sentryDsn = os.getenv("SENTRY_DSN", None)
if sentryDsn is not None:
sentry_sdk.init(dsn=sentryDsn, integrations=[FlaskIntegration()])
app = Flask(__name__)
CORS(app)
config = getConfig()
imageSearcher = ImageSearcher()
colorPicker = ColorPicker()
poet = Poet()
tweeter = Tweeter()
model = Model()
@app.route("/health")
def health():
return Response("OK", status=200)
@app.route("/")
@app.route("/similar-images")
def similarImages():
imageUrl = request.args.get("image_url")
if imageUrl is None:
return Response("image_url parameter is required", status=400)
else:
images = imageSearcher.searchWithUrl(imageUrl)
return jsonify(images)
@app.route("/current-color")
def currentColor():
color = colorPicker.getCurrentColorRgb()
html = """
<body
style="
background-color: rgb({}, {}, {});">
</body>
""".format(
*color
)
return Response(html, status=200)
def pickImage():
from app.ImagePicker.ImagePicker import ImagePicker
source = request.args.get("source")
def imageIsUnique(url):
return model.getCount({"url": url}) == 0
image = ImagePicker().pickImage(source, unique=imageIsUnique)
return image
@app.route("/pick-image")
def pickImageView():
image = pickImage()
response = app.response_class(
response=json_util.dumps(image), status=200, mimetype="application/json"
)
return response
@app.route("/generate-poem")
def generatePoem():
return poet.makePoem()
@app.route("/all")
def all():
response = app.response_class(
response=json_util.dumps(model.getAll()),
status=200,
mimetype="application/json",
)
return response
@app.route("/list")
def list():
response = app.response_class(
response=json_util.dumps(
model.getPage(
request.args.get("page"),
request.args.get("size"),
request.args.get("fetchNext"),
)
),
status=200,
mimetype="application/json",
)
return response
@app.route("/last")
def last():
response = app.response_class(
response=json_util.dumps(model.getLast()),
status=200,
mimetype="application/json",
)
return response
@app.route("/one/<slug>")
def one(slug):
response = app.response_class(
response=json_util.dumps(model.getOneBySlug(slug)),
status=200,
mimetype="application/json",
)
return response
@app.route("/process-image")
def processImage():
if isAuthorizedRequest(request) == False:
return Response("Unauthorized", status=401)
image = {"source": None, "url": request.args.get("image_url")}
if image["url"] is None:
image = pickImage()
imageProcessor = ImageProcessor()
currentColor = colorPicker.getCurrentColorRgb()
visuallySimilarToOriginal = imageSearcher.searchWithUrl(image["url"])
originalImageFile, grabCutFile, countoursFile = imageProcessor.colorizeImage(
imageUrl=image["url"], currentColor=currentColor
)
originalFileFullPath = getFilePath(
originalImageFile, path=config["Files"]["OriginalImagePath"]
)
grabCutFilePath = getFilePath(
grabCutFile, path=config["Files"]["ColorizedImagePath"], withRoot=False
)
grabCutFileFullPath = getFilePath(
grabCutFile, path=config["Files"]["ColorizedImagePath"]
)
countoursFilePath = getFilePath(
countoursFile, path=config["Files"]["ColorizedImagePath"], withRoot=False
)
countoursFileFullPath = getFilePath(
countoursFile, path=config["Files"]["ColorizedImagePath"]
)
pixelSortedFile = imageProcessor.pixelSortImage(originalFileFullPath)
pixelSortedFilePath = getFilePath(
pixelSortedFile,
path=config["Files"]["PixelSortedImagePath"],
withRoot=False,
)
pixelSortedFileFullPath = getFilePath(
pixelSortedFile, path=config["Files"]["PixelSortedImagePath"]
)
visuallySimilarToProcessed = imageSearcher.searchWithLocalFile(
countoursFileFullPath
)
visuallySimilarImages = visuallySimilarToProcessed + visuallySimilarToOriginal
visuallySimilarImagesLinks = [image["link"] for image in visuallySimilarImages]
finalImage = imageProcessor.makeSlicedImage(
[countoursFileFullPath],
canvasImgPath=grabCutFileFullPath,
sliceName="contours",
minProp=0.15,
maxProp=0.25,
)
finalImage = imageProcessor.makeSlicedImage(
[pixelSortedFileFullPath],
canvas=finalImage,
sliceName="pixelsort",
minProp=0.15,
maxProp=0.25,
)
finalImage = imageProcessor.makeSlicedImage(
visuallySimilarImagesLinks,
canvas=finalImage,
sliceName="visually similar large",
minProp=0.10,
maxProp=0.12,
)
visuallySimilarImagesLinks.pop(0)
finalImage = imageProcessor.makeSlicedImage(
visuallySimilarImagesLinks,
canvas=finalImage,
sliceName="visually similar normal",
returnCanvas=False,
filenamePrefix="Prospect-{}-".format(image["source"]),
maxSlicesCount=3,
)
finalImageFilePath = getFilePath(
finalImage, path=config["Files"]["FinalImagePath"], withRoot=False
)
finalImageFilePathFullPath = getFilePath(
finalImage, path=config["Files"]["FinalImagePath"]
) + "/full.jpg"
poem = generatePoem()
# Persist to DB if request is authenticated
model.insert(
{
"originalUrl": image["url"],
"finalImagePath": finalImageFilePath + "/",
"gisement": image["sourceId"],
"description": image["description"],
"poem": poem,
"color": currentColor,
"slug": "{}-{}".format(
image["sourceId"], re.sub(r"[^0-9]", "", finalImageFilePath)
),
"active": True,
}
)
tweeter.tweet(
poem, finalImageFilePathFullPath, additionalText=image["twitterText"]
)
return Response("OK", status=200)
return app
app = create_app()