ocr.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 ..components import SortBoxes, CropByPolys
  15. from ..results import OCRResult
  16. from .base import BasePipeline
  17. class OCRPipeline(BasePipeline):
  18. """OCR Pipeline"""
  19. entities = "OCR"
  20. def __init__(
  21. self,
  22. det_model,
  23. rec_model,
  24. batch_size=1,
  25. predictor_kwargs=None,
  26. ):
  27. super().__init__(predictor_kwargs)
  28. self._build_predictor(det_model, rec_model)
  29. self.set_predictor(batch_size)
  30. def _build_predictor(self, det_model, rec_model):
  31. self.det_model = self._create_model(det_model)
  32. self.rec_model = self._create_model(rec_model)
  33. self.is_curve = self.det_model.model_name in [
  34. "PP-OCRv4_mobile_seal_det",
  35. "PP-OCRv4_server_seal_det",
  36. ]
  37. self._sort_boxes = SortBoxes()
  38. self._crop_by_polys = CropByPolys(
  39. det_box_type="poly" if self.is_curve else "quad"
  40. )
  41. def set_predictor(self, batch_size):
  42. self.rec_model.set_predictor(batch_size=batch_size)
  43. def predict(self, input, **kwargs):
  44. device = kwargs.get("device", "gpu")
  45. for det_res in self.det_model(
  46. input, batch_size=kwargs.get("det_batch_size", 1), device=device
  47. ):
  48. single_img_res = (
  49. det_res if self.is_curve else next(self._sort_boxes(det_res))
  50. )
  51. single_img_res["rec_text"] = []
  52. single_img_res["rec_score"] = []
  53. if len(single_img_res["dt_polys"]) > 0:
  54. all_subs_of_img = list(self._crop_by_polys(single_img_res))
  55. for rec_res in self.rec_model(
  56. all_subs_of_img,
  57. batch_size=kwargs.get("rec_batch_size", 1),
  58. device=device,
  59. ):
  60. single_img_res["rec_text"].append(rec_res["rec_text"])
  61. single_img_res["rec_score"].append(rec_res["rec_score"])
  62. yield OCRResult(single_img_res)