vqa_token_ser_layoutlm_postprocess.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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, j]])
  54. decode_out_list[i].append(self.id2label_map[pred_idxs[i, j]])
  55. return decode_out_list, label_decode_out_list
  56. def _infer(self, preds, segment_offset_ids, ocr_infos):
  57. results = []
  58. for pred, segment_offset_id, ocr_info in zip(
  59. preds, segment_offset_ids, ocr_infos
  60. ):
  61. pred = np.argmax(pred, axis=1)
  62. pred = [self.id2label_map[idx] for idx in pred]
  63. for idx in range(len(segment_offset_id)):
  64. if idx == 0:
  65. start_id = 0
  66. else:
  67. start_id = segment_offset_id[idx - 1]
  68. end_id = segment_offset_id[idx]
  69. curr_pred = pred[start_id:end_id]
  70. curr_pred = [self.label2id_map_for_draw[p] for p in curr_pred]
  71. if len(curr_pred) <= 0:
  72. pred_id = 0
  73. else:
  74. counts = np.bincount(curr_pred)
  75. pred_id = np.argmax(counts)
  76. ocr_info[idx]["pred_id"] = int(pred_id)
  77. ocr_info[idx]["pred"] = self.id2label_map_for_show[int(pred_id)]
  78. results.append(ocr_info)
  79. return results
  80. class DistillationSerPostProcess(VQASerTokenLayoutLMPostProcess):
  81. """
  82. DistillationSerPostProcess
  83. """
  84. def __init__(self, class_path, model_name=["Student"], key=None, **kwargs):
  85. super().__init__(class_path, **kwargs)
  86. if not isinstance(model_name, list):
  87. model_name = [model_name]
  88. self.model_name = model_name
  89. self.key = key
  90. def __call__(self, preds, batch=None, *args, **kwargs):
  91. output = dict()
  92. for name in self.model_name:
  93. pred = preds[name]
  94. if self.key is not None:
  95. pred = pred[self.key]
  96. output[name] = super().__call__(pred, batch=batch, *args, **kwargs)
  97. return output