I define a funtion which use model to predict for text recognition in Google Colab but I have an UnboundLocalError for preds and preds_str variables. These two variables only appear in the function and did not assigned amywhere ot of the function.
def text_recoginition(model_path):
converter,recognition_model = text_recog_model_config(model_path)
demo_loader = demo_loader_for_recog()
recognition_model.eval()
with torch.no_grad():
for image_tensors, image_path_list in demo_loader:
batch_size = image_tensors.size(0)
image = image_tensors.to(device)
# For max length prediction
length_for_pred = torch.IntTensor([opt.batch_max_length] * batch_size).to(device)
text_for_pred = torch.LongTensor(batch_size, opt.batch_max_length + 1).fill_(0).to(device)
if 'CTC' in opt.Prediction:
preds = recognition_model(image, text_for_pred)
# Select max probabilty (greedy decoding) then decode index to character
preds_size = torch.IntTensor([preds.size(1)] * batch_size)
_, preds_index = preds.max(2)
# preds_index = preds_index.view(-1)
preds_str = converter.decode(preds_index, preds_size)
else:
preds = recognition_model(image, text_for_pred, is_train=False)
# select max probabilty (greedy decoding) then decode index to character
_, preds_index = preds.max(2)
preds_str = converter.decode(preds_index, length_for_pred)
return preds, preds_str
When I run this cell code. Error happen.
preds, preds_str = text_recoginition('/content/recognition_model_transform_ctc.pth')
This is the error specification.
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:477: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.
cpuset_checked))
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-136-d4b062b4c284> in <module>()
1 start = time.time()
----> 2 preds, preds_str = text_recoginition('/content/recognition_model_transform_ctc.pth')
3 print(time.time()-start)
<ipython-input-132-622b20c3d7ee> in text_recoginition(model_path)
22 _, preds_index = preds.max(2)
23 preds_str = converter.decode(preds_index, length_for_pred)
---> 24 return preds, preds_str
UnboundLocalError: local variable 'preds' referenced before assignment
I cannot figure out why. Please help me.