predictor.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 typing import Any, Union, Dict, List, Tuple
  15. import numpy as np
  16. from ....modules.image_unwarping.model_list import MODELS
  17. from ...common.batch_sampler import ImageBatchSampler
  18. from ...common.reader import ReadImage
  19. from ..common import (
  20. Normalize,
  21. ToCHWImage,
  22. ToBatch,
  23. StaticInfer,
  24. )
  25. from ..base import BasicPredictor
  26. from .processors import DocTrPostProcess
  27. from .result import DocTrResult
  28. class WarpPredictor(BasicPredictor):
  29. """WarpPredictor that inherits from BasicPredictor."""
  30. entities = MODELS
  31. def __init__(self, *args: List, **kwargs: Dict) -> None:
  32. """Initializes WarpPredictor.
  33. Args:
  34. *args: Arbitrary positional arguments passed to the superclass.
  35. **kwargs: Arbitrary keyword arguments passed to the superclass.
  36. """
  37. super().__init__(*args, **kwargs)
  38. self.preprocessors, self.infer, self.postprocessors = self._build()
  39. def _build_batch_sampler(self) -> ImageBatchSampler:
  40. """Builds and returns an ImageBatchSampler instance.
  41. Returns:
  42. ImageBatchSampler: An instance of ImageBatchSampler.
  43. """
  44. return ImageBatchSampler()
  45. def _get_result_class(self) -> type:
  46. """Returns the warpping result, DocTrResult.
  47. Returns:
  48. type: The DocTrResult.
  49. """
  50. return DocTrResult
  51. def _build(self) -> Tuple:
  52. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  53. Returns:
  54. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  55. """
  56. preprocessors = {"Read": ReadImage(format="BGR")}
  57. preprocessors["Normalize"] = Normalize(mean=0.0, std=1.0, scale=1.0 / 255)
  58. preprocessors["ToCHW"] = ToCHWImage()
  59. preprocessors["ToBatch"] = ToBatch()
  60. infer = StaticInfer(
  61. model_dir=self.model_dir,
  62. model_prefix=self.MODEL_FILE_PREFIX,
  63. option=self.pp_option,
  64. )
  65. postprocessors = {"DocTrPostProcess": DocTrPostProcess()}
  66. return preprocessors, infer, postprocessors
  67. def process(self, batch_data: List[Union[str, np.ndarray]]) -> Dict[str, Any]:
  68. """
  69. Process a batch of data through the preprocessing, inference, and postprocessing.
  70. Args:
  71. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  72. Returns:
  73. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  74. """
  75. batch_raw_imgs = self.preprocessors["Read"](imgs=batch_data.instances)
  76. batch_imgs = self.preprocessors["Normalize"](imgs=batch_raw_imgs)
  77. batch_imgs = self.preprocessors["ToCHW"](imgs=batch_imgs)
  78. x = self.preprocessors["ToBatch"](imgs=batch_imgs)
  79. batch_preds = self.infer(x=x)
  80. batch_warp_preds = self.postprocessors["DocTrPostProcess"](batch_preds)
  81. return {
  82. "input_path": batch_data.input_paths,
  83. "page_index": batch_data.page_indexes,
  84. "input_img": batch_raw_imgs,
  85. "doctr_img": batch_warp_preds,
  86. }