Skip to content

Commit 82b8bdc

Browse files
committed
fix: resolve ruff lint warnings
1 parent 12396bd commit 82b8bdc

2 files changed

Lines changed: 38 additions & 42 deletions

File tree

src/sailsprep/tracking_pose_model_testing/efficientpose.py

Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
import sys
33
import time
4-
from getopt import GetoptError as error
54
from getopt import error, getopt
65
from os.path import join, normpath
76

@@ -35,15 +34,15 @@ def get_model(framework, model_variant):
3534
from tensorflow.keras.backend import set_learning_phase
3635
from tensorflow.keras.models import load_model
3736
set_learning_phase(0)
38-
model = load_model(join('models', 'keras', 'EfficientPose{0}.h5'.format(model_variant.upper())), custom_objects={'BilinearWeights': helpers.keras_BilinearWeights, 'Swish': helpers.Swish(helpers.eswish), 'eswish': helpers.eswish, 'swish1': helpers.swish1})
37+
model = load_model(join('models', 'keras', 'EfficientPose{}.h5'.format(model_variant.upper())), custom_objects={'BilinearWeights': helpers.keras_BilinearWeights, 'Swish': helpers.Swish(helpers.eswish), 'eswish': helpers.eswish, 'swish1': helpers.swish1})
3938

4039
# TensorFlow
4140
elif framework in ['tensorflow', 'tf']:
4241
from tensorflow import import_graph_def
4342
from tensorflow.compat.v1 import GraphDef
4443
from tensorflow.compat.v1.keras.backend import get_session
4544
from tensorflow.python.platform.gfile import FastGFile
46-
f = FastGFile(join('models', 'tensorflow', 'EfficientPose{0}.pb'.format(model_variant.upper())), 'rb')
45+
f = FastGFile(join('models', 'tensorflow', 'EfficientPose{}.pb'.format(model_variant.upper())), 'rb')
4746
graph_def = GraphDef()
4847
graph_def.ParseFromString(f.read())
4948
f.close()
@@ -54,7 +53,7 @@ def get_model(framework, model_variant):
5453
# TensorFlow Lite
5554
elif framework in ['tensorflowlite', 'tflite']:
5655
from tensorflow import lite
57-
model = lite.Interpreter(model_path=join('models', 'tflite', 'EfficientPose{0}.tflite'.format(model_variant.upper())))
56+
model = lite.Interpreter(model_path=join('models', 'tflite', 'EfficientPose{}.tflite'.format(model_variant.upper())))
5857
model.allocate_tensors()
5958

6059
# PyTorch
@@ -63,13 +62,13 @@ def get_model(framework, model_variant):
6362

6463
from torch import backends, load, quantization
6564
try:
66-
MainModel = load_source('MainModel', join('models', 'pytorch', 'EfficientPose{0}.py'.format(model_variant.upper())))
65+
MainModel = load_source('MainModel', join('models', 'pytorch', 'EfficientPose{}.py'.format(model_variant.upper())))
6766
except:
6867
print('\n##########################################################################################################')
69-
print('Desired model "EfficientPose{0}Lite" not available in PyTorch. Please select among "RT", "I", "II", "III" or "IV".'.format(model_variant.split('lite')[0].upper()))
68+
print('Desired model "EfficientPose{}Lite" not available in PyTorch. Please select among "RT", "I", "II", "III" or "IV".'.format(model_variant.split('lite')[0].upper()))
7069
print('##########################################################################################################\n')
7170
return False, False
72-
model = load(join('models', 'pytorch', 'EfficientPose{0}'.format(model_variant.upper())))
71+
model = load(join('models', 'pytorch', 'EfficientPose{}'.format(model_variant.upper())))
7372
model.eval()
7473
qconfig = quantization.get_default_qconfig('qnnpack')
7574
backends.quantized.engine = 'qnnpack'
@@ -183,7 +182,7 @@ def analyze_camera(model, framework, resolution, lite):
183182
cv2.destroyAllWindows()
184183

185184
# Print total operation time
186-
print('Camera operated in {0} seconds'.format(time.time() - start_time))
185+
print('Camera operated in {} seconds'.format(time.time() - start_time))
187186
print('##########################################################################################################\n')
188187

189188
return coordinates
@@ -226,7 +225,7 @@ def analyze_image(file_path, model, framework, resolution, lite):
226225

227226
# Print processing time
228227
print('\n##########################################################################################################')
229-
print('Image processed in {0} seconds'.format('%.3f' % (time.time() - start_time)))
228+
print('Image processed in {} seconds'.format('%.3f' % (time.time() - start_time)))
230229
print('##########################################################################################################\n')
231230

