|
| 1 | +from typing import Final, Optional, Union, Dict, List |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from PIL import Image |
| 5 | +from huggingface_hub import hf_hub_download |
| 6 | + |
| 7 | +from unstructured_inference.logger import logger |
| 8 | +from unstructured_inference.inference.layoutelement import LayoutElement |
| 9 | +from unstructured_inference.models.unstructuredmodel import UnstructuredModel |
| 10 | +from unstructured_inference.utils import LazyDict, LazyEvaluateInfo |
| 11 | +import onnxruntime |
| 12 | +import numpy as np |
| 13 | +import cv2 |
| 14 | + |
| 15 | + |
| 16 | +DEFAULT_LABEL_MAP: Final[Dict[int, str]] = { |
| 17 | + 0: "Text", |
| 18 | + 1: "Title", |
| 19 | + 2: "List", |
| 20 | + 3: "Table", |
| 21 | + 4: "Figure", |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +# NOTE(alan): Entries are implemented as LazyDicts so that models aren't downloaded until they are |
| 26 | +# needed. |
| 27 | +MODEL_TYPES: Dict[Optional[str], LazyDict] = { |
| 28 | + "detectron2_onnx": LazyDict( |
| 29 | + model_path=LazyEvaluateInfo( |
| 30 | + hf_hub_download, |
| 31 | + "unstructuredio/detectron2_faster_rcnn_R_50_FPN_3x", |
| 32 | + "model.onnx", |
| 33 | + ), |
| 34 | + label_map=DEFAULT_LABEL_MAP, |
| 35 | + confidence_threshold=0.8, |
| 36 | + ), |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +class UnstructuredDetectronONNXModel(UnstructuredModel): |
| 41 | + """Unstructured model wrapper for detectron2 ONNX model.""" |
| 42 | + |
| 43 | + # The model was trained and exported with this shape |
| 44 | + required_w = 800 |
| 45 | + required_h = 1035 |
| 46 | + |
| 47 | + def predict(self, image: Image.Image) -> List[LayoutElement]: |
| 48 | + """Makes a prediction using detectron2 model.""" |
| 49 | + super().predict(image) |
| 50 | + |
| 51 | + prepared_input = self.preprocess(image) |
| 52 | + bboxes, labels, confidence_scores, _ = self.model.run(None, prepared_input) |
| 53 | + input_w, input_h = image.size |
| 54 | + regions = self.postprocess(bboxes, labels, confidence_scores, input_w, input_h) |
| 55 | + |
| 56 | + return regions |
| 57 | + |
| 58 | + def initialize( |
| 59 | + self, |
| 60 | + model_path: Union[str, Path], |
| 61 | + label_map: Dict[int, str], |
| 62 | + confidence_threshold: Optional[float] = None, |
| 63 | + ): |
| 64 | + """Loads the detectron2 model using the specified parameters""" |
| 65 | + logger.info("Loading the Detectron2 layout model ...") |
| 66 | + self.model = onnxruntime.InferenceSession(model_path, providers=["CPUExecutionProvider"]) |
| 67 | + self.label_map = label_map |
| 68 | + if confidence_threshold is None: |
| 69 | + confidence_threshold = 0.5 |
| 70 | + self.confidence_threshold = confidence_threshold |
| 71 | + |
| 72 | + def preprocess(self, image: Image.Image) -> Dict[str, np.ndarray]: |
| 73 | + """Process input image into required format for ingestion into the Detectron2 ONNX binary. |
| 74 | + This involves resizing to a fixed shape and converting to a specific numpy format.""" |
| 75 | + # TODO (benjamin): check other shapes for inference |
| 76 | + img = np.array(image) |
| 77 | + # TODO (benjamin): We should use models.get_model() but currenly returns Detectron model |
| 78 | + session = self.model |
| 79 | + # onnx input expected |
| 80 | + # [3,1035,800] |
| 81 | + img = cv2.resize( |
| 82 | + img, |
| 83 | + (self.required_w, self.required_h), |
| 84 | + interpolation=cv2.INTER_LINEAR, |
| 85 | + ).astype(np.float32) |
| 86 | + img = img.transpose(2, 0, 1) |
| 87 | + ort_inputs = {session.get_inputs()[0].name: img} |
| 88 | + return ort_inputs |
| 89 | + |
| 90 | + def postprocess( |
| 91 | + self, |
| 92 | + bboxes: np.ndarray, |
| 93 | + labels: np.ndarray, |
| 94 | + confidence_scores: np.ndarray, |
| 95 | + input_w: float, |
| 96 | + input_h: float, |
| 97 | + ) -> List[LayoutElement]: |
| 98 | + """Process output into Unstructured class. Bounding box coordinates are converted to |
| 99 | + original image resolution.""" |
| 100 | + regions = [] |
| 101 | + width_conversion = input_w / self.required_w |
| 102 | + height_conversion = input_h / self.required_h |
| 103 | + for (x1, y1, x2, y2), label, conf in zip(bboxes, labels, confidence_scores): |
| 104 | + detected_class = self.label_map[int(label)] |
| 105 | + if conf >= self.confidence_threshold: |
| 106 | + region = LayoutElement( |
| 107 | + x1 * width_conversion, |
| 108 | + y1 * height_conversion, |
| 109 | + x2 * width_conversion, |
| 110 | + y2 * height_conversion, |
| 111 | + text=None, |
| 112 | + type=detected_class, |
| 113 | + ) |
| 114 | + |
| 115 | + regions.append(region) |
| 116 | + |
| 117 | + regions.sort(key=lambda element: element.y1) |
| 118 | + return regions |
0 commit comments