2022 the impira team and the huggingface team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license normalizebbox and applytesseract are derived from applytesseract in modelslayoutlmv3featureextractionlayoutlmv3 py however because the pipeline may evolve from what layoutlmv3 currently does it s copied vs imported to avoid creating an unnecessary dependency applies tesseract ocr on a document image and returns recognized words normalized bounding boxes apply ocr data pytesseract imagetodataimage langlang outputtypedict configtesseractconfig words left top width height datatext dataleft datatop datawidth dataheight filter empty words and corresponding coordinates irrelevantindices idx for idx word in enumeratewords if not word strip words word for idx word in enumeratewords if idx not in irrelevantindices left coord for idx coord in enumerateleft if idx not in irrelevantindices top coord for idx coord in enumeratetop if idx not in irrelevantindices width coord for idx coord in enumeratewidth if idx not in irrelevantindices height coord for idx coord in enumerateheight if idx not in irrelevantindices turn coordinates into left top leftwidth topheight format actualboxes for x y w h in zipleft top width height actualbox x y x w y h actualboxes appendactualbox imagewidth imageheight image size finally normalize the bounding boxes normalizedboxes for box in actualboxes normalizedboxes appendnormalizeboxbox imagewidth imageheight if lenwords lennormalizedboxes raise valueerrornot as many words as there are bounding boxes return words normalizedboxes class modeltypeexplicitenum layoutlm layoutlm layoutlmv2andv3 layoutlmv2andv3 visionencoderdecoder visionencoderdecoder addenddocstringspipelineinitargs class documentquestionansweringpipelinechunkpipeline todo update tasksummary docs to include an example with document qa and then update the first sentence def initself args kwargs super initargs kwargs if self tokenizer is not none and not self tokenizer class name endswithfast raise valueerror documentquestionansweringpipeline requires a fast tokenizer but a slow tokenizer fself tokenizer class name is provided if self model config class name visionencoderdecoderconfig self modeltype modeltype visionencoderdecoder if self model config encoder modeltype donutswin raise valueerrorcurrently the only supported visionencoderdecoder model is donut else self checkmodeltypemodelfordocumentquestionansweringmappingnames if self model config class name layoutlmconfig self modeltype modeltype layoutlm else self modeltype modeltype layoutlmv2andv3 def sanitizeparameters self paddingnone docstridenone maxquestionlennone lang optionalstr none tesseractconfig optionalstr none maxanswerlennone maxseqlennone topknone handleimpossibleanswernone timeoutnone kwargs preprocessparams postprocessparams if padding is not none preprocessparamspadding padding if docstride is not none preprocessparamsdocstride docstride if maxquestionlen is not none preprocessparamsmaxquestionlen maxquestionlen if maxseqlen is not none preprocessparamsmaxseqlen maxseqlen if lang is not none preprocessparamslang lang if tesseractconfig is not none preprocessparamstesseractconfig tesseractconfig if timeout is not none preprocessparamstimeout timeout if topk is not none if topk 1 raise valueerrorftopk parameter should be 1 got topk postprocessparamstopk topk if maxanswerlen is not none if maxanswerlen 1 raise valueerrorfmaxanswerlen parameter should be 1 got maxanswerlen postprocessparamsmaxanswerlen maxanswerlen if handleimpossibleanswer is not none postprocessparamshandleimpossibleanswer handleimpossibleanswer return preprocessparams postprocessparams def call self image unionimage image str question optionalstr none wordboxes tuplestr listfloat none kwargs if isinstancequestion str inputs question question image image if wordboxes is not none inputswordboxes wordboxes else inputs image return super callinputs kwargs def preprocess self input paddingdonotpad docstridenone maxseqlennone wordboxes tuplestr listfloat none langnone tesseractconfig timeoutnone note this code mirrors the code in question answering and will be implemented in a follow up pr to support documents with enough tokens that overflow the model s window if maxseqlen is none maxseqlen self tokenizer modelmaxlength if docstride is none docstride minmaxseqlen 2 256 image none imagefeatures if input getimage none is not none image loadimageinputimage timeouttimeout if self imageprocessor is not none imagefeatures updateself imageprocessorimagesimage returntensorsself framework elif self featureextractor is not none imagefeatures updateself featureextractorimagesimage returntensorsself framework elif self modeltype modeltype visionencoderdecoder raise valueerrorif you are using a visionencoderdecodermodel you must provide a feature extractor words boxes none none if not self modeltype modeltype visionencoderdecoder if wordboxes in input words x0 for x in inputwordboxes boxes x1 for x in inputwordboxes elif words in imagefeatures and boxes in imagefeatures words imagefeatures popwords0 boxes imagefeatures popboxes0 elif image is not none if not tesseractloaded raise valueerror if you provide an image without wordboxes then the pipeline will run ocr using tesseract but pytesseract is not available if tesseractloaded words boxes applytesseractimage langlang tesseractconfigtesseractconfig else raise valueerror you must provide an image or wordboxes if you provide an image the pipeline will automatically run ocr to derive words and boxes if self tokenizer paddingside right raise valueerror document question answering only supports tokenizers whose padding side is right not f self tokenizer paddingside if self modeltype modeltype visionencoderdecoder taskprompt f sdocvqasquestioninputquestionsquestionsanswer adapted from https huggingface cospacesnielsrdonutdocvqablobmainapp py encoding inputs imagefeaturespixelvalues decoderinputids self tokenizer taskprompt addspecialtokensfalse returntensorsself framework inputids returndictingenerate true yield encoding pmask none wordids none words none outputattentions true islast true else tokenizerkwargs if self modeltype modeltype layoutlm tokenizerkwargstext inputquestion split tokenizerkwargstextpair words tokenizerkwargsissplitintowords true else tokenizerkwargstext inputquestion tokenizerkwargstextpair words tokenizerkwargsboxes boxes encoding self tokenizer paddingpadding maxlengthmaxseqlen stridedocstride returntokentypeidstrue truncationonlysecond returnoverflowingtokenstrue tokenizerkwargs todo check why slower layoutlmtokenizer and layoutlmv2tokenizer don t have this key in outputs fixme ydshieh andor narsil encoding popoverflowtosamplemapping none we do not use this numspans lenencodinginputids pmask mask with 1 for token than cannot be in the answer 0 for token which can be in an answer we put 0 on the tokens from the context and 1 everywhere else question and special tokens this logic mirrors the logic in the questionanswering pipeline pmask tok 1 for tok in encoding sequenceidsspanid for spanid in rangenumspans for spanidx in rangenumspans if self framework pt spanencoding k torch tensorvspanidx spanidx 1 for k v in encoding items if pixelvalues in imagefeatures spanencodingimage imagefeaturespixelvalues else raise valueerrorunsupported tensorflow preprocessing for documentquestionansweringpipeline inputidsspanidx encodinginputidsspanidx keep the clstoken unmasked some models use it to indicate unanswerable questions if self tokenizer clstokenid is not none clsindices np nonzeronp arrayinputidsspanidx self tokenizer clstokenid0 for clsindex in clsindices pmaskspanidxclsindex 0 for each span place a bounding box 0 0 0 0 for question and cls tokens 1000 1000 1000 1000 for sep tokens and the word s bounding box for words in the original document if boxes not in tokenizerkwargs bbox for inputid sequenceid wordid in zip encoding inputidsspanidx encoding sequenceidsspanidx encoding wordidsspanidx if sequenceid 1 bbox appendboxeswordid elif inputid self tokenizer septokenid bbox append1000 4 else bbox append0 4 if self framework pt spanencodingbbox torch tensorbbox unsqueeze0 elif self framework tf raise valueerrorunsupported tensorflow preprocessing for documentquestionansweringpipeline yield spanencoding pmask pmaskspanidx wordids encoding wordidsspanidx words words islast spanidx numspans 1 def forwardself modelinputs pmask modelinputs poppmask none wordids modelinputs popwordids none words modelinputs popwords none islast modelinputs popislast false if self modeltype modeltype visionencoderdecoder modeloutputs self model generatemodelinputs else modeloutputs self modelmodelinputs modeloutputs dictmodeloutputs items modeloutputspmask pmask modeloutputswordids wordids modeloutputswords words modeloutputsattentionmask modelinputs getattentionmask none modeloutputsislast islast return modeloutputs def postprocessself modeloutputs topk1 kwargs if self modeltype modeltype visionencoderdecoder answers self postprocessencoderdecodersingleo for o in modeloutputs else answers self postprocessextractiveqamodeloutputs topktopk kwargs answers sortedanswers keylambda x x getscore 0 reversetrue topk return answers def postprocessencoderdecodersingleself modeloutputs kwargs sequence self tokenizer batchdecodemodeloutputssequences0 todo a lot of this logic is specific to donut and should probably be handled in the tokenizer see https github comhuggingfacetransformerspull18414filesr961747408 for more context sequence sequence replaceself tokenizer eostoken replaceself tokenizer padtoken sequence re subr sequence count1 strip remove first task start token ret answer none answer re searchrsanswer sanswer sequence if answer is not none retanswer answer group1 strip return ret def postprocessextractiveqa self modeloutputs topk1 handleimpossibleanswerfalse maxanswerlen15 kwargs minnullscore 1000000 large and positive answers for output in modeloutputs words outputwords starts ends scores minnullscore selectstartsends startoutputstartlogits endoutputendlogits pmaskoutputpmask attentionmaskoutputattentionmask numpy if output getattentionmask none is not none else none minnullscoreminnullscore topktopk handleimpossibleanswerhandleimpossibleanswer maxanswerlenmaxanswerlen wordids outputwordids for start end score in zipstarts ends scores wordstart wordend wordidsstart wordidsend if wordstart is not none and wordend is not none answers append score floatscore answer joinwordswordstart wordend 1 start wordstart end wordend if handleimpossibleanswer answers appendscore minnullscore answer start 0 end 0 return answers 2022 the impira team and the huggingface team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license normalize_bbox and apply_tesseract are derived from apply_tesseract in models layoutlmv3 feature_extraction_layoutlmv3 py however because the pipeline may evolve from what layoutlmv3 currently does it s copied vs imported to avoid creating an unnecessary dependency applies tesseract ocr on a document image and returns recognized words normalized bounding boxes apply ocr filter empty words and corresponding coordinates turn coordinates into left top left width top height format finally normalize the bounding boxes todo update task_summary docs to include an example with document qa and then update the first sentence document question answering pipeline using any automodelfordocumentquestionanswering the inputs outputs are similar to the extractive question answering pipeline however the pipeline takes an image and optional ocr d words boxes as input instead of text context example python from transformers import pipeline document_qa pipeline model impira layoutlm document qa document_qa image https huggingface co spaces impira docquery resolve 2359223c1837a7587402bda0f2643382a6eefeab invoice png question what is the invoice number score 0 425 answer us 001 start 16 end 16 learn more about the basics of using a pipeline in the pipeline tutorial pipeline_tutorial this document question answering pipeline can currently be loaded from pipeline using the following task identifier document question answering the models that this pipeline can use are models that have been fine tuned on a document question answering task see the up to date list of available models on huggingface co models https huggingface co models filter document question answering answer the question s given as inputs by using the document s a document is defined as an image and an optional list of word box tuples which represent the text in the document if the word_boxes are not provided it will use the tesseract ocr engine if available to extract the words and boxes automatically for layoutlm like models which require them as input for donut no ocr is run you can invoke the pipeline several ways pipeline image image question question pipeline image image question question word_boxes word_boxes pipeline image image question question pipeline image image question question word_boxes word_boxes args image str or pil image the pipeline handles three types of images a string containing a http link pointing to an image a string containing a local path to an image an image loaded in pil directly the pipeline accepts either a single image or a batch of images if given a single image it can be broadcasted to multiple questions question str a question to ask of the document word_boxes list str tuple float float float float optional a list of words and bounding boxes normalized 0 1000 if you provide this optional input then the pipeline will use these words and boxes instead of running ocr on the image to derive them for models that need them e g layoutlm this allows you to reuse ocr d results across many invocations of the pipeline without having to re run it each time top_k int optional defaults to 1 the number of answers to return will be chosen by order of likelihood note that we return less than top_k answers if there are not enough options available within the context doc_stride int optional defaults to 128 if the words in the document are too long to fit with the question for the model it will be split in several chunks with some overlap this argument controls the size of that overlap max_answer_len int optional defaults to 15 the maximum length of predicted answers e g only answers with a shorter length are considered max_seq_len int optional defaults to 384 the maximum length of the total sentence context question in tokens of each chunk passed to the model the context will be split in several chunks using doc_stride as overlap if needed max_question_len int optional defaults to 64 the maximum length of the question after tokenization it will be truncated if needed handle_impossible_answer bool optional defaults to false whether or not we accept impossible as an answer lang str optional language to use while running ocr defaults to english tesseract_config str optional additional flags to pass to tesseract while running ocr timeout float optional defaults to none the maximum time in seconds to wait for fetching images from the web if none no timeout is set and the call may block forever return a dict or a list of dict each result comes as a dictionary with the following keys score float the probability associated to the answer start int the start word index of the answer in the ocr d version of the input or provided word_boxes end int the end word index of the answer in the ocr d version of the input or provided word_boxes answer str the answer to the question words list int the index of each word box pair that is in the answer note this code mirrors the code in question answering and will be implemented in a follow up pr to support documents with enough tokens that overflow the model s window adapted from https huggingface co spaces nielsr donut docvqa blob main app py todo check why slower layoutlmtokenizer and layoutlmv2tokenizer don t have this key in outputs fixme ydshieh and or narsil we do not use this p_mask mask with 1 for token than cannot be in the answer 0 for token which can be in an answer we put 0 on the tokens from the context and 1 everywhere else question and special tokens this logic mirrors the logic in the question_answering pipeline keep the cls_token unmasked some models use it to indicate unanswerable questions for each span place a bounding box 0 0 0 0 for question and cls tokens 1000 1000 1000 1000 for sep tokens and the word s bounding box for words in the original document todo a lot of this logic is specific to donut and should probably be handled in the tokenizer see https github com huggingface transformers pull 18414 files r961747408 for more context remove first task start token large and positive
import re
from typing import List, Optional, Tuple, Union