232231
return coordinates
@@ -266,7 +265,7 @@ def analyze_video(file_path, model, framework, resolution, lite):
266265
frame_height, frame_width = next(vreader(file_path)).shape[:2]
267266
except Exception as e:
268267
print('error',e,'error')
269-
print('Video "{0}" could not be loaded. Please verify that the file is working.'.format(file_path))
268+
print('Video "{}" could not be loaded. Please verify that the file is working.'.format(file_path))
270269
print('##########################################################################################################\n')
271270
return False
272271

@@ -279,10 +278,10 @@ def analyze_video(file_path, model, framework, resolution, lite):
279278

280279
# Fetch batch of frames
281280
batch = [next(videogen, None) for _ in range(batch_size)]
282-
if not type(batch[0]) == np.ndarray:
281+
if type(batch[0]) is not np.ndarray:
283282
break
284-
elif not type(batch[-1]) == np.ndarray:
285-
batch = [frame if type(frame) == np.ndarray else np.zeros((frame_height, frame_width, 3)) for frame in batch]
283+
elif type(batch[-1]) is not np.ndarray:
284+
batch = [frame if type(frame) is np.ndarray else np.zeros((frame_height, frame_width, 3)) for frame in batch]
286285

287286
# Preprocess batch
288287
batch = helpers.preprocess(batch, resolution, lite)
@@ -296,7 +295,7 @@ def analyze_video(file_path, model, framework, resolution, lite):
296295

297296
# Print partial processing time
298297
if batch_num % part_size == 0:
299-
print('{0} of {1}: Part processed in {2} seconds | Video processed for {3} seconds'.format(int(batch_num / part_size), int(np.ceil(num_batches / part_size)), '%.3f' % (time.time() - part_start_time), '%.3f' % (time.time() - start_time)))
298+
print('{} of {}: Part processed in {} seconds | Video processed for {} seconds'.format(int(batch_num / part_size), int(np.ceil(num_batches / part_size)), '%.3f' % (time.time() - part_start_time), '%.3f' % (time.time() - start_time)))
300299
part_start_time = time.time()
301300
batch_num += 1
302301

@@ -446,22 +445,19 @@ def save(video, file_path, coordinates):
446445
# Initialize CSV
447446
import csv
448447
csv_path = normpath(file_path.split('.')[0] + '_coordinates.csv') if file_path is not None else normpath('camera_coordinates.csv')
449-
csv_file = open(csv_path, 'w')
450448
headers = ['frame'] if video else []
451449
[headers.extend([body_part + '_x', body_part + '_y']) for body_part, _, _ in coordinates[0]]
452-
writer = csv.DictWriter(csv_file, fieldnames=headers)
453-
writer.writeheader()
454-
455-
# Write coordinates to CSV
456-
for i, image_coordinates in enumerate(coordinates):
457-
row = {'frame': i + 1} if video else {}
458-
for body_part, body_part_x, body_part_y in image_coordinates:
459-
row[body_part + '_x'] = body_part_x
460-
row[body_part + '_y'] = body_part_y
461-
writer.writerow(row)
462-
463-
csv_file.flush()
464-
csv_file.close()
450+
with open(csv_path, 'w') as csv_file:
451+
writer = csv.DictWriter(csv_file, fieldnames=headers)
452+
writer.writeheader()
453+
454+
# Write coordinates to CSV
455+
for i, image_coordinates in enumerate(coordinates):
456+
row = {'frame': i + 1} if video else {}
457+
for body_part, body_part_x, body_part_y in image_coordinates:
458+
row[body_part + '_x'] = body_part_x
459+
row[body_part + '_y'] = body_part_y
460+
writer.writerow(row)
465461

