I noticed a logical issue in the _generate_and_score_completions function where the image resizing code relies on exception handling for the normal control flow.
Currently, the img.resize call uses variables (new_w, new_h) that are only defined inside the if w < 28 or h < 28 block. However, the resize call itself is placed outside this block.
...
try:
w, h = img.size
if w < 28 or h < 28:
# new_w and new_h are defined here
if w < h:
new_w = 28
new_h = int(h * (28/w))
else:
new_h = 28
new_w = int(w * (28/h))
# PROBLEM: This executes even if the condition above is False.
# It raises UnboundLocalError for normal images, which is expensive.
img = img.resize((new_w, new_h), PIL.Image.Resampling.LANCZOS)
except:
pass
images.append(img)