CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
processing_udop.py195 linesDownload Raw Back to udop
1# coding=utf-82# Copyright 2024 The HuggingFace Inc. team.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""16Processor class for UDOP.17"""18 19from typing import Optional, Union20 21from transformers import logging22 23from ...image_processing_utils import BatchFeature24from ...image_utils import ImageInput25from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack26from ...tokenization_utils_base import PreTokenizedInput, TextInput27 28 29logger = logging.get_logger(__name__)30 31 32class UdopTextKwargs(TextKwargs, total=False):33    word_labels: Optional[Union[list[int], list[list[int]]]]34    boxes: Union[list[list[int]], list[list[list[int]]]]35 36 37class UdopProcessorKwargs(ProcessingKwargs, total=False):38    text_kwargs: UdopTextKwargs39    _defaults = {40        "text_kwargs": {41            "add_special_tokens": True,42            "padding": False,43            "truncation": False,44            "stride": 0,45            "return_overflowing_tokens": False,46            "return_special_tokens_mask": False,47            "return_offsets_mapping": False,48            "return_length": False,49            "verbose": True,50        },51        "images_kwargs": {},52    }53 54 55class UdopProcessor(ProcessorMixin):56    r"""57    Constructs a UDOP processor which combines a LayoutLMv3 image processor and a UDOP tokenizer into a single processor.58 59    [`UdopProcessor`] offers all the functionalities you need to prepare data for the model.60 61    It first uses [`LayoutLMv3ImageProcessor`] to resize, rescale and normalize document images, and optionally applies OCR62    to get words and normalized bounding boxes. These are then provided to [`UdopTokenizer`] or [`UdopTokenizerFast`],63    which turns the words and bounding boxes into token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`.64    Optionally, one can provide integer `word_labels`, which are turned into token-level `labels` for token65    classification tasks (such as FUNSD, CORD).66 67    Additionally, it also supports passing `text_target` and `text_pair_target` to the tokenizer, which can be used to68    prepare labels for language modeling tasks.69 70    Args:71        image_processor (`LayoutLMv3ImageProcessor`):72            An instance of [`LayoutLMv3ImageProcessor`]. The image processor is a required input.73        tokenizer (`UdopTokenizer` or `UdopTokenizerFast`):74            An instance of [`UdopTokenizer`] or [`UdopTokenizerFast`]. The tokenizer is a required input.75    """76 77    attributes = ["image_processor", "tokenizer"]78    image_processor_class = "LayoutLMv3ImageProcessor"79    tokenizer_class = ("UdopTokenizer", "UdopTokenizerFast")80 81    def __init__(self, image_processor, tokenizer):82        super().__init__(image_processor, tokenizer)83 84    def __call__(85        self,86        images: Optional[ImageInput] = None,87        text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,88        audio=None,89        videos=None,90        **kwargs: Unpack[UdopProcessorKwargs],91    ) -> BatchFeature:92        """93        This method first forwards the `images` argument to [`~UdopImageProcessor.__call__`]. In case94        [`UdopImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and95        bounding boxes along with the additional arguments to [`~UdopTokenizer.__call__`] and returns the output,96        together with the prepared `pixel_values`. In case [`UdopImageProcessor`] was initialized with `apply_ocr` set97        to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the98        additional arguments to [`~UdopTokenizer.__call__`] and returns the output, together with the prepared99        `pixel_values`.100 101        Alternatively, one can pass `text_target` and `text_pair_target` to prepare the targets of UDOP.102 103        Please refer to the docstring of the above two methods for more information.104        """105        # verify input106        output_kwargs = self._merge_kwargs(107            UdopProcessorKwargs,108            tokenizer_init_kwargs=self.tokenizer.init_kwargs,109            **kwargs,110        )111 112        boxes = output_kwargs["text_kwargs"].pop("boxes", None)113        word_labels = output_kwargs["text_kwargs"].pop("word_labels", None)114        text_pair = output_kwargs["text_kwargs"].pop("text_pair", None)115        return_overflowing_tokens = output_kwargs["text_kwargs"].get("return_overflowing_tokens", False)116        return_offsets_mapping = output_kwargs["text_kwargs"].get("return_offsets_mapping", False)117        text_target = output_kwargs["text_kwargs"].get("text_target", None)118 119        if self.image_processor.apply_ocr and (boxes is not None):120            raise ValueError(121                "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."122            )123 124        if self.image_processor.apply_ocr and (word_labels is not None):125            raise ValueError(126                "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."127            )128 129        if return_overflowing_tokens and not return_offsets_mapping:130            raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")131 132        if text_target is not None:133            # use the processor to prepare the targets of UDOP134            return self.tokenizer(135                **output_kwargs["text_kwargs"],136            )137 138        else:139            # use the processor to prepare the inputs of UDOP140            # first, apply the image processor141            features = self.image_processor(images=images, **output_kwargs["images_kwargs"])142            features_words = features.pop("words", None)143            features_boxes = features.pop("boxes", None)144 145            output_kwargs["text_kwargs"].pop("text_target", None)146            output_kwargs["text_kwargs"].pop("text_pair_target", None)147            output_kwargs["text_kwargs"]["text_pair"] = text_pair148            output_kwargs["text_kwargs"]["boxes"] = boxes if boxes is not None else features_boxes149            output_kwargs["text_kwargs"]["word_labels"] = word_labels150 151            # second, apply the tokenizer152            if text is not None and self.image_processor.apply_ocr and text_pair is None:153                if isinstance(text, str):154                    text = [text]  # add batch dimension (as the image processor always adds a batch dimension)155                output_kwargs["text_kwargs"]["text_pair"] = features_words156 157            encoded_inputs = self.tokenizer(158                text=text if text is not None else features_words,159                **output_kwargs["text_kwargs"],160            )161 162            # add pixel values163            if return_overflowing_tokens is True:164                features["pixel_values"] = self.get_overflowing_images(165                    features["pixel_values"], encoded_inputs["overflow_to_sample_mapping"]166                )167            features.update(encoded_inputs)168 169            return features170 171    # Copied from transformers.models.layoutlmv3.processing_layoutlmv3.LayoutLMv3Processor.get_overflowing_images172    def get_overflowing_images(self, images, overflow_to_sample_mapping):173        # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image174        images_with_overflow = []175        for sample_idx in overflow_to_sample_mapping:176            images_with_overflow.append(images[sample_idx])177 178        if len(images_with_overflow) != len(overflow_to_sample_mapping):179            raise ValueError(180                "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"181                f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"182            )183 184        return images_with_overflow185 186    @property187    def model_input_names(self):188        tokenizer_input_names = self.tokenizer.model_input_names189        image_processor_input_names = self.image_processor.model_input_names190 191        return list(tokenizer_input_names + image_processor_input_names + ["bbox"])192 193 194__all__ = ["UdopProcessor"]195 
Aluode/PerceptionLabPortable · CoolFace