text_recognition.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 ..results import TextRecResult
  19. from ..utils.process_hook import batchable_method
  20. from .base import BasicPredictor
  21. class TextRecPredictor(BasicPredictor):
  22. entities = MODELS
  23. _FUNC_MAP = {}
  24. register = FuncRegister(_FUNC_MAP)
  25. def _build_components(self):
  26. ops = {}
  27. for cfg in self.config["PreProcess"]["transform_ops"]:
  28. tf_key = list(cfg.keys())[0]
  29. assert tf_key in self._FUNC_MAP
  30. func = self._FUNC_MAP.get(tf_key)
  31. args = cfg.get(tf_key, {})
  32. op = func(self, **args) if args else func(self)
  33. if op:
  34. ops[tf_key] = op
  35. predictor = ImagePredictor(
  36. model_dir=self.model_dir,
  37. model_prefix=self.MODEL_FILE_PREFIX,
  38. option=self.pp_option,
  39. )
  40. ops["predictor"] = predictor
  41. key, op = self.build_postprocess(**self.config["PostProcess"])
  42. ops[key] = op
  43. return ops
  44. @register("DecodeImage")
  45. def build_readimg(self, channel_first, img_mode):
  46. assert channel_first == False
  47. return ReadImage(format=img_mode, batch_size=self.kwargs.get("batch_size", 1))
  48. @register("RecResizeImg")
  49. def build_resize(self, image_shape):
  50. return OCRReisizeNormImg(rec_image_shape=image_shape)
  51. def build_postprocess(self, **kwargs):
  52. if kwargs.get("name") == "CTCLabelDecode":
  53. return "CTCLabelDecode", CTCLabelDecode(
  54. character_list=kwargs.get("character_dict"),
  55. )
  56. else:
  57. raise Exception()
  58. @register("MultiLabelEncode")
  59. def foo(self, *args, **kwargs):
  60. return None
  61. @register("KeepKeys")
  62. def foo(self, *args, **kwargs):
  63. return None
  64. def _pack_res(self, single):
  65. keys = ["img_path", "rec_text", "rec_score"]
  66. return TextRecResult({key: single[key] for key in keys})