text_recognition.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.func_register import FuncRegister
  16. from ...modules.text_recognition.model_list import MODELS
  17. from ..components import *
  18. from .base import BasePredictor
  19. class TextRecPredictor(BasePredictor):
  20. entities = MODELS
  21. INPUT_KEYS = "x"
  22. OUTPUT_KEYS = "text_rec_res"
  23. DEAULT_INPUTS = {"x": "x"}
  24. DEAULT_OUTPUTS = {"text_rec_res": "text_rec_res"}
  25. _FUNC_MAP = {}
  26. register = FuncRegister(_FUNC_MAP)
  27. def _build_components(self):
  28. ops = {}
  29. for cfg in self.config["PreProcess"]["transform_ops"]:
  30. tf_key = list(cfg.keys())[0]
  31. assert tf_key in self._FUNC_MAP
  32. func = self._FUNC_MAP.get(tf_key)
  33. args = cfg.get(tf_key, {})
  34. op = func(self, **args) if args else func(self)
  35. if op:
  36. ops[tf_key] = op
  37. kernel_option = PaddlePredictorOption()
  38. # kernel_option.set_device(self.device)
  39. predictor = ImagePredictor(
  40. model_dir=self.model_dir,
  41. model_prefix=self.MODEL_FILE_PREFIX,
  42. option=kernel_option,
  43. )
  44. predictor.set_inputs({"imgs": "img"})
  45. ops["predictor"] = predictor
  46. key, op = self.build_postprocess(**self.config["PostProcess"])
  47. ops[key] = op
  48. return ops
  49. @register("DecodeImage")
  50. def build_readimg(self, channel_first, img_mode):
  51. assert channel_first == False
  52. return ReadImage(format=img_mode, batch_size=self.kwargs.get("batch_size", 1))
  53. @register("RecResizeImg")
  54. def build_resize(self, image_shape):
  55. return OCRReisizeNormImg(rec_image_shape=image_shape)
  56. def build_postprocess(self, **kwargs):
  57. if kwargs.get("name") == "CTCLabelDecode":
  58. return "CTCLabelDecode", CTCLabelDecode(
  59. character_list=kwargs.get("character_dict"),
  60. )
  61. else:
  62. raise Exception()
  63. @register("MultiLabelEncode")
  64. def foo(self, *args, **kwargs):
  65. return None
  66. @register("KeepKeys")
  67. def foo(self, *args, **kwargs):
  68. return None