ctc_postprocess.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import re
  2. import numpy as np
  3. class BaseRecLabelDecode(object):
  4. """Convert between text-label and text-index."""
  5. def __init__(self, character_dict_path=None, use_space_char=False):
  6. self.beg_str = 'sos'
  7. self.end_str = 'eos'
  8. self.reverse = False
  9. self.character_str = []
  10. if character_dict_path is None:
  11. self.character_str = '0123456789abcdefghijklmnopqrstuvwxyz'
  12. dict_character = list(self.character_str)
  13. else:
  14. with open(character_dict_path, 'rb') as fin:
  15. lines = fin.readlines()
  16. for line in lines:
  17. line = line.decode('utf-8').strip('\n').strip('\r\n')
  18. self.character_str.append(line)
  19. if use_space_char:
  20. self.character_str.append(' ')
  21. dict_character = list(self.character_str)
  22. if 'arabic' in character_dict_path:
  23. self.reverse = True
  24. dict_character = self.add_special_char(dict_character)
  25. self.dict = {}
  26. for i, char in enumerate(dict_character):
  27. self.dict[char] = i
  28. self.character = dict_character
  29. def pred_reverse(self, pred):
  30. pred_re = []
  31. c_current = ''
  32. for c in pred:
  33. if not bool(re.search('[a-zA-Z0-9 :*./%+-]', c)):
  34. if c_current != '':
  35. pred_re.append(c_current)
  36. pred_re.append(c)
  37. c_current = ''
  38. else:
  39. c_current += c
  40. if c_current != '':
  41. pred_re.append(c_current)
  42. return ''.join(pred_re[::-1])
  43. def add_special_char(self, dict_character):
  44. return dict_character
  45. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  46. """convert text-index into text-label."""
  47. result_list = []
  48. ignored_tokens = self.get_ignored_tokens()
  49. batch_size = len(text_index)
  50. for batch_idx in range(batch_size):
  51. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  52. if is_remove_duplicate:
  53. selection[1:] = text_index[batch_idx][1:] != text_index[
  54. batch_idx][:-1]
  55. for ignored_token in ignored_tokens:
  56. selection &= text_index[batch_idx] != ignored_token
  57. char_list = [
  58. self.character[text_id]
  59. for text_id in text_index[batch_idx][selection]
  60. ]
  61. if text_prob is not None:
  62. conf_list = text_prob[batch_idx][selection]
  63. else:
  64. conf_list = [1] * len(selection)
  65. if len(conf_list) == 0:
  66. conf_list = [0]
  67. text = ''.join(char_list)
  68. if self.reverse: # for arabic rec
  69. text = self.pred_reverse(text)
  70. result_list.append((text, np.mean(conf_list).tolist()))
  71. return result_list
  72. def get_ignored_tokens(self):
  73. return [0] # for ctc blank
  74. def get_character_num(self):
  75. return len(self.character)
  76. class CTCLabelDecode(BaseRecLabelDecode):
  77. """Convert between text-label and text-index."""
  78. def __init__(self,
  79. character_dict_path=None,
  80. use_space_char=False,
  81. **kwargs):
  82. super(CTCLabelDecode, self).__init__(character_dict_path,
  83. use_space_char)
  84. def __call__(self, preds, batch=None, **kwargs):
  85. # preds = preds['res']
  86. if kwargs.get('torch_tensor', True):
  87. preds = preds.detach().cpu().numpy()
  88. preds_idx = preds.argmax(axis=2)
  89. preds_prob = preds.max(axis=2)
  90. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  91. if batch is None:
  92. return text
  93. label = self.decode(batch[1])
  94. return text, label
  95. def add_special_char(self, dict_character):
  96. dict_character = ['blank'] + dict_character
  97. return dict_character