predictor.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. )
  24. from ..base import BasePredictor
  25. from .processors import DocTrPostProcess
  26. from .result import DocTrResult
  27. class WarpPredictor(BasePredictor):
  28. """WarpPredictor that inherits from BasePredictor."""
  29. entities = MODELS
  30. def __init__(self, *args: List, **kwargs: Dict) -> None:
  31. """Initializes WarpPredictor.
  32. Args:
  33. *args: Arbitrary positional arguments passed to the superclass.
  34. **kwargs: Arbitrary keyword arguments passed to the superclass.
  35. """
  36. super().__init__(*args, **kwargs)
  37. self.preprocessors, self.infer, self.postprocessors = self._build()
  38. def _build_batch_sampler(self) -> ImageBatchSampler:
  39. """Builds and returns an ImageBatchSampler instance.
  40. Returns:
  41. ImageBatchSampler: An instance of ImageBatchSampler.
  42. """
  43. return ImageBatchSampler()
  44. def _get_result_class(self) -> type:
  45. """Returns the warpping result, DocTrResult.
  46. Returns:
  47. type: The DocTrResult.
  48. """
  49. return DocTrResult
  50. def _build(self) -> Tuple:
  51. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  52. Returns:
  53. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  54. """
  55. preprocessors = {"Read": ReadImage(format="BGR")}
  56. preprocessors["Normalize"] = Normalize(mean=0.0, std=1.0, scale=1.0 / 255)
  57. preprocessors["ToCHW"] = ToCHWImage()
  58. preprocessors["ToBatch"] = ToBatch()
  59. infer = self.create_static_infer()
  60. postprocessors = {"DocTrPostProcess": DocTrPostProcess()}
  61. return preprocessors, infer, postprocessors
  62. def process(self, batch_data: List[Union[str, np.ndarray]]) -> Dict[str, Any]:
  63. """
  64. Process a batch of data through the preprocessing, inference, and postprocessing.
  65. Args:
  66. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  67. Returns:
  68. 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'.
  69. """
  70. batch_raw_imgs = self.preprocessors["Read"](imgs=batch_data.instances)
  71. batch_imgs = self.preprocessors["Normalize"](imgs=batch_raw_imgs)
  72. batch_imgs = self.preprocessors["ToCHW"](imgs=batch_imgs)
  73. x = self.preprocessors["ToBatch"](imgs=batch_imgs)
  74. batch_preds = self.infer(x=x)
  75. batch_warp_preds = self.postprocessors["DocTrPostProcess"](batch_preds)
  76. return {
  77. "input_path": batch_data.input_paths,
  78. "page_index": batch_data.page_indexes,
  79. "input_img": batch_raw_imgs,
  80. "doctr_img": batch_warp_preds,
  81. }