vqa_token_ser_layoutlm_postprocess.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. import paddle
  16. from ppocr.utils.utility import load_vqa_bio_label_maps
  17. class VQASerTokenLayoutLMPostProcess(object):
  18. """ Convert between text-label and text-index """
  19. def __init__(self, class_path, **kwargs):
  20. super(VQASerTokenLayoutLMPostProcess, self).__init__()
  21. label2id_map, self.id2label_map = load_vqa_bio_label_maps(class_path)
  22. self.label2id_map_for_draw = dict()
  23. for key in label2id_map:
  24. if key.startswith("I-"):
  25. self.label2id_map_for_draw[key] = label2id_map["B" + key[1:]]
  26. else:
  27. self.label2id_map_for_draw[key] = label2id_map[key]
  28. self.id2label_map_for_show = dict()
  29. for key in self.label2id_map_for_draw:
  30. val = self.label2id_map_for_draw[key]
  31. if key == "O":
  32. self.id2label_map_for_show[val] = key
  33. if key.startswith("B-") or key.startswith("I-"):
  34. self.id2label_map_for_show[val] = key[2:]
  35. else:
  36. self.id2label_map_for_show[val] = key
  37. def __call__(self, preds, batch=None, *args, **kwargs):
  38. if isinstance(preds, tuple):
  39. preds = preds[0]
  40. if isinstance(preds, paddle.Tensor):
  41. preds = preds.numpy()
  42. if batch is not None:
  43. return self._metric(preds, batch[5])
  44. else:
  45. return self._infer(preds, **kwargs)
  46. def _metric(self, preds, label):
  47. pred_idxs = preds.argmax(axis=2)
  48. decode_out_list = [[] for _ in range(pred_idxs.shape[0])]
  49. label_decode_out_list = [[] for _ in range(pred_idxs.shape[0])]
  50. for i in range(pred_idxs.shape[0]):
  51. for j in range(pred_idxs.shape[1]):
  52. if label[i, j] != -100:
  53. label_decode_out_list[i].append(self.id2label_map[label[i,
  54. j]])
  55. decode_out_list[i].append(self.id2label_map[pred_idxs[i,
  56. j]])
  57. return decode_out_list, label_decode_out_list
  58. def _infer(self, preds, segment_offset_ids, ocr_infos):
  59. results = []
  60. for pred, segment_offset_id, ocr_info in zip(preds, segment_offset_ids,
  61. ocr_infos):
  62. pred = np.argmax(pred, axis=1)
  63. pred = [self.id2label_map[idx] for idx in pred]
  64. for idx in range(len(segment_offset_id)):
  65. if idx == 0:
  66. start_id = 0
  67. else:
  68. start_id = segment_offset_id[idx - 1]
  69. end_id = segment_offset_id[idx]
  70. curr_pred = pred[start_id:end_id]
  71. curr_pred = [self.label2id_map_for_draw[p] for p in curr_pred]
  72. if len(curr_pred) <= 0:
  73. pred_id = 0
  74. else:
  75. counts = np.bincount(curr_pred)
  76. pred_id = np.argmax(counts)
  77. ocr_info[idx]["pred_id"] = int(pred_id)
  78. ocr_info[idx]["pred"] = self.id2label_map_for_show[int(pred_id)]
  79. results.append(ocr_info)
  80. return results
  81. class DistillationSerPostProcess(VQASerTokenLayoutLMPostProcess):
  82. """
  83. DistillationSerPostProcess
  84. """
  85. def __init__(self, class_path, model_name=["Student"], key=None, **kwargs):
  86. super().__init__(class_path, **kwargs)
  87. if not isinstance(model_name, list):
  88. model_name = [model_name]
  89. self.model_name = model_name
  90. self.key = key
  91. def __call__(self, preds, batch=None, *args, **kwargs):
  92. output = dict()
  93. for name in self.model_name:
  94. pred = preds[name]
  95. if self.key is not None:
  96. pred = pred[self.key]
  97. output[name] = super().__call__(pred, batch=batch, *args, **kwargs)
  98. return output