|
|
@@ -17,10 +17,7 @@ from typing import Any, Dict, Optional
|
|
|
import numpy as np
|
|
|
import cv2
|
|
|
from ..base import BasePipeline
|
|
|
-from ..components import CropByBoxes
|
|
|
-
|
|
|
-# from ..layout_parsing.utils import convert_points_to_boxes
|
|
|
-from ..components import convert_points_to_boxes
|
|
|
+from ..components import CropByBoxes, convert_points_to_boxes
|
|
|
|
|
|
from .result import FormulaRecognitionResult
|
|
|
from ...models_new.formula_recognition.result import (
|
|
|
@@ -50,7 +47,7 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
use_hpip: bool = False,
|
|
|
hpi_params: Optional[Dict[str, Any]] = None,
|
|
|
) -> None:
|
|
|
- """Initializes the layout parsing pipeline.
|
|
|
+ """Initializes the formula recognition pipeline.
|
|
|
|
|
|
Args:
|
|
|
config (Dict): Configuration dictionary containing various settings.
|
|
|
@@ -64,24 +61,31 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
|
|
|
)
|
|
|
|
|
|
- self.use_doc_preprocessor = False
|
|
|
- if "use_doc_preprocessor" in config:
|
|
|
- self.use_doc_preprocessor = config["use_doc_preprocessor"]
|
|
|
-
|
|
|
+ self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
|
|
|
if self.use_doc_preprocessor:
|
|
|
- doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
|
|
|
+ doc_preprocessor_config = config.get("SubPipelines", {}).get(
|
|
|
+ "DocPreprocessor",
|
|
|
+ {
|
|
|
+ "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
|
|
|
+ },
|
|
|
+ )
|
|
|
self.doc_preprocessor_pipeline = self.create_pipeline(
|
|
|
doc_preprocessor_config
|
|
|
)
|
|
|
|
|
|
- self.use_layout_detection = True
|
|
|
- if "use_layout_detection" in config:
|
|
|
- self.use_layout_detection = config["use_layout_detection"]
|
|
|
+ self.use_layout_detection = config.get("use_layout_detection", True)
|
|
|
+
|
|
|
if self.use_layout_detection:
|
|
|
- layout_det_config = config["SubModules"]["LayoutDetection"]
|
|
|
+ layout_det_config = config.get("SubModules", {}).get(
|
|
|
+ "LayoutDetection",
|
|
|
+ {"model_config_error": "config error for layout_det_model!"},
|
|
|
+ )
|
|
|
self.layout_det_model = self.create_model(layout_det_config)
|
|
|
|
|
|
- formula_recognition_config = config["SubModules"]["FormulaRecognition"]
|
|
|
+ formula_recognition_config = config.get("SubModules", {}).get(
|
|
|
+ "FormulaRecognition",
|
|
|
+ {"model_config_error": "config error for formula_rec_model!"},
|
|
|
+ )
|
|
|
self.formula_recognition_model = self.create_model(formula_recognition_config)
|
|
|
|
|
|
self._crop_by_boxes = CropByBoxes()
|
|
|
@@ -89,26 +93,56 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
self.batch_sampler = ImageBatchSampler(batch_size=1)
|
|
|
self.img_reader = ReadImage(format="BGR")
|
|
|
|
|
|
- def check_input_params_valid(
|
|
|
- self, input_params: Dict, layout_det_res: DetResult
|
|
|
+ def get_model_settings(
|
|
|
+ self,
|
|
|
+ use_doc_orientation_classify: Optional[bool],
|
|
|
+ use_doc_unwarping: Optional[bool],
|
|
|
+ use_layout_detection: Optional[bool],
|
|
|
+ ) -> dict:
|
|
|
+ """
|
|
|
+ Get the model settings based on the provided parameters or default values.
|
|
|
+
|
|
|
+ Args:
|
|
|
+ use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
|
|
|
+ use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
|
|
|
+ use_layout_detection (Optional[bool]): Whether to use layout detection.
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ dict: A dictionary containing the model settings.
|
|
|
+ """
|
|
|
+ if use_doc_orientation_classify is None and use_doc_unwarping is None:
|
|
|
+ use_doc_preprocessor = self.use_doc_preprocessor
|
|
|
+ else:
|
|
|
+ use_doc_preprocessor = True
|
|
|
+
|
|
|
+ if use_layout_detection is None:
|
|
|
+ use_layout_detection = self.use_layout_detection
|
|
|
+
|
|
|
+ return dict(
|
|
|
+ use_doc_preprocessor=use_doc_preprocessor,
|
|
|
+ use_layout_detection=use_layout_detection,
|
|
|
+ )
|
|
|
+
|
|
|
+ def check_model_settings_valid(
|
|
|
+ self, model_settings: Dict, layout_det_res: DetResult
|
|
|
) -> bool:
|
|
|
"""
|
|
|
Check if the input parameters are valid based on the initialized models.
|
|
|
|
|
|
Args:
|
|
|
- input_params (Dict): A dictionary containing input parameters.
|
|
|
+ model_settings (Dict): A dictionary containing input parameters.
|
|
|
layout_det_res (DetResult): The layout detection result.
|
|
|
Returns:
|
|
|
bool: True if all required models are initialized according to input parameters, False otherwise.
|
|
|
"""
|
|
|
|
|
|
- if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
|
|
|
+ if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
|
|
|
logging.error(
|
|
|
"Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
|
|
|
)
|
|
|
return False
|
|
|
|
|
|
- if input_params["use_layout_detection"]:
|
|
|
+ if model_settings["use_layout_detection"]:
|
|
|
if layout_det_res is not None:
|
|
|
logging.error(
|
|
|
"The layout detection model has already been initialized, please set use_layout_detection=False"
|
|
|
@@ -123,36 +157,6 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
|
|
|
return True
|
|
|
|
|
|
- def predict_doc_preprocessor_res(
|
|
|
- self, image_array: np.ndarray, input_params: dict
|
|
|
- ) -> tuple[DocPreprocessorResult, np.ndarray]:
|
|
|
- """
|
|
|
- Preprocess the document image based on input parameters.
|
|
|
-
|
|
|
- Args:
|
|
|
- image_array (np.ndarray): The input image array.
|
|
|
- input_params (dict): Dictionary containing preprocessing parameters.
|
|
|
-
|
|
|
- Returns:
|
|
|
- tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
|
|
|
- result dictionary and the processed image array.
|
|
|
- """
|
|
|
- if input_params["use_doc_preprocessor"]:
|
|
|
- use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
|
|
|
- use_doc_unwarping = input_params["use_doc_unwarping"]
|
|
|
- doc_preprocessor_res = next(
|
|
|
- self.doc_preprocessor_pipeline(
|
|
|
- image_array,
|
|
|
- use_doc_orientation_classify=use_doc_orientation_classify,
|
|
|
- use_doc_unwarping=use_doc_unwarping,
|
|
|
- )
|
|
|
- )
|
|
|
- doc_preprocessor_image = doc_preprocessor_res["output_img"]
|
|
|
- else:
|
|
|
- doc_preprocessor_res = {}
|
|
|
- doc_preprocessor_image = image_array
|
|
|
- return doc_preprocessor_res, doc_preprocessor_image
|
|
|
-
|
|
|
def predict_single_formula_recognition_res(
|
|
|
self,
|
|
|
image_array: np.ndarray,
|
|
|
@@ -179,7 +183,7 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
use_doc_orientation_classify: bool = False,
|
|
|
use_doc_unwarping: bool = False,
|
|
|
layout_det_res: DetResult = None,
|
|
|
- **kwargs
|
|
|
+ **kwargs,
|
|
|
) -> FormulaRecognitionResult:
|
|
|
"""
|
|
|
This function predicts the layout parsing result for the given input.
|
|
|
@@ -197,34 +201,41 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
formulaRecognitionResult: The predicted formula recognition result.
|
|
|
"""
|
|
|
|
|
|
- input_params = {
|
|
|
- "use_layout_detection": use_layout_detection,
|
|
|
- "use_doc_preprocessor": self.use_doc_preprocessor,
|
|
|
- "use_doc_orientation_classify": use_doc_orientation_classify,
|
|
|
- "use_doc_unwarping": use_doc_unwarping,
|
|
|
- }
|
|
|
-
|
|
|
- if use_doc_orientation_classify or use_doc_unwarping:
|
|
|
- input_params["use_doc_preprocessor"] = True
|
|
|
- else:
|
|
|
- input_params["use_doc_preprocessor"] = False
|
|
|
+ model_settings = self.get_model_settings(
|
|
|
+ use_doc_orientation_classify,
|
|
|
+ use_doc_unwarping,
|
|
|
+ use_layout_detection,
|
|
|
+ )
|
|
|
|
|
|
- if not self.check_input_params_valid(input_params, layout_det_res):
|
|
|
- yield None
|
|
|
+ if not self.check_model_settings_valid(model_settings, layout_det_res):
|
|
|
+ yield {"error": "the input params for model settings are invalid!"}
|
|
|
|
|
|
for img_id, batch_data in enumerate(self.batch_sampler(input)):
|
|
|
+ if not isinstance(batch_data[0], str):
|
|
|
+ # TODO: add support input_pth for ndarray and pdf
|
|
|
+ input_path = f"{img_id}.jpg"
|
|
|
+ else:
|
|
|
+ input_path = batch_data[0]
|
|
|
+
|
|
|
image_array = self.img_reader(batch_data)[0]
|
|
|
- input_path = batch_data[0]
|
|
|
- img_id += 1
|
|
|
|
|
|
- doc_preprocessor_res, doc_preprocessor_image = (
|
|
|
- self.predict_doc_preprocessor_res(image_array, input_params)
|
|
|
- )
|
|
|
+ if model_settings["use_doc_preprocessor"]:
|
|
|
+ doc_preprocessor_res = next(
|
|
|
+ self.doc_preprocessor_pipeline(
|
|
|
+ image_array,
|
|
|
+ use_doc_orientation_classify=use_doc_orientation_classify,
|
|
|
+ use_doc_unwarping=use_doc_unwarping,
|
|
|
+ )
|
|
|
+ )
|
|
|
+ else:
|
|
|
+ doc_preprocessor_res = {"output_img": image_array}
|
|
|
+
|
|
|
+ doc_preprocessor_image = doc_preprocessor_res["output_img"]
|
|
|
|
|
|
formula_res_list = []
|
|
|
formula_region_id = 1
|
|
|
|
|
|
- if not input_params["use_layout_detection"] and layout_det_res is None:
|
|
|
+ if not model_settings["use_layout_detection"] and layout_det_res is None:
|
|
|
layout_det_res = {}
|
|
|
img_height, img_width = doc_preprocessor_image.shape[:2]
|
|
|
single_formula_rec_res = self.predict_single_formula_recognition_res(
|
|
|
@@ -234,7 +245,7 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
formula_res_list.append(single_formula_rec_res)
|
|
|
formula_region_id += 1
|
|
|
else:
|
|
|
- if input_params["use_layout_detection"]:
|
|
|
+ if model_settings["use_layout_detection"]:
|
|
|
layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
|
|
|
for box_info in layout_det_res["boxes"]:
|
|
|
if box_info["label"].lower() in ["formula"]:
|
|
|
@@ -251,11 +262,10 @@ class FormulaRecognitionPipeline(BasePipeline):
|
|
|
formula_region_id += 1
|
|
|
|
|
|
single_img_res = {
|
|
|
+ "input_path": input_path,
|
|
|
"layout_det_res": layout_det_res,
|
|
|
"doc_preprocessor_res": doc_preprocessor_res,
|
|
|
"formula_res_list": formula_res_list,
|
|
|
- "input_params": input_params,
|
|
|
- "img_id": img_id,
|
|
|
- "img_name": input_path,
|
|
|
+ "model_settings": model_settings,
|
|
|
}
|
|
|
yield FormulaRecognitionResult(single_img_res)
|