466462
def perform_tracking(video, file_path, model_name, framework_name, visualize, store):
467463
"""
@@ -490,19 +486,19 @@ def perform_tracking(video, file_path, model_name, framework_name, visualize, st
490486
model_variant = model_name.lower()
491487
if framework not in ['keras', 'k', 'tensorflow', 'tf', 'tensorflowlite', 'tflite', 'pytorch', 'torch']:
492488
print('\n##########################################################################################################')
493-
print('Desired framework "{0}" not available. Please select among "tflite", "tensorflow", "keras" or "pytorch".'.format(framework_name))
489+
print('Desired framework "{}" not available. Please select among "tflite", "tensorflow", "keras" or "pytorch".'.format(framework_name))
494490
print('##########################################################################################################\n')
495491
return False
496492
elif model_variant not in ['efficientposert', 'rt', 'efficientposei', 'i', 'efficientposeii', 'ii', 'efficientposeiii', 'iii', 'efficientposeiv', 'iv', 'efficientposert_lite', 'rt_lite', 'efficientposei_lite', 'i_lite', 'efficientposeii_lite', 'ii_lite']:
497493
print('\n##########################################################################################################')
498-
print('Desired model "{0}" not available. Please select among "RT", "I", "II", "III", "IV", "RT_Lite", "I_Lite" or "II_Lite".'.format(model_name))
494+
print('Desired model "{}" not available. Please select among "RT", "I", "II", "III", "IV", "RT_Lite", "I_Lite" or "II_Lite".'.format(model_name))
499495
print('##########################################################################################################\n')
500496
return False
501497

502498
# LOAD MODEL
503499
else:
504500
model_variant = model_variant[13:] if len(model_variant) > 7 else model_variant
505-
lite = True if model_variant.endswith('_lite') else False
501+
lite = bool(model_variant.endswith('_lite'))
506502
model, resolution = get_model(framework, model_variant)
507503
if not model:
508504
return True
@@ -540,7 +536,7 @@ def main(file_path, model_name, framework_name, visualize, store):
540536
# LIVE ANALYSIS FROM CAMERA
541537
if file_path is None:
542538
print('\n##########################################################################################################')
543-
print('Click "Q" to end camera-based tracking.'.format(file_path))
539+
print('Click "Q" to end camera-based tracking.')
544540
print('##########################################################################################################\n')
545541
perform_tracking(video=True, file_path=None, model_name=model_name, framework_name=framework_name, visualize=False, store=store)
546542

@@ -554,7 +550,7 @@ def main(file_path, model_name, framework_name, visualize, store):
554550

555551
else:
556552
print('\n##########################################################################################################')
557-
print('Ensure supplied file "{0}" is a video or image'.format(file_path))
553+
print('Ensure supplied file "{}" is a video or image'.format(file_path))
558554
print('##########################################################################################################\n')
559555

560556

src/sailsprep/tracking_pose_model_testing/movenet.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ def draw_prediction_on_image(
214214
elif "movenet_thunder_int8" in model_name:
215215
input_size = 256
216216
else:
217-
raise ValueError("Unsupported model name: %s" % model_name)
217+
raise ValueError("Unsupported model name: {}".format(model_name))
218218

219219
# Initialize the TFLite interpreter
220220
interpreter = tf.lite.Interpreter(model_path="model.tflite")
@@ -251,7 +251,7 @@ def movenet(input_image):
251251
module = hub.load("https://tfhub.dev/google/movenet/singlepose/thunder/4")
252252
input_size = 256
253253
else:
254-
raise ValueError("Unsupported model name: %s" % model_name)
254+
raise ValueError("Unsupported model name: {}".format(model_name))
255255

256256
def movenet(input_image):
257257
"""Runs detection on an input image.
@@ -347,8 +347,8 @@ def determine_torso_and_body_range(
347347
for joint in KEYPOINT_DICT.keys():
348348
if keypoints[0, 0, KEYPOINT_DICT[joint], 2] < MIN_CROP_KEYPOINT_SCORE:
349349
continue
350-
dist_y = abs(center_y - target_keypoints[joint][0]);
351-
dist_x = abs(center_x - target_keypoints[joint][1]);
350+
dist_y = abs(center_y - target_keypoints[joint][0])
351+
dist_x = abs(center_x - target_keypoints[joint][1])
352352
if dist_y > max_body_yrange:
353353
max_body_yrange = dist_y
354354

@@ -378,9 +378,9 @@ def determine_crop_region(
378378

379379
if torso_visible(keypoints):
380380
center_y = (target_keypoints['left_hip'][0] +
381-
target_keypoints['right_hip'][0]) / 2;
381+
target_keypoints['right_hip'][0]) / 2
382382
center_x = (target_keypoints['left_hip'][1] +
383-
target_keypoints['right_hip'][1]) / 2;
383+
target_keypoints['right_hip'][1]) / 2
384384

385385
(max_torso_yrange, max_torso_xrange,
386386
max_body_yrange, max_body_xrange) = determine_torso_and_body_range(
@@ -393,14 +393,14 @@ def determine_crop_region(
393393
tmp = np.array(
394394
[center_x, image_width - center_x, center_y, image_height - center_y])
395395
crop_length_half = np.amin(
396-
[crop_length_half, np.amax(tmp)]);
396+
[crop_length_half, np.amax(tmp)])
397397

398-
crop_corner = [center_y - crop_length_half, center_x - crop_length_half];
398+
crop_corner = [center_y - crop_length_half, center_x - crop_length_half]
399399

400400
if crop_length_half > max(image_width, image_height) / 2:
401401
return init_crop_region(image_height, image_width)
402402
else:
403-
crop_length = crop_length_half * 2;
403+
crop_length = crop_length_half * 2
404404
return {
405405
'y_min': crop_corner[0] / image_height,
406406
'x_min': crop_corner[1] / image_width,

0 commit comments

Comments
 (0)