formula_recognition.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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
  16. from ..results import FormulaRecResult
  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. def _build_predictor(self, layout_model, formula_rec_model):
  38. self.layout_predictor = self._create(model=layout_model)
  39. self.formula_predictor = self._create(model=formula_rec_model)
  40. self._crop_by_boxes = CropByBoxes()
  41. def set_predictor(
  42. self, layout_batch_size=None, formula_rec_batch_size=None, device=None
  43. ):
  44. if layout_batch_size:
  45. self.layout_predictor.set_predictor(batch_size=layout_batch_size)
  46. if formula_rec_batch_size:
  47. self.formula_predictor.set_predictor(batch_size=formula_rec_batch_size)
  48. if device:
  49. self.layout_predictor.set_predictor(device=device)
  50. self.formula_predictor.set_predictor(device=device)
  51. def predict(self, x, **kwargs):
  52. self.set_predictor(**kwargs)
  53. for layout_pred in self.layout_predictor(x):
  54. single_img_res = {
  55. "input_path": "",
  56. "layout_result": {},
  57. "ocr_result": {},
  58. "table_result": [],
  59. }
  60. # update layout result
  61. single_img_res["input_path"] = layout_pred["input_path"]
  62. single_img_res["layout_result"] = layout_pred
  63. single_img_res["dt_polys"] = []
  64. single_img_res["rec_formula"] = []
  65. all_subs_of_formula_img = []
  66. layout_pred["boxes"] = sorted(
  67. layout_pred["boxes"], key=lambda x: self.sorted_formula_box(x)
  68. )
  69. if len(layout_pred["boxes"]) > 0:
  70. subs_of_img = list(self._crop_by_boxes(layout_pred))
  71. # get cropped images with label "formula"
  72. for sub in subs_of_img:
  73. if sub["label"].lower() == "formula":
  74. boxes = sub["box"]
  75. x1, y1, x2, y2 = list(boxes)
  76. poly = np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
  77. all_subs_of_formula_img.append(sub["img"])
  78. single_img_res["dt_polys"].append(poly)
  79. if len(all_subs_of_formula_img) > 0:
  80. for formula_res in self.formula_predictor(all_subs_of_formula_img):
  81. single_img_res["rec_formula"].append(
  82. str(formula_res["rec_text"])
  83. )
  84. yield FormulaRecResult(single_img_res)
  85. def sorted_formula_box(self, x):
  86. coordinate = x["coordinate"]
  87. x1, y1, x2, y2 = list(coordinate)
  88. return (y1 + y2) / 2