
"""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 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE  ):
     A__      =			"""naver-clova-ix/donut-base-finetuned-docvqa"""
     A__      =			(
         """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."""
     )
     A__      =			"""document_qa"""
     A__      =			AutoProcessor
     A__      =			VisionEncoderDecoderModel

     A__      =			["""image""", """text"""]
     A__      =			["""text"""]
     def __init__(     self  ,     *snake_case__  ,     **snake_case__				):




       """simple docstring"""


       if not is_vision_available():
         raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool."				)

       super().__init__(*snake_case__  ,     **snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = "<s_docvqa><s_question>{user_input}</s_question><s_answer>"
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = task_prompt.replace("{user_input}"  ,     snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = self.pre_processor.tokenizer(
           snake_case__  ,     add_special_tokens=snake_case__  ,     return_tensors="pt"				).input_ids
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.pre_processor(snake_case__  ,     return_tensors="pt"				).pixel_values

       return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       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=snake_case__  ,     pad_token_id=self.pre_processor.tokenizer.pad_token_id  ,     eos_token_id=self.pre_processor.tokenizer.eos_token_id  ,     use_cache=snake_case__  ,     num_beams=1  ,     bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]  ,     return_dict_in_generate=snake_case__  ,     ).sequences




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				int							    = self.pre_processor.batch_decode(snake_case__				)[0]
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = sequence.replace(self.pre_processor.tokenizer.eos_token  ,     ""				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = sequence.replace(self.pre_processor.tokenizer.pad_token  ,     ""				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = re.sub(r"<.*?>"  ,     ""  ,     snake_case__  ,     count=1				).strip()  # remove first task start token
       _SCREAMING_SNAKE_CASE   :				Dict							    = self.pre_processor.tokenajson(snake_case__				)

       return sequence["answer"]





"""simple docstring"""
import unittest

from datasets import load_dataset

from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE      ,       unittest.TestCase  ):
     A__      =			None
     A__      =			BloomTokenizerFast
     A__      =			BloomTokenizerFast
     A__      =			True
     A__      =			False
     A__      =			"""tokenizer_file"""
     A__      =			{"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""}
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       super().setUp()
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = BloomTokenizerFast.from_pretrained("bigscience/tokenizer"				)
       tokenizer.save_pretrained(self.tmpdirname				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     **snake_case__				):




       """simple docstring"""


       kwargs.update(self.special_tokens_map				)
       return BloomTokenizerFast.from_pretrained(self.tmpdirname  ,     **snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				int							    = self.get_rust_tokenizer()

       _SCREAMING_SNAKE_CASE   :				Tuple							    = ["The quick brown fox</s>", "jumps over the lazy dog</s>"]
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = [[2175, 23714, 73173, 144252, 2], [77, 132619, 3478, 368, 109586, 35433, 2]]

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = tokenizer.batch_encode_plus(snake_case__				)["input_ids"]
       self.assertListEqual(snake_case__  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Tuple							    = tokenizer.batch_decode(snake_case__				)
       self.assertListEqual(snake_case__  ,     snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__=6				):




       """simple docstring"""


       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''				):
           _SCREAMING_SNAKE_CASE   :				Tuple							    = self.rust_tokenizer_class.from_pretrained(snake_case__  ,     **snake_case__				)
           # tokenizer_r.pad_token = None # Hotfixing padding = None
           # Simple input
           _SCREAMING_SNAKE_CASE   :				str							    = "This is a simple input"
           _SCREAMING_SNAKE_CASE   :				Tuple							    = ["This is a simple input 1", "This is a simple input 2"]
           _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = ("This is a simple input", "This is a pair")
           _SCREAMING_SNAKE_CASE   :				List[str]							    = [
               ("This is a simple input 1", "This is a simple input 2"),
               ("This is a simple pair 1", "This is a simple pair 2"),
           ]

           # Simple input tests
           try:
             tokenizer_r.encode(snake_case__  ,     max_length=snake_case__				)
             tokenizer_r.encode_plus(snake_case__  ,     max_length=snake_case__				)

             tokenizer_r.batch_encode_plus(snake_case__  ,     max_length=snake_case__				)
             tokenizer_r.encode(snake_case__  ,     max_length=snake_case__				)
             tokenizer_r.batch_encode_plus(snake_case__  ,     max_length=snake_case__				)
           except ValueError:
             self.fail("Bloom Tokenizer should be able to deal with padding"				)

           _SCREAMING_SNAKE_CASE   :				Tuple							    = None  # Hotfixing padding = None
           self.assertRaises(snake_case__  ,     tokenizer_r.encode  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"				)

           # Simple input
           self.assertRaises(snake_case__  ,     tokenizer_r.encode_plus  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"				)

           # Simple input
           self.assertRaises(
               snake_case__  ,     tokenizer_r.batch_encode_plus  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"  ,     )

           # Pair input
           self.assertRaises(snake_case__  ,     tokenizer_r.encode  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"				)

           # Pair input
           self.assertRaises(snake_case__  ,     tokenizer_r.encode_plus  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"				)

           # Pair input
           self.assertRaises(
               snake_case__  ,     tokenizer_r.batch_encode_plus  ,     snake_case__  ,     max_length=snake_case__  ,     padding="max_length"  ,     )
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.get_rust_tokenizer()
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = load_dataset("xnli"  ,     "all_languages"  ,     split="test"  ,     streaming=snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Tuple							    = next(iter(snake_case__				)				)["premise"]  # pick up one data
       _SCREAMING_SNAKE_CASE   :				int							    = list(sample_data.values()				)

       _SCREAMING_SNAKE_CASE   :				List[str]							    = list(map(tokenizer.encode  ,     snake_case__				)				)
       _SCREAMING_SNAKE_CASE   :				int							    = [tokenizer.decode(snake_case__  ,     clean_up_tokenization_spaces=snake_case__				) for x in output_tokens]
       self.assertListEqual(snake_case__  ,     snake_case__				)




     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map				)  ,     1				)
       self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()				)[0]				)  ,     1				)



