-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline_nadav.py
375 lines (332 loc) · 17.3 KB
/
pipeline_nadav.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
__author__ = 'Nadav Paz'
import logging
import datetime
import time
import pickle
import numpy as np
import pymongo
import bson
import cv2
from rq import Queue
from rq.job import Job
import tldextract
import boto3
import page_results
from .paperdoll import paperdoll_parse_enqueue
from . import find_similar_mongo
from . import background_removal
from . import Utils
from . import constants
from . import whitelist
from .constants import db
from .constants import redis_conn
folder = '/home/ubuntu/paperdoll/masks/'
QC_URL = 'https://extremeli.trendi.guru/api/fake_qc/index'
callback_url = "https://extremeli.trendi.guru/api/nadav/index"
images = db.images
iip = db.iip
q1 = Queue('find_similar', connection=redis_conn)
q2 = Queue('find_top_n', connection=redis_conn)
# sys.stdout = sys.stderr
TTL = constants.general_ttl
def get_person_by_id(person_id, collection=iip):
image = collection.find_one({'people.person_id': person_id})
if image:
for person in image['people']:
if person['person_id'] == person_id:
return image, person
else:
return None, None
def get_item_by_id(item_id, collection=iip):
image = collection.find_one({'people.items.item_id': item_id})
for person in image['people']:
try:
for item in person['items']:
if item['item_id'] == item_id:
person["person_idx"] = image['people'].index(person)
item["item_idx"] = person['items'].index(item)
return image, person, item
except:
logging.warning("No items to this person, continuing..")
return None, None, None
def bb_from_mask(mask):
r, c = mask.nonzero()
x = min(c)
y = min(r)
w = max(c) - x + 1
h = max(r) - y + 1
return x, y, w, h
def search_existing_images(page_url):
ex_list = []
query = images.find({'page_urls': page_url}, {'relevant': 1, 'image_urls': 1})
for doc in query:
ex_list.append(doc)
return ex_list
def clear_collection(collection):
print "before: " + str(collection.count()) + " docs"
for doc in collection.find():
if doc['relevant'] is True and len(doc['people'][0]['items']) == 0:
collection.delete_one({'_id': doc['_id']})
print "after: " + str(collection.count()) + " docs"
def job_result_from_id(job_id, job_class=Job, conn=None):
conn = conn or constants.redis_conn
job = job_class.fetch(job_id, connection=conn)
return job.result
def blacklisted_term_in_url(page_url):
lowercase_url = page_url.lower()
for term in constants.blacklisted_terms:
if term in lowercase_url:
return True
return False
# ----------------------------------------------MAIN-FUNCTIONS----------------------------------------------------------
def start_process(page_url, image_url, lang=None):
# db.monitoring.update_one({'queue': 'start_process'}, {'$inc': {'count': 1}})
if not lang:
products_collection = 'products'
coll_name = 'images'
images_collection = db[coll_name]
else:
products_collection = 'products_' + lang
coll_name = 'images_' + lang
images_collection = db[coll_name]
page_domain = tldextract.extract(page_url).registered_domain
if page_domain not in whitelist.all_white_lists:
logging.debug("Domain not in whitelist: {0}. Page: {1}".format(page_domain, page_url))
return
# IF URL IS BLACKLISTED - put in blacklisted_urls
# {"page_url":"hoetownXXX.com","image_urls":["hoetownXXX.com/yomama1.jpg","yomama2.jpg"]}
# if blacklisted_term_in_url(page_url):
# if db.blacklisted_urls.find_one({"page_url": page_url}):
# db.blacklisted_urls.update_one({"page_url": page_url},
# {"$push": {"image_urls": image_url}})
# else:
# db.blacklisted_urls.insert_one({"page_url": page_url, "image_urls": [image_url]})
# return
# IF IMAGE IN IRRELEVANT_IMAGES
images_obj_url = db.irrelevant_images.find_one({"image_urls": image_url})
if images_obj_url:
return
# IF URL HAS NO IMAGE IN IT
image = Utils.get_cv2_img_array(image_url)
if image is None:
return
# IF IMAGE EXISTS IN IMAGES BY HASH (WITH ANOTHER URL)
image_hash = page_results.get_hash_of_image_from_url(image_url)
images_obj_hash = images_collection.find_one_and_update({"image_hash": image_hash},
{'$push': {'image_urls': image_url}})
if images_obj_hash:
return
# IF IMAGE IN PROCESS BY URL/HASH
iip_obj = iip.find_one({"image_urls": image_url}) or iip.find_one({"image_hash": image_hash})
if iip_obj:
return
# NEW_IMAGE !!
print "Start process image shape: " + str(image.shape)
relevance = background_removal.image_is_relevant(image, use_caffe=False, image_url=image_url)
image_dict = {'image_urls': [image_url], 'relevant': relevance.is_relevant, 'views': 1, 'people': [],
'image_hash': image_hash, 'page_urls': [page_url], 'saved_date': datetime.datetime.now()}
if relevance.is_relevant:
# There are faces
idx = 0
for face in relevance.faces:
x, y, w, h = face
person_bb = [int(round(max(0, x - 1.5 * w))), int(y), int(round(min(image.shape[1], x + 2.5 * w))),
min(image.shape[0], 8 * h)]
person = {'face': face.tolist(), 'person_id': str(bson.ObjectId()), 'person_idx': idx, 'items': [],
'person_bb': person_bb}
image_copy = person_isolation(image, face)
image_dict['people'].append(person)
paper_job = paperdoll_parse_enqueue.paperdoll_enqueue(image_copy, person['person_id'])
# TODO: what happens if paper_job is failed (pop person..)
q1.enqueue_call(func=from_paperdoll_to_similar_results, args=(person['person_id'], paper_job.id, 100,
products_collection, coll_name),
depends_on=paper_job, ttl=TTL, result_ttl=TTL, timeout=TTL)
try:
iip.insert_one(image_dict)
except pymongo.errors.InvalidDocument as inv_err:
print image_dict
with open("/tmp/bad_dict.pickle", "wb") as f:
f.write(pickle.dumps(image_dict))
raise inv_err
return
else: # if not relevant
print 'image is not relevant, but stored anyway..'
db.irrelevant_images.insert_one(image_dict)
return
def from_paperdoll_to_similar_results(person_id, paper_job_id, num_of_matches=100, products_collection='products',
images_collection='images'):
start = time.time()
products_collection = products_collection
images_collection = db[images_collection]
paper_job_results = job_result_from_id(paper_job_id)
if paper_job_results[3] != person_id:
print
raise ValueError("paper job refers to another image!!! oy vey !!! filename: {0} & person_id: {1}".format(
paper_job_results[3], person_id))
mask, labels = paper_job_results[:2]
image_obj, person = get_person_by_id(person_id, iip)
if not image_obj or not person:
raise SystemError("couldn't find image or person by person_id")
final_mask = after_pd_conclusions(mask, labels, person['face'])
image = Utils.get_cv2_img_array(image_obj['image_urls'][0])
if image is None:
iip.delete_one({'_id': image_obj['_id']})
raise SystemError("image came back empty from Utils.get_cv2..")
idx = 0
items = []
jobs = {}
for num in np.unique(final_mask):
# convert numbers to labels
category = list(labels.keys())[list(labels.values()).index(num)]
if category in constants.paperdoll_shopstyle_women.keys():
item_mask = 255 * np.array(final_mask == num, dtype=np.uint8)
shopstyle_cat_local_name = constants.paperdoll_shopstyle_women_jp_categories[category]['name']
item_dict = {"category": category, 'item_id': str(bson.ObjectId()), 'item_idx': idx,
'category_name': shopstyle_cat_local_name}
# svg_name = find_similar_mongo.mask2svg(
# item_mask,
# str(image_obj['_id']) + '_' + person['person_id'] + '_' + item_dict['category'],
# constants.svg_folder)
# item_dict["svg_url"] = constants.svg_url_prefix + svg_name
items.append(item_dict)
# db.monitoring.update_one({'queue': 'find_top_n'}, {'$inc': {'count': 1}})
jobs[idx] = q2.enqueue_call(func=find_similar_mongo.find_top_n_results, args=(image, item_mask,
num_of_matches,
item_dict['category'],
products_collection),
ttl=TTL, result_ttl=TTL, timeout=TTL)
idx += 1
# print "everyone was sent to find_top_n after {0} seconds.".format(time.time() - start)
done = all([job.is_finished for job in jobs.values()])
while not done:
time.sleep(0.2)
done = all([job.is_finished or job.is_failed for job in jobs.values()])
# print "all find_top_n is done after {0} seconds".format(time.time() - start)
for idx, job in jobs.iteritems():
cur_item = next((item for item in items if item['item_idx'] == idx), None)
if job.is_failed:
items[:] = [item for item in items if item['item_idx'] != cur_item['item_idx']]
else:
cur_item['fp'], cur_item['similar_results'] = job.result
new_image_obj = iip.find_one_and_update({'people.person_id': person_id}, {'$set': {'people.$.items': items}},
return_document=pymongo.ReturnDocument.AFTER)
if all((len(similar_results) for person in new_image_obj['people'] for similar_results in person['items'])):
# print "inserted to db.images after {0} seconds".format(time.time() - start)
a = images_collection.insert_one(new_image_obj)
iip.delete_one({'_id': image_obj['_id']})
logging.warning("# of images inserted to db.images: {0}".format(a.acknowledged * 1))
def get_results_now(page_url, image_url, collection='products_jp'):
a = time.time()
# IF IMAGE EXISTS IN DEMO BY URL
images_obj_url = db.demo.find_one({"image_urls": image_url})
if images_obj_url:
return page_results.merge_items(images_obj_url)
# IF IMAGE EXISTS IN IMAGES BY URL
images_obj_url = images.find_one({"image_urls": image_url})
if images_obj_url:
return page_results.merge_items(images_obj_url)
# IF URL HAS NO IMAGE IN IT
image = Utils.get_cv2_img_array(image_url)
if image is None:
return
# IF IMAGE EXISTS IN IMAGES BY HASH (WITH ANOTHER URL)
image_hash = page_results.get_hash_of_image_from_url(image_url)
images_obj_hash = images.find_one_and_update({"image_hash": image_hash}, {'$push': {'image_urls': image_url}})
if images_obj_hash:
return page_results.merge_items(images_obj_hash)
# IF IMAGE IN PROCESS BY URL/HASH
iip_obj = iip.find_one({"image_urls": image_url}) or iip.find_one({"image_hash": image_hash})
if iip_obj:
return
# NEW_IMAGE !!
relevance = background_removal.image_is_relevant(image, True, image_url)
image_dict = {'image_urls': [image_url], 'relevant': relevance.is_relevant,
'image_hash': image_hash, 'page_urls': [page_url], 'people': []}
if relevance.is_relevant:
idx = 0
if len(relevance.faces):
if not isinstance(relevance.faces, list):
relevant_faces = relevance.faces.tolist()
else:
relevant_faces = relevance.faces
for face in relevant_faces:
image_copy = person_isolation(image, face)
person = {'face': face, 'person_id': str(bson.ObjectId()), 'person_idx': idx,
'items': []}
image_dict['people'].append(person)
print "untill pd: {0}".format(time.time() - a)
mask, labels, pose = paperdoll_parse_enqueue.paperdoll_enqueue(image_copy, async=False).result[:3]
start = time.time()
final_mask = after_pd_conclusions(mask, labels, person['face'])
item_idx = 0
jobs = {}
for num in np.unique(final_mask):
# convert numbers to labels
category = list(labels.keys())[list(labels.values()).index(num)]
if category in constants.paperdoll_shopstyle_women.keys():
item_mask = 255 * np.array(final_mask == num, dtype=np.uint8)
shopstyle_cat = constants.paperdoll_shopstyle_women[category]
item_dict = {"category": shopstyle_cat, 'item_id': str(bson.ObjectId()), 'item_idx': item_idx,
'saved_date': datetime.datetime.now()}
svg_name = find_similar_mongo.mask2svg(
item_mask,
str(image_dict['image_hash']) + '_' + person['person_id'] + '_' + item_dict['category'],
constants.svg_folder)
item_dict["svg_url"] = constants.svg_url_prefix + svg_name
jobs[item_idx] = q2.enqueue_call(func=find_similar_mongo.find_top_n_results, args=(image,
item_mask,
100,
item_dict[
'category'],
collection),
ttl=TTL,
result_ttl=TTL, timeout=TTL)
person['items'].append(item_dict)
item_idx += 1
done = all([job.is_finished for job in jobs.values()])
b = time.time()
print "done is {0}".format(done)
while not done:
time.sleep(0.2)
done = all([job.is_finished for job in jobs.values()])
print "done is {0} after {1} seconds with {2} items..".format(done, time.time() - b,
len(person['items']))
for idx, job in jobs.iteritems():
cur_item = next((item for item in person['items'] if item['item_idx'] == idx), None)
cur_item['fp'], cur_item['similar_results'] = job.result
idx += 1
image_dict['people'].append(person)
else:
print "no faces, went caffe.."
person = {'face': [], 'person_id': str(bson.ObjectId()), 'person_idx': 0, 'items': []}
image_dict['people'].append(person)
mask, labels, pose = paperdoll_parse_enqueue.paperdoll_enqueue(image, async=False).result[:3]
final_mask = after_pd_conclusions(mask, labels)
item_idx = 0
jobs = {}
for num in np.unique(final_mask):
# convert numbers to labels
category = list(labels.keys())[list(labels.values()).index(num)]
if category in constants.paperdoll_shopstyle_women.keys():
item_mask = 255 * np.array(final_mask == num, dtype=np.uint8)
shopstyle_cat = constants.paperdoll_shopstyle_women[category]
item_dict = {"category": shopstyle_cat, 'item_id': str(bson.ObjectId()), 'item_idx': item_idx,
'saved_date': datetime.datetime.now()}
svg_name = find_similar_mongo.mask2svg(
item_mask,
str(image_dict['image_hash']) + '_' + person['person_id'] + '_' + item_dict['category'],
constants.svg_folder)
item_dict["svg_url"] = constants.svg_url_prefix + svg_name
jobs[idx] = q2.enqueue_call(func=find_similar_mongo.find_top_n_results, args=(image,
item_mask, 100,
item_dict['category'],
collection), ttl=TTL,
result_ttl=TTL, timeout=TTL)
person['items'].append(item_dict)
item_idx += 1
image_dict['people'].append(person)
db.demo.insert_one(image_dict)
print "all took {0} seconds".format(time.time() - start)
return page_results.merge_items(image_dict)
else: # if not relevant
return