formula_recognition.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. import numpy as np
  15. from ..components import CropByBoxes, ReadImage
  16. from ..results import FormulaResult, FormulaVisualResult
  17. from .base import BasePipeline
  18. from ...utils import logging
  19. class FormulaRecognitionPipeline(BasePipeline):
  20. """Formula Recognition Pipeline"""
  21. entities = "formula_recognition"
  22. def __init__(
  23. self,
  24. layout_model,
  25. formula_rec_model,
  26. layout_batch_size=1,
  27. formula_rec_batch_size=1,
  28. device=None,
  29. predictor_kwargs=None,
  30. ):
  31. super().__init__(device, predictor_kwargs)
  32. self._build_predictor(layout_model, formula_rec_model)
  33. self.set_predictor(
  34. layout_batch_size=layout_batch_size,
  35. formula_rec_batch_size=formula_rec_batch_size,
  36. )
  37. self.img_reader = ReadImage(format="BGR")
  38. def _build_predictor(self, layout_model, formula_rec_model):
  39. self.layout_predictor = self._create(model=layout_model)
  40. self.formula_predictor = self._create(model=formula_rec_model)
  41. self._crop_by_boxes = CropByBoxes()
  42. def set_predictor(
  43. self, layout_batch_size=None, formula_rec_batch_size=None, device=None
  44. ):
  45. if layout_batch_size:
  46. self.layout_predictor.set_predictor(batch_size=layout_batch_size)
  47. if formula_rec_batch_size:
  48. self.formula_predictor.set_predictor(batch_size=formula_rec_batch_size)
  49. if device:
  50. self.layout_predictor.set_predictor(device=device)
  51. self.formula_predictor.set_predictor(device=device)
  52. def predict(self, inputs, **kwargs):
  53. self.set_predictor(**kwargs)
  54. img_info_list = list(self.img_reader(inputs))[0]
  55. img_list = [img_info["img"] for img_info in img_info_list]
  56. for page_id, layout_pred in enumerate(self.layout_predictor(img_list)):
  57. single_img_res = {
  58. "input_path": "",
  59. "layout_result": {},
  60. "ocr_result": {},
  61. "table_result": [],
  62. }
  63. # update layout result
  64. single_img_res["input_path"] = layout_pred["input_path"]
  65. single_img_res["layout_result"] = layout_pred
  66. single_img_res["dt_polys"] = []
  67. single_img_res["rec_formula"] = []
  68. all_subs_of_formula_img = []
  69. layout_pred["boxes"] = sorted(
  70. layout_pred["boxes"], key=lambda x: self.sorted_formula_box(x)
  71. )
  72. if len(layout_pred["boxes"]) > 0:
  73. subs_of_img = list(self._crop_by_boxes(layout_pred))
  74. # get cropped images with label "formula"
  75. for sub in subs_of_img:
  76. if sub["label"].lower() == "formula":
  77. boxes = sub["box"]
  78. x1, y1, x2, y2 = list(boxes)
  79. poly = np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
  80. all_subs_of_formula_img.append(sub["img"])
  81. single_img_res["dt_polys"].append(poly)
  82. if len(all_subs_of_formula_img) > 0:
  83. for formula_res in self.formula_predictor(all_subs_of_formula_img):
  84. single_img_res["rec_formula"].append(
  85. str(formula_res["rec_text"])
  86. )
  87. single_img_res["formula_result"] = FormulaResult(single_img_res)
  88. single_img_res["page_id"] = page_id + 1
  89. yield FormulaVisualResult(single_img_res, page_id, inputs)
  90. def sorted_formula_box(self, x):
  91. coordinate = x["coordinate"]
  92. x1, y1, x2, y2 = list(coordinate)
  93. return (y1 + y2) / 2