-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.py
187 lines (142 loc) · 5.36 KB
/
solution.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
""" Solution to the inteview question, lotlinx - Nov 8, 2018
By: Saman Rahbar """
import json
import logging
import os
import requests as r
from requests.auth import HTTPBasicAuth
import time
# path of the project
PROJECT_ROOT_PATH = os.environ.get('PROJECT_ROOT_PATH')
SLEEP_TIME = 60
# lotlinx URL
BASE_URL = 'https://api.lotlinx.com/photoai/v1'
DEALER_ID = 343 # arbitrary
VEHICLE_ID = 3743 # arbitrary
logger = logging.getLogger('LotLinx')
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('%s/app.log' % PROJECT_ROOT_PATH)
file_handler.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logging.Formatter.converter = time.gmtime
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Submitting the request
def submit_requests(auth, images):
"""
:param auth: authentication
:param images: JSON image file
:return: response object
"""
_path = 'images/optimize'
body = {
'dealerId': DEALER_ID,
'vehicles': [
{
'id': VEHICLE_ID,
'images': list()
}
]
}
for image in images:
body['vehicles'][0]['images'].append({
'imageId': image['id'],
'imageUrl': image['url']
})
url = '%s/%s' % (BASE_URL, _path)
logger.info("Submitting requests to '%s'." % url)
resp = r.post(url, json=body, auth=auth)
logger.info('HTTP response: %s' % resp.content)
return resp
#Function to check the status
def check_status(auth, token):
"""
:param auth: authentication
:param token: tokens
:return: response object
"""
_path = 'images/%s/status' % token
url = '%s/%s' % (BASE_URL, _path)
logger.info("Checking status at '%s'." % url)
resp = r.get(url, auth=auth)
logger.info('HTTP response: %s' % resp.content)
return resp
#Function to lead the response
def load_response(auth, token):
"""
:param auth: authentication
:param token: tokens
:return: response object
"""
_path = 'images/%s' % token
url = '%s/%s' % (BASE_URL, _path)
logger.info("Loading response from '%s'." % url)
resp = r.get(url, auth=auth)
logger.info('HTTP response: %s' % resp.content)
return resp
if __name__ == '__main__':
#logging
logger.info('Starting solution.\n')
filename = '%s/inputs/credentials.json' % PROJECT_ROOT_PATH
credentials = json.load(open(filename))
auth = HTTPBasicAuth(credentials['username'], credentials['password'])
logger.info("Credentials loaded from '%s'." % filename)
filename = '%s/inputs/images.json' % PROJECT_ROOT_PATH
images = json.load(open(filename))
logger.info("Images info loaded from '%s'.\n" % filename)
state = 'SUBMIT_REQUESTS'
status_code = None
request_status = None
token = None
optimized_images = None
logger.info('Ready to request.\n')
while True:
logger.info('state: %s' % state)
if state == 'SUBMIT_REQUESTS':
resp = submit_requests(auth, images)
status_code = resp.status_code
state = 'CHECK_STATUS'
logger.info("State changed to '%s'" % state)
if state == 'CHECK_STATUS':
if status_code != 200:
exception_message = '%s - %s' % (status_code, resp.json()['meta']['errorMsg'])
logger.error(exception_message)
raise Exception(exception_message)
else:
body = resp.json()['data'][0]
request_status = body['status']
token = body['token']
logger.info('request_status: %s' % request_status)
logger.info('token: %s' % token)
if request_status == 'complete':
resp = load_response(auth, token)
optimized_images = resp.json()['data'][0]['vehicles'][0]['images']
break
elif request_status == 'failed':
state = 'SUBMIT_REQUESTS'
logger.info("State changed to '%s'" % state)
elif request_status == 'queued':
logger.info('Request queued. Sleeping for a minute.')
time.sleep(SLEEP_TIME)
resp = check_status(auth, token)
if optimized_images:
if not os.path.exists('%s/outputs' % PROJECT_ROOT_PATH):
os.makedirs('%s/outputs' % PROJECT_ROOT_PATH)
filename = '%s/outputs/optimized_images.json' % PROJECT_ROOT_PATH
with open(filename, 'w') as file:
json.dump(optimized_images, file, indent=4)
logger.info("Description of optimized images saved in file '%s'." % filename)
for image in optimized_images:
image_id = image['imageId']
modified_url = image['modifiedUrl']
resp = r.get(modified_url, allow_redirects=True)
filename = '%s/outputs/optimized_image_%d.png' % (PROJECT_ROOT_PATH, image_id)
with open(filename, 'wb') as file:
file.write(resp.content)
logger.info("Image %d saved in file '%s'." % (image_id, filename))
logger.info('All images saved.\n')
logger.info('Finished.')