import numpy as np

from ..utils import (
    ExplicitEnum,
    add_end_docstrings,
    is_pytesseract_available,
    is_torch_available,
    is_vision_available,
    logging,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
from .question_answering import select_starts_ends


if is_vision_available():
    from PIL import Image

    from ..image_utils import load_image

if is_torch_available():
    import torch

    from ..models.auto.modeling_auto import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES

TESSERACT_LOADED = False
if is_pytesseract_available():
    TESSERACT_LOADED = True
    import pytesseract

logger = logging.get_logger(__name__)





def normalize_box(box, width, height):
    return [
        int(1000 * (box[0] / width)),
        int(1000 * (box[1] / height)),
        int(1000 * (box[2] / width)),
        int(1000 * (box[3] / height)),
    ]


def apply_tesseract(image: "Image.Image", lang: Optional[str], tesseract_config: Optional[str]):
    
    
    data = pytesseract.image_to_data(image, lang=lang, output_type="dict", config=tesseract_config)
    words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]

    
    irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
    words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
    left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
    top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
    width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
    height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]

    
    actual_boxes = []
    for x, y, w, h in zip(left, top, width, height):
        actual_box = [x, y, x + w, y + h]
        actual_boxes.append(actual_box)

    image_width, image_height = image.size

    
    normalized_boxes = []
    for box in actual_boxes:
        normalized_boxes.append(normalize_box(box, image_width, image_height))

    if len(words) != len(normalized_boxes):
        raise ValueError("Not as many words as there are bounding boxes")

    return words, normalized_boxes


class ModelType(ExplicitEnum):
    LayoutLM = "layoutlm"
    LayoutLMv2andv3 = "layoutlmv2andv3"
    VisionEncoderDecoder = "vision_encoder_decoder"


@add_end_docstrings(PIPELINE_INIT_ARGS)
class DocumentQuestionAnsweringPipeline(ChunkPipeline):
    
    

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.tokenizer is not None and not self.tokenizer.__class__.__name__.endswith("Fast"):
            raise ValueError(
                "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer "
                f"(`{self.tokenizer.__class__.__name__}`) is provided."
            )

        if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig":
            self.model_type = ModelType.VisionEncoderDecoder
            if self.model.config.encoder.model_type != "donut-swin":
                raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut")
        else:
            self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES)
            if self.model.config.__class__.__name__ == "LayoutLMConfig":
                self.model_type = ModelType.LayoutLM
            else:
                self.model_type = ModelType.LayoutLMv2andv3

    def _sanitize_parameters(
        self,
        padding=None,
        doc_stride=None,
        max_question_len=None,
        lang: Optional[str] = None,
        tesseract_config: Optional[str] = None,
        max_answer_len=None,
        max_seq_len=None,
        top_k=None,
        handle_impossible_answer=None,
        timeout=None,
        **kwargs,
    ):
        preprocess_params, postprocess_params = {}, {}
        if padding is not None:
            preprocess_params["padding"] = padding
        if doc_stride is not None:
            preprocess_params["doc_stride"] = doc_stride
        if max_question_len is not None:
            preprocess_params["max_question_len"] = max_question_len
        if max_seq_len is not None:
            preprocess_params["max_seq_len"] = max_seq_len
        if lang is not None:
            preprocess_params["lang"] = lang
        if tesseract_config is not None:
            preprocess_params["tesseract_config"] = tesseract_config
        if timeout is not None:
            preprocess_params["timeout"] = timeout

        if top_k is not None:
            if top_k < 1:
                raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
            postprocess_params["top_k"] = top_k
        if max_answer_len is not None:
            if max_answer_len < 1:
                raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len}")
            postprocess_params["max_answer_len"] = max_answer_len
        if handle_impossible_answer is not None:
            postprocess_params["handle_impossible_answer"] = handle_impossible_answer

        return preprocess_params, {}, postprocess_params

    def __call__(
        self,
        image: Union["Image.Image", str],
        question: Optional[str] = None,
        word_boxes: Tuple[str, List[float]] = None,
        **kwargs,
    ):
        
        if isinstance(question, str):
            inputs = {"question": question, "image": image}
            if word_boxes is not None:
                inputs["word_boxes"] = word_boxes
        else:
            inputs = image
        return super().__call__(inputs, **kwargs)

    def preprocess(
        self,
        input,
        padding="do_not_pad",
        doc_stride=None,
        max_seq_len=None,
        word_boxes: Tuple[str, List[float]] = None,
        lang=None,
        tesseract_config="",
        timeout=None,
    ):
        
        
        if max_seq_len is None:
            max_seq_len = self.tokenizer.model_max_length

        if doc_stride is None:
            doc_stride = min(max_seq_len // 2, 256)

        image = None
        image_features = {}
        if input.get("image", None) is not None:
            image = load_image(input["image"], timeout=timeout)
            if self.image_processor is not None:
                image_features.update(self.image_processor(images=image, return_tensors=self.framework))
            elif self.feature_extractor is not None:
                image_features.update(self.feature_extractor(images=image, return_tensors=self.framework))
            elif self.model_type == ModelType.VisionEncoderDecoder:
                raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor")

        words, boxes = None, None
        if not self.model_type == ModelType.VisionEncoderDecoder:
            if "word_boxes" in input:
                words = [x[0] for x in input["word_boxes"]]
                boxes = [x[1] for x in input["word_boxes"]]
            elif "words" in image_features and "boxes" in image_features:
                words = image_features.pop("words")[0]
                boxes = image_features.pop("boxes")[0]
            elif image is not None:
                if not TESSERACT_LOADED:
                    raise ValueError(
                        "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract,"
                        " but pytesseract is not available"
                    )
                if TESSERACT_LOADED:
                    words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config)
            else:
                raise ValueError(
                    "You must provide an image or word_boxes. If you provide an image, the pipeline will automatically"
                    " run OCR to derive words and boxes"
                )

        if self.tokenizer.padding_side != "right":
            raise ValueError(
                "Document question answering only supports tokenizers whose padding side is 'right', not"
                f" {self.tokenizer.padding_side}"
            )

        if self.model_type == ModelType.VisionEncoderDecoder:
            task_prompt = f'<s_docvqa><s_question>{input["question"]}</s_question><s_answer>'
            
            encoding = {
                "inputs": image_features["pixel_values"],
                "decoder_input_ids": self.tokenizer(
                    task_prompt, add_special_tokens=False, return_tensors=self.framework
                ).input_ids,
                "return_dict_in_generate": True,
            }
            yield {
                **encoding,
                "p_mask": None,
                "word_ids": None,
                "words": None,
                "output_attentions": True,
                "is_last": True,
            }
        else:
            tokenizer_kwargs = {}
            if self.model_type == ModelType.LayoutLM:
                tokenizer_kwargs["text"] = input["question"].split()
                tokenizer_kwargs["text_pair"] = words
                tokenizer_kwargs["is_split_into_words"] = True
            else:
                tokenizer_kwargs["text"] = [input["question"]]
                tokenizer_kwargs["text_pair"] = [words]
                tokenizer_kwargs["boxes"] = [boxes]

            encoding = self.tokenizer(
                padding=padding,
                max_length=max_seq_len,
                stride=doc_stride,
                return_token_type_ids=True,
                truncation="only_second",
                return_overflowing_tokens=True,
                **tokenizer_kwargs,
            )
            
            
            encoding.pop("overflow_to_sample_mapping", None)  

            num_spans = len(encoding["input_ids"])

            
            
            
            p_mask = [[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)]
            for span_idx in range(num_spans):
                if self.framework == "pt":
                    span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()}
                    if "pixel_values" in image_features:
                        span_encoding["image"] = image_features["pixel_values"]
                else:
                    raise ValueError("Unsupported: Tensorflow preprocessing for DocumentQuestionAnsweringPipeline")

                input_ids_span_idx = encoding["input_ids"][span_idx]
                
                if self.tokenizer.cls_token_id is not None:
                    cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
                    for cls_index in cls_indices:
                        p_mask[span_idx][cls_index] = 0

                
                
                if "boxes" not in tokenizer_kwargs:
                    bbox = []
                    for input_id, sequence_id, word_id in zip(
                        encoding.input_ids[span_idx],
                        encoding.sequence_ids(span_idx),
                        encoding.word_ids(span_idx),
                    ):
                        if sequence_id == 1:
                            bbox.append(boxes[word_id])
                        elif input_id == self.tokenizer.sep_token_id:
                            bbox.append([1000] * 4)
                        else:
                            bbox.append([0] * 4)

                    if self.framework == "pt":
                        span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0)
                    elif self.framework == "tf":
                        raise ValueError("Unsupported: Tensorflow preprocessing for DocumentQuestionAnsweringPipeline")
                yield {
                    **span_encoding,
                    "p_mask": p_mask[span_idx],
                    "word_ids": encoding.word_ids(span_idx),
                    "words": words,
                    "is_last": span_idx == num_spans - 1,
                }

    def _forward(self, model_inputs):
        p_mask = model_inputs.pop("p_mask", None)
        word_ids = model_inputs.pop("word_ids", None)
        words = model_inputs.pop("words", None)
        is_last = model_inputs.pop("is_last", False)

        if self.model_type == ModelType.VisionEncoderDecoder:
            model_outputs = self.model.generate(**model_inputs)
        else:
            model_outputs = self.model(**model_inputs)

        model_outputs = dict(model_outputs.items())
        model_outputs["p_mask"] = p_mask
        model_outputs["word_ids"] = word_ids
        model_outputs["words"] = words
        model_outputs["attention_mask"] = model_inputs.get("attention_mask", None)
        model_outputs["is_last"] = is_last
        return model_outputs

    def postprocess(self, model_outputs, top_k=1, **kwargs):
        if self.model_type == ModelType.VisionEncoderDecoder:
            answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs]
        else:
            answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs)

        answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k]
        return answers

    def postprocess_encoder_decoder_single(self, model_outputs, **kwargs):
        sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0]

        
        
        sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "")
        sequence = re.sub(r"<.*?>", "", sequence, count=1).strip()  
        ret = {
            "answer": None,
        }

        answer = re.search(r"<s_answer>(.*)</s_answer>", sequence)
        if answer is not None:
            ret["answer"] = answer.group(1).strip()
        return ret

    def postprocess_extractive_qa(
        self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs
    ):
        min_null_score = 1000000  
        answers = []
        for output in model_outputs:
            words = output["words"]

            starts, ends, scores, min_null_score = select_starts_ends(
                start=output["start_logits"],
                end=output["end_logits"],
                p_mask=output["p_mask"],
                attention_mask=output["attention_mask"].numpy()
                if output.get("attention_mask", None) is not None
                else None,
                min_null_score=min_null_score,
                top_k=top_k,
                handle_impossible_answer=handle_impossible_answer,
                max_answer_len=max_answer_len,
            )
            word_ids = output["word_ids"]
            for start, end, score in zip(starts, ends, scores):
                word_start, word_end = word_ids[start], word_ids[end]
                if word_start is not None and word_end is not None:
                    answers.append(
                        {
                            "score": float(score),
                            "answer": " ".join(words[word_start : word_end + 1]),
                            "start": word_start,
                            "end": word_end,
                        }
                    )

        if handle_impossible_answer:
            answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0})

        return answers