predictor.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Copyright (c) 2024 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. from ....modules.formula_recognition.model_list import MODELS
  16. from ....utils import logging
  17. from ....utils.func_register import FuncRegister
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ..base import BasePredictor
  21. from .processors import (
  22. LatexImageFormat,
  23. LaTeXOCRDecode,
  24. LatexTestTransform,
  25. MinMaxResize,
  26. NormalizeImage,
  27. ToBatch,
  28. UniMERNetDecode,
  29. UniMERNetImageFormat,
  30. UniMERNetImgDecode,
  31. UniMERNetTestTransform,
  32. )
  33. from .result import FormulaRecResult
  34. class FormulaRecPredictor(BasePredictor):
  35. """FormulaRecPredictor that inherits from BasePredictor."""
  36. entities = MODELS
  37. _FUNC_MAP = {}
  38. register = FuncRegister(_FUNC_MAP)
  39. def __init__(self, *args, **kwargs):
  40. """Initializes FormulaRecPredictor.
  41. Args:
  42. *args: Arbitrary positional arguments passed to the superclass.
  43. **kwargs: Arbitrary keyword arguments passed to the superclass.
  44. """
  45. super().__init__(*args, **kwargs)
  46. self.model_names_only_supports_batchsize_of_one = {
  47. "LaTeX_OCR_rec",
  48. }
  49. if self.model_name in self.model_names_only_supports_batchsize_of_one:
  50. logging.warning(
  51. f"Formula Recognition Models: \"{', '.join(list(self.model_names_only_supports_batchsize_of_one))}\" only supports prediction with a batch_size of one, "
  52. "if you set the predictor with a batch_size larger than one, no error will occur, however, it will actually inference with a batch_size of one, "
  53. f"which will lead to a slower inference speed. You are now using {self.config['Global']['model_name']}."
  54. )
  55. self.pre_tfs, self.infer, self.post_op = self._build()
  56. def _build_batch_sampler(self):
  57. return ImageBatchSampler()
  58. def _get_result_class(self):
  59. return FormulaRecResult
  60. def _build(self):
  61. pre_tfs = {"Read": ReadImage(format="RGB")}
  62. for cfg in self.config["PreProcess"]["transform_ops"]:
  63. tf_key = list(cfg.keys())[0]
  64. assert tf_key in self._FUNC_MAP
  65. func = self._FUNC_MAP[tf_key]
  66. args = cfg.get(tf_key, {})
  67. name, op = func(self, **args) if args else func(self)
  68. if op:
  69. pre_tfs[name] = op
  70. pre_tfs["ToBatch"] = ToBatch()
  71. infer = self.create_static_infer()
  72. post_op = self.build_postprocess(**self.config["PostProcess"])
  73. return pre_tfs, infer, post_op
  74. def process(self, batch_data):
  75. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  76. if self.model_name in ("LaTeX_OCR_rec"):
  77. batch_imgs = self.pre_tfs["MinMaxResize"](imgs=batch_raw_imgs)
  78. batch_imgs = self.pre_tfs["LatexTestTransform"](imgs=batch_imgs)
  79. batch_imgs = self.pre_tfs["NormalizeImage"](imgs=batch_imgs)
  80. batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
  81. elif self.model_name in ("UniMERNet"):
  82. batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=batch_raw_imgs)
  83. batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
  84. batch_imgs = self.pre_tfs["UniMERNetImageFormat"](imgs=batch_imgs)
  85. elif self.model_name in ("PP-FormulaNet-S", "PP-FormulaNet-L"):
  86. batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=batch_raw_imgs)
  87. batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
  88. batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
  89. if self.model_name in self.model_names_only_supports_batchsize_of_one:
  90. batch_preds = []
  91. max_length = 0
  92. for batch_img in batch_imgs:
  93. batch_pred_ = self.infer([batch_img])[0].reshape([-1])
  94. max_length = max(max_length, batch_pred_.shape[0])
  95. batch_preds.append(batch_pred_)
  96. for i in range(len(batch_preds)):
  97. batch_preds[i] = np.pad(
  98. batch_preds[i],
  99. (0, max_length - batch_preds[i].shape[0]),
  100. mode="constant",
  101. constant_values=0,
  102. )
  103. else:
  104. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  105. batch_preds = self.infer(x=x)
  106. batch_preds = [p.reshape([-1]) for p in batch_preds[0]]
  107. rec_formula = self.post_op(batch_preds)
  108. return {
  109. "input_path": batch_data.input_paths,
  110. "page_index": batch_data.page_indexes,
  111. "input_img": batch_raw_imgs,
  112. "rec_formula": rec_formula,
  113. }
  114. @register("DecodeImage")
  115. def build_readimg(self, channel_first, img_mode):
  116. assert channel_first == False
  117. return "Read", ReadImage(format=img_mode)
  118. @register("MinMaxResize")
  119. def build_min_max_resize(self, min_dimensions, max_dimensions):
  120. return "MinMaxResize", MinMaxResize(
  121. min_dimensions=min_dimensions, max_dimensions=max_dimensions
  122. )
  123. @register("LatexTestTransform")
  124. def build_latex_test_transform(
  125. self,
  126. ):
  127. return "LatexTestTransform", LatexTestTransform()
  128. @register("NormalizeImage")
  129. def build_normalize(self, mean, std, order="chw"):
  130. return "NormalizeImage", NormalizeImage(mean=mean, std=std, order=order)
  131. @register("LatexImageFormat")
  132. def build_latexocr_imageformat(self):
  133. return "LatexImageFormat", LatexImageFormat()
  134. @register("UniMERNetImgDecode")
  135. def build_unimernet_decode(self, input_size):
  136. return "UniMERNetImgDecode", UniMERNetImgDecode(input_size)
  137. def build_postprocess(self, **kwargs):
  138. if kwargs.get("name") == "LaTeXOCRDecode":
  139. return LaTeXOCRDecode(
  140. character_list=kwargs.get("character_dict"),
  141. )
  142. elif kwargs.get("name") == "UniMERNetDecode":
  143. return UniMERNetDecode(
  144. character_list=kwargs.get("character_dict"),
  145. )
  146. else:
  147. raise Exception()
  148. @register("UniMERNetTestTransform")
  149. def build_unimernet_imageformat(self):
  150. return "UniMERNetTestTransform", UniMERNetTestTransform()
  151. @register("UniMERNetImageFormat")
  152. def build_unimernet_imageformat(self):
  153. return "UniMERNetImageFormat", UniMERNetImageFormat()
  154. @register("UniMERNetLabelEncode")
  155. def foo(self, *args, **kwargs):
  156. return None, None
  157. @register("KeepKeys")
  158. def foo(self, *args, **kwargs):
  159. return None, None