Skip to content

Commit fa98d85

Browse files
authored
Create inference-sql-argparse.py
1 parent 50224af commit fa98d85

File tree

1 file changed

+237
-0
lines changed

1 file changed

+237
-0
lines changed

inference-sql-argparse.py

+237
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
import time
2+
import argparse
3+
import mysql.connector
4+
import json
5+
6+
import requests
7+
import io
8+
import os
9+
import numpy as np
10+
import glob
11+
import json
12+
13+
from six import BytesIO
14+
from PIL import Image
15+
16+
import tensorflow as tf
17+
from object_detection.utils import ops as utils_ops
18+
from object_detection.utils import label_map_util
19+
from object_detection.utils import visualization_utils as vis_util
20+
import ftplib
21+
22+
def load_image_into_numpy_array(path):
23+
"""Load an image from file into a numpy array.
24+
25+
Puts image into numpy array to feed into tensorflow graph.
26+
Note that by convention we put it into a numpy array with shape
27+
(height, width, channels), where channels=3 for RGB.
28+
29+
Args:
30+
path: a file path (this can be local or on colossus)
31+
32+
Returns:
33+
uint8 numpy array with shape (img_height, img_width, 3)
34+
"""
35+
img_data = tf.io.gfile.GFile(path, 'rb').read()
36+
image = Image.open(BytesIO(img_data))
37+
(im_width, im_height) = image.size
38+
return np.array(image.getdata()).reshape(
39+
(im_height, im_width, 3)).astype(np.uint8)
40+
41+
def run_inference_for_single_image(model, image):
42+
image = np.asarray(image)
43+
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
44+
input_tensor = tf.convert_to_tensor(image)
45+
# The model expects a batch of images, so add an axis with `tf.newaxis`.
46+
input_tensor = input_tensor[tf.newaxis, ...]
47+
48+
# Run inference
49+
model_fn = model.signatures['serving_default']
50+
output_dict = model_fn(input_tensor)
51+
52+
# All outputs are batches tensors.
53+
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
54+
# We're only interested in the first num_detections.
55+
num_detections = int(output_dict.pop('num_detections'))
56+
output_dict = {key: value[0, :num_detections].numpy()
57+
for key, value in output_dict.items()}
58+
output_dict['num_detections'] = num_detections
59+
60+
# detection_classes should be ints.
61+
output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
62+
63+
# Handle models with masks:
64+
if 'detection_masks' in output_dict:
65+
# Reframe the the bbox mask to the image size.
66+
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
67+
output_dict['detection_masks'], output_dict['detection_boxes'],
68+
image.shape[0], image.shape[1])
69+
detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
70+
tf.uint8)
71+
output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()
72+
73+
return output_dict
74+
75+
labelmap_path = 'labelmap.pbtxt'
76+
category_index = label_map_util.create_category_index_from_labelmap(labelmap_path, use_display_name=True)
77+
print("Load labelmap")
78+
tf.keras.backend.clear_session()
79+
model = tf.saved_model.load('inference_graph/saved_model')
80+
print("Load inference graph")
81+
82+
global_time = time.time()
83+
parser = argparse.ArgumentParser(description='Paso de parámetros')
84+
parser.add_argument("-MUID", dest="p_MUID", help="MUID to fetch")
85+
params = parser.parse_args()
86+
87+
c = open("config.json")
88+
config = json.load(c)
89+
#MUID = 'asoter_1_hashtagTop_9_cec6fcb9'
90+
MUID = params.p_MUID
91+
92+
dir_exist = os.path.exists("./exported_images/" + MUID)
93+
94+
def directory_exists(dir,ftp):
95+
filelist = []
96+
ftp.retrlines('LIST',filelist.append)
97+
for f in filelist:
98+
if f.split()[-1] == dir and f.upper().startswith('D'):
99+
return True
100+
return False
101+
102+
def DataUpload(local_dir, target_dir):
103+
ftp_server = ftplib.FTP(config["FTP"]["hostname"],config["FTP"]["username"],config["FTP"]["password"])
104+
ftp_server.encoding = "utf-8"
105+
#ftp_server.login()
106+
ftp_server.cwd('/media/exported_images')
107+
if directory_exists(target_dir, ftp_server) is False: # (or negate, whatever you prefer for readability)
108+
print(target_dir)
109+
ftp_server.mkd(target_dir)
110+
ftp_server.cwd(target_dir)
111+
# https://stackoverflow.com/questions/67520579/uploading-a-files-in-a-folder-to-ftp-using-python-ftplib
112+
print("Uploading exported batch")
113+
toFTP = os.listdir(local_dir)
114+
for filename in toFTP:
115+
if filename not in ftp_server.nlst():
116+
print("Uploading: ")
117+
with open(os.path.join(local_dir, filename), 'rb') as file: # Here I open the file using it's full path
118+
ftp_server.storbinary(f'STOR {filename}', file) # Here I store the file in the FTP using only it's name as I intended
119+
print(filename)
120+
else:
121+
print("File already exist")
122+
ftp_server.quit()
123+
124+
if not dir_exist:
125+
#os.makedirs(user_dir, 0o777)
126+
os.makedirs("./exported_images/" + MUID, 0o777)
127+
print("The dir was created")
128+
else:
129+
print("The dir already exist")
130+
131+
try:
132+
cnx = mysql.connector.connect(user=config["SQL"]["username"],
133+
password=config["SQL"]["password"],
134+
host=config["SQL"]["hostname"],
135+
database=config["SQL"]["database"],
136+
)
137+
except mysql.connector.Error as err:
138+
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
139+
print("Something is wrong with your user name or password")
140+
elif err.errno == errorcode.ER_BAD_DB_ERROR:
141+
print("Database does not exist")
142+
else:
143+
print(err)
144+
else:
145+
print("Looking for caption in MUID:", MUID)
146+
cursor = cnx.cursor()
147+
cursor.execute("SELECT * FROM data_media WHERE MUID IN ('%s') " % (MUID))
148+
posts = cursor.fetchall()
149+
print("MUID found :", len(posts))
150+
asset_url = ''
151+
img_format = ''
152+
153+
for post in posts:
154+
inference_dict = []
155+
print("Image URL:")
156+
print(post)
157+
if post[6] == 1:
158+
asset_url_jpg = "http://data.abundis.com.mx/media/" + post[14] + "/" + post[1] + "_" + post[3] + ".jpg"
159+
asset_url_webp = "http://data.abundis.com.mx/media/" + post[14] + "/" + post[1] + "_" + post[3] + ".webp"
160+
r_webp = requests.head(asset_url_webp)
161+
r_jpg = requests.head(asset_url_jpg)
162+
if r_webp.headers['Content-Type'] == 'image/webp':
163+
asset_url = asset_url_webp
164+
img_format= "webp"
165+
elif r_jpg.headers['Content-Type'] == 'image/jpeg':
166+
asset_url = asset_url_jpg
167+
img_format = "jpg"
168+
169+
img_data = requests.get(asset_url).content
170+
if img_format == 'webp':
171+
with open('./downloaded_images/'+post[4]+'.webp', 'wb') as handler:
172+
handler.write(img_data)
173+
filename = post[4]+'_exported.webp'
174+
image_np = load_image_into_numpy_array('./downloaded_images/'+post[4]+'.webp')
175+
output_dict = run_inference_for_single_image(model, image_np)
176+
vis_util.visualize_boxes_and_labels_on_image_array(
177+
image_np,
178+
output_dict['detection_boxes'],
179+
output_dict['detection_classes'],
180+
output_dict['detection_scores'],
181+
category_index,
182+
instance_masks=output_dict.get('detection_masks_reframed', None),
183+
use_normalized_coordinates=True,
184+
line_thickness=8)
185+
im = Image.fromarray(image_np)
186+
im.save('./exported_images/' +MUID+ '/' + filename)
187+
188+
print("File inferences", filename)
189+
print("with at least 0.5 of score")
190+
for d_class, d_score in zip(output_dict['detection_classes'][:5], output_dict['detection_scores'][:5]):
191+
if d_score > 0.5:
192+
d_class_name = category_index[d_class]['name']
193+
print('{0} with score {1}'.format(d_class_name, d_score))
194+
inference_dict.append( ( d_class_name, float(d_score) ) )
195+
196+
elif img_format == 'jpg':
197+
with open('./downloaded_images/'+post[4]+'.jpg', 'wb') as handler:
198+
handler.write(img_data)
199+
filename = post[4] + '_exported.jpg'
200+
image_np = load_image_into_numpy_array('./downloaded_images/' + post[4] + '.jpg')
201+
output_dict = run_inference_for_single_image(model, image_np)
202+
vis_util.visualize_boxes_and_labels_on_image_array(
203+
image_np,
204+
output_dict['detection_boxes'],
205+
output_dict['detection_classes'],
206+
output_dict['detection_scores'],
207+
category_index,
208+
instance_masks=output_dict.get('detection_masks_reframed', None),
209+
use_normalized_coordinates=True,
210+
line_thickness=8)
211+
im = Image.fromarray(image_np)
212+
im.save('./exported_images/' +MUID+ '/' + filename)
213+
214+
print("File inferences", filename)
215+
print("with at least 0.5 of score")
216+
c = 1
217+
for d_class, d_score in zip(output_dict['detection_classes'][:5], output_dict['detection_scores'][:5]):
218+
if d_score > 0.5:
219+
220+
d_class_name = category_index[d_class]['name']
221+
print('{0} with score {1}'.format(d_class_name, d_score))
222+
inference_dict.append( ( d_class_name, float(d_score) ) )
223+
224+
print("Inference to JSON and then SQL")
225+
inference_json = json.dumps(inference_dict)
226+
print(inference_json)
227+
cnx.reconnect()
228+
innercursor = cnx.cursor()
229+
sql_inference = "UPDATE data_media SET inference_custom = %s WHERE id = %s"
230+
val = (inference_json, post[0])
231+
innercursor.execute(sql_inference, val)
232+
cnx.commit()
233+
234+
print(innercursor.rowcount, "registros afectado/s")
235+
236+
237+
DataUpload('./exported_images/' +MUID+ '/', MUID)

0 commit comments

Comments
 (0)