




"""simple docstring"""


import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


A_						=				logging.get_logger(__name__)

A_						=				{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

A_						=				{
    '''vocab_file''': {
        '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''',
        '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''',
        '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''',
        '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''',
        '''bert-base-multilingual-uncased''': (
            '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt'''
        ),
        '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''',
        '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''',
        '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''',
        '''bert-large-uncased-whole-word-masking''': (
            '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt'''
        ),
        '''bert-large-cased-whole-word-masking''': (
            '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt'''
        ),
        '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
            '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'''
        ),
        '''bert-large-cased-whole-word-masking-finetuned-squad''': (
            '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'''
        ),
        '''bert-base-cased-finetuned-mrpc''': (
            '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt'''
        ),
        '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''',
        '''bert-base-german-dbmdz-uncased''': (
            '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt'''
        ),
        '''TurkuNLP/bert-base-finnish-cased-v1''': (
            '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt'''
        ),
        '''TurkuNLP/bert-base-finnish-uncased-v1''': (
            '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt'''
        ),
        '''wietsedv/bert-base-dutch-cased''': (
            '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''',
        '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''',
        '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''',
        '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''',
        '''bert-base-multilingual-uncased''': (
            '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json'''
        ),
        '''bert-base-multilingual-cased''': (
            '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json'''
        ),
        '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''',
        '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''',
        '''bert-large-uncased-whole-word-masking''': (
            '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json'''
        ),
        '''bert-large-cased-whole-word-masking''': (
            '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json'''
        ),
        '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
            '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'''
        ),
        '''bert-large-cased-whole-word-masking-finetuned-squad''': (
            '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'''
        ),
        '''bert-base-cased-finetuned-mrpc''': (
            '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json'''
        ),
        '''bert-base-german-dbmdz-cased''': (
            '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json'''
        ),
        '''bert-base-german-dbmdz-uncased''': (
            '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json'''
        ),
        '''TurkuNLP/bert-base-finnish-cased-v1''': (
            '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json'''
        ),
        '''TurkuNLP/bert-base-finnish-uncased-v1''': (
            '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json'''
        ),
        '''wietsedv/bert-base-dutch-cased''': (
            '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json'''
        ),
    },
}

A_						=				{
    '''bert-base-uncased''': 5_12,
    '''bert-large-uncased''': 5_12,
    '''bert-base-cased''': 5_12,
    '''bert-large-cased''': 5_12,
    '''bert-base-multilingual-uncased''': 5_12,
    '''bert-base-multilingual-cased''': 5_12,
    '''bert-base-chinese''': 5_12,
    '''bert-base-german-cased''': 5_12,
    '''bert-large-uncased-whole-word-masking''': 5_12,
    '''bert-large-cased-whole-word-masking''': 5_12,
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12,
    '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12,
    '''bert-base-cased-finetuned-mrpc''': 5_12,
    '''bert-base-german-dbmdz-cased''': 5_12,
    '''bert-base-german-dbmdz-uncased''': 5_12,
    '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12,
    '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12,
    '''wietsedv/bert-base-dutch-cased''': 5_12,
}

A_						=				{
    '''bert-base-uncased''': {'''do_lower_case''': True},
    '''bert-large-uncased''': {'''do_lower_case''': True},
    '''bert-base-cased''': {'''do_lower_case''': False},
    '''bert-large-cased''': {'''do_lower_case''': False},
    '''bert-base-multilingual-uncased''': {'''do_lower_case''': True},
    '''bert-base-multilingual-cased''': {'''do_lower_case''': False},
    '''bert-base-chinese''': {'''do_lower_case''': False},
    '''bert-base-german-cased''': {'''do_lower_case''': False},
    '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True},
    '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False},
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True},
    '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False},
    '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False},
    '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False},
    '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True},
    '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False},
    '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True},
    '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False},
}






class 					lowercase(     __a ):







 '''simple docstring'''





 lowercase__ 					=					VOCAB_FILES_NAMES
 lowercase__ 					=					PRETRAINED_VOCAB_FILES_MAP
 lowercase__ 					=					PRETRAINED_INIT_CONFIGURATION
 lowercase__ 					=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowercase__ 					=					BertTokenizer


 def __init__(				self:		int,      a_:		Any=None,      a_:		Tuple=None,      a_:		Tuple=True,      a_:		Union[str, Any]="[UNK]",      a_:		List[Any]="[SEP]",      a_:		Union[str, Any]="[PAD]",      a_:		List[str]="[CLS]",      a_:		Union[str, Any]="[MASK]",      a_:		List[str]=True,      a_:		List[str]=None,      **a_:		List[Any],      ):




   '''simple docstring'''



   super().__init__(
       a_,      tokenizer_file=a_,      do_lower_case=a_,      unk_token=a_,      sep_token=a_,      pad_token=a_,      cls_token=a_,      mask_token=a_,      tokenize_chinese_chars=a_,      strip_accents=a_,      **a_,      )

   _snake_case							:		Optional[int]								=  json.loads(self.backend_tokenizer.normalizer.__getstate__()		)
   if (
       normalizer_state.get("""lowercase""",      a_		) != do_lower_case
       or normalizer_state.get("""strip_accents""",      a_		) != strip_accents
       or normalizer_state.get("""handle_chinese_chars""",      a_		) != tokenize_chinese_chars
   ):
     _snake_case							:		Optional[int]								=  getattr(a_,      normalizer_state.pop("""type"""		)		)
     _snake_case							:		Optional[Any]								=  do_lower_case
     _snake_case							:		Optional[int]								=  strip_accents
     _snake_case							:		int								=  tokenize_chinese_chars
     _snake_case							:		Union[str, Any]								=  normalizer_class(**a_		)

   _snake_case							:		str								=  do_lower_case


 def  UpperCamelCase_   (				self:		Dict,      a_:		Dict,      a_:		str=None		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  [self.cls_token_id] + token_ids_a + [self.sep_token_id]

   if token_ids_a:
     output += token_ids_a + [self.sep_token_id]

   return output


 def  UpperCamelCase_   (				self:		Any,      a_:		List[int],      a_:		Optional[List[int]] = None		):




   '''simple docstring'''



   _snake_case							:		Dict								=  [self.sep_token_id]
   _snake_case							:		str								=  [self.cls_token_id]
   if token_ids_a is None:
     return len(cls + token_ids_a + sep		) * [0]
   return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + sep		) * [1]


 def  UpperCamelCase_   (				self:		Union[str, Any],      a_:		str,      a_:		Optional[str] = None		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  self._tokenizer.model.save(a_,      name=a_		)
   return tuple(a_		)









'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# 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.
import re

from ..models.auto import AutoProcessor
from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
from ..utils import is_vision_available
from .base import PipelineTool


if is_vision_available():
    from PIL import Image

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_	:					Tuple					="naver-clova-ix/donut-base-finetuned-docvqa"
 SCREAMING_SNAKE_CASE_	:					Dict					=(
     "This is a tool that answers a question about an document (pdf). It takes an input named `document` which "
     "should be the document containing the information, as well as a `question` that is the question about the "
     "document. It returns a text that contains the answer to the question."
 )
 SCREAMING_SNAKE_CASE_	:					List[str]					="document_qa"
 SCREAMING_SNAKE_CASE_	:					Union[str, Any]					=AutoProcessor
 SCREAMING_SNAKE_CASE_	:					Union[str, Any]					=VisionEncoderDecoderModel

 SCREAMING_SNAKE_CASE_	:					List[Any]					=["image", "text"]
 SCREAMING_SNAKE_CASE_	:					Any					=["text"]






 def __init__(       self       :							Optional[int]							,	*__A       :							List[str]							,	**__A       :							List[Any]	):
        if not is_vision_available():
               raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.'	)

        super().__init__(*__A							,	**__A	)






 def        _lowerCamelCase					(       self       :							Any							,	__A       :							"Image"							,	__A       :							str	):
        __UpperCamelCase       =  '<s_docvqa><s_question>{user_input}</s_question><s_answer>'
        __UpperCamelCase       =  task_prompt.replace('{user_input}'							,	__A	)
        __UpperCamelCase       =  self.pre_processor.tokenizer(
            __A							,	add_special_tokens=__A							,	return_tensors='pt'	).input_ids
        __UpperCamelCase       =  self.pre_processor(__A							,	return_tensors='pt'	).pixel_values

        return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}






 def        _lowerCamelCase					(       self       :							Union[str, Any]							,	__A       :							Optional[Any]	):
        return self.model.generate(
            inputs['pixel_values'].to(self.device	)							,	decoder_input_ids=inputs['decoder_input_ids'].to(self.device	)							,	max_length=self.model.decoder.config.max_position_embeddings							,	early_stopping=__A							,	pad_token_id=self.pre_processor.tokenizer.pad_token_id							,	eos_token_id=self.pre_processor.tokenizer.eos_token_id							,	use_cache=__A							,	num_beams=1							,	bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]							,	return_dict_in_generate=__A							,	).sequences






 def        _lowerCamelCase					(       self       :							Tuple							,	__A       :							List[Any]	):
        __UpperCamelCase       =  self.pre_processor.batch_decode(__A	)[0]
        __UpperCamelCase       =  sequence.replace(self.pre_processor.tokenizer.eos_token							,	''	)
        __UpperCamelCase       =  sequence.replace(self.pre_processor.tokenizer.pad_token							,	''	)
        __UpperCamelCase       =  re.sub(R'<.*?>'							,	''							,	__A							,	count=1	).strip()  # remove first task start token
        __UpperCamelCase       =  self.pre_processor.tokenajson(__A	)

        return sequence["answer"]
