predictor.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. from ....utils import logging
  15. from ....utils.func_register import FuncRegister
  16. from ....modules.formula_recognition.model_list import MODELS
  17. from ...common.batch_sampler import ImageBatchSampler
  18. from ...common.reader import ReadImage
  19. from ..common import (
  20. StaticInfer,
  21. )
  22. from ..base import BasicPredictor
  23. from .processors import (
  24. MinMaxResize,
  25. LatexTestTransform,
  26. LatexImageFormat,
  27. LaTeXOCRDecode,
  28. NormalizeImage,
  29. ToBatch,
  30. UniMERNetImgDecode,
  31. UniMERNetDecode,
  32. UniMERNetTestTransform,
  33. UniMERNetImageFormat,
  34. )
  35. from .result import FormulaRecResult
  36. class FormulaRecPredictor(BasicPredictor):
  37. entities = MODELS
  38. _FUNC_MAP = {}
  39. register = FuncRegister(_FUNC_MAP)
  40. def __init__(self, *args, **kwargs):
  41. super().__init__(*args, **kwargs)
  42. self.pre_tfs, self.infer, self.post_op = self._build()
  43. def _build_batch_sampler(self):
  44. return ImageBatchSampler()
  45. def _get_result_class(self):
  46. return FormulaRecResult
  47. def _build(self):
  48. pre_tfs = {"Read": ReadImage(format="RGB")}
  49. for cfg in self.config["PreProcess"]["transform_ops"]:
  50. tf_key = list(cfg.keys())[0]
  51. assert tf_key in self._FUNC_MAP
  52. func = self._FUNC_MAP[tf_key]
  53. args = cfg.get(tf_key, {})
  54. name, op = func(self, **args) if args else func(self)
  55. if op:
  56. pre_tfs[name] = op
  57. pre_tfs["ToBatch"] = ToBatch()
  58. if self.model_name in ("LaTeX_OCR_rec") and self.pp_option.device in ("cpu"):
  59. import cpuinfo
  60. if "GenuineIntel" in cpuinfo.get_cpu_info().get("vendor_id_raw", ""):
  61. self.pp_option.run_mode = "mkldnn"
  62. logging.warning(
  63. "Now, the `LaTeX_OCR_rec` model only support `mkldnn` mode when running on Intel CPU devices. So using `mkldnn` instead."
  64. )
  65. infer = StaticInfer(
  66. model_dir=self.model_dir,
  67. model_prefix=self.MODEL_FILE_PREFIX,
  68. option=self.pp_option,
  69. )
  70. post_op = self.build_postprocess(**self.config["PostProcess"])
  71. return pre_tfs, infer, post_op
  72. def process(self, batch_data):
  73. batch_raw_imgs = self.pre_tfs["Read"](imgs=batch_data.instances)
  74. if self.model_name in ("LaTeX_OCR_rec"):
  75. batch_imgs = self.pre_tfs["MinMaxResize"](imgs=batch_raw_imgs)
  76. batch_imgs = self.pre_tfs["LatexTestTransform"](imgs=batch_imgs)
  77. batch_imgs = self.pre_tfs["NormalizeImage"](imgs=batch_imgs)
  78. batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
  79. elif self.model_name in ("UniMERNet"):
  80. batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=batch_raw_imgs)
  81. batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
  82. batch_imgs = self.pre_tfs["UniMERNetImageFormat"](imgs=batch_imgs)
  83. elif self.model_name in ("PP-FormulaNet-S", "PP-FormulaNet-L"):
  84. batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=batch_raw_imgs)
  85. batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
  86. batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
  87. x = self.pre_tfs["ToBatch"](imgs=batch_imgs)
  88. batch_preds = self.infer(x=x)
  89. batch_preds = [p.reshape([-1]) for p in batch_preds[0]]
  90. rec_formula = self.post_op(batch_preds)
  91. return {
  92. "input_path": batch_data.input_paths,
  93. "page_index": batch_data.page_indexes,
  94. "input_img": batch_raw_imgs,
  95. "rec_formula": rec_formula,
  96. }
  97. @register("DecodeImage")
  98. def build_readimg(self, channel_first, img_mode):
  99. assert channel_first == False
  100. return "Read", ReadImage(format=img_mode)
  101. @register("MinMaxResize")
  102. def build_min_max_resize(self, min_dimensions, max_dimensions):
  103. return "MinMaxResize", MinMaxResize(
  104. min_dimensions=min_dimensions, max_dimensions=max_dimensions
  105. )
  106. @register("LatexTestTransform")
  107. def build_latex_test_transform(
  108. self,
  109. ):
  110. return "LatexTestTransform", LatexTestTransform()
  111. @register("NormalizeImage")
  112. def build_normalize(self, mean, std, order="chw"):
  113. return "NormalizeImage", NormalizeImage(mean=mean, std=std, order=order)
  114. @register("LatexImageFormat")
  115. def build_latexocr_imageformat(self):
  116. return "LatexImageFormat", LatexImageFormat()
  117. @register("UniMERNetImgDecode")
  118. def build_unimernet_decode(self, input_size):
  119. return "UniMERNetImgDecode", UniMERNetImgDecode(input_size)
  120. def build_postprocess(self, **kwargs):
  121. if kwargs.get("name") == "LaTeXOCRDecode":
  122. return LaTeXOCRDecode(
  123. character_list=kwargs.get("character_dict"),
  124. )
  125. elif kwargs.get("name") == "UniMERNetDecode":
  126. return UniMERNetDecode(
  127. character_list=kwargs.get("character_dict"),
  128. )
  129. else:
  130. raise Exception()
  131. @register("UniMERNetTestTransform")
  132. def build_unimernet_imageformat(self):
  133. return "UniMERNetTestTransform", UniMERNetTestTransform()
  134. @register("UniMERNetImageFormat")
  135. def build_unimernet_imageformat(self):
  136. return "UniMERNetImageFormat", UniMERNetImageFormat()
  137. @register("UniMERNetLabelEncode")
  138. def foo(self, *args, **kwargs):
  139. return None, None
  140. @register("KeepKeys")
  141. def foo(self, *args, **kwargs):
  142. return None, None