ocr.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. rec_batch_size,
  25. predictor_kwargs=None,
  26. ):
  27. super().__init__(predictor_kwargs)
  28. self._det_predict = self._create_predictor(det_model)
  29. self._rec_predict = self._create_predictor(rec_model, batch_size=rec_batch_size)
  30. is_curve = self._det_predict.model_name in [
  31. "PP-OCRv4_mobile_seal_det",
  32. "PP-OCRv4_server_seal_det",
  33. ]
  34. self._sort_boxes = SortBoxes()
  35. self._crop_by_polys = CropByPolys(det_box_type="poly" if is_curve else "quad")
  36. def predict(self, x):
  37. for det_res in self._det_predict(x):
  38. single_img_res = next(self._sort_boxes(det_res))
  39. single_img_res["rec_text"] = []
  40. single_img_res["rec_score"] = []
  41. if len(single_img_res["dt_polys"]) > 0:
  42. all_subs_of_img = list(self._crop_by_polys(single_img_res))
  43. for rec_res in self._rec_predict(all_subs_of_img):
  44. single_img_res["rec_text"].append(rec_res["rec_text"])
  45. single_img_res["rec_score"].append(rec_res["rec_score"])
  46. yield OCRResult(single_img_res)