ocr.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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=1,
  25. device="gpu",
  26. predictor_kwargs=None,
  27. ):
  28. super().__init__(predictor_kwargs)
  29. self._det_predict = self._create_model(det_model, device=device)
  30. self._rec_predict = self._create_model(
  31. rec_model, batch_size=rec_batch_size, device=device
  32. )
  33. self.is_curve = self._det_predict.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 predict(self, x):
  42. for det_res in self._det_predict(x):
  43. single_img_res = (
  44. det_res if self.is_curve else next(self._sort_boxes(det_res))
  45. )
  46. single_img_res["rec_text"] = []
  47. single_img_res["rec_score"] = []
  48. if len(single_img_res["dt_polys"]) > 0:
  49. all_subs_of_img = list(self._crop_by_polys(single_img_res))
  50. for rec_res in self._rec_predict(all_subs_of_img):
  51. single_img_res["rec_text"].append(rec_res["rec_text"])
  52. single_img_res["rec_score"].append(rec_res["rec_score"])
  53. yield OCRResult(single_img_res)