ocr.py 2.5 KB

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