predictor.py 7.2 KB

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