




# 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    __lowerCAmelCase       (							lowerCAmelCase):
       _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:					str       ,					*_lowerCAmelCase:					Tuple       ,					**_lowerCAmelCase:					List[str]				):
         if not is_vision_available():
           raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool."				)

         super().__init__(*_lowerCAmelCase       ,					**_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					str       ,					_lowerCAmelCase:					"Image"       ,					_lowerCAmelCase:					str				):
         lowercase    :List[str]      	=						"<s_docvqa><s_question>{user_input}</s_question><s_answer>"
         lowercase    :List[Any]      	=						task_prompt.replace("{user_input}"       ,					_lowerCAmelCase				)
         lowercase    :str      	=						self.pre_processor.tokenizer(
             _lowerCAmelCase       ,					add_special_tokens=_lowerCAmelCase       ,					return_tensors="pt"				).input_ids
         lowercase    :Any      	=						self.pre_processor(_lowerCAmelCase       ,					return_tensors="pt"				).pixel_values

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					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=_lowerCAmelCase       ,					pad_token_id=self.pre_processor.tokenizer.pad_token_id       ,					eos_token_id=self.pre_processor.tokenizer.eos_token_id       ,					use_cache=_lowerCAmelCase       ,					num_beams=1       ,					bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]       ,					return_dict_in_generate=_lowerCAmelCase       ,					).sequences






       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]       ,					_lowerCAmelCase:					Tuple				):
         lowercase    :Tuple      	=						self.pre_processor.batch_decode(_lowerCAmelCase				)[0]
         lowercase    :List[Any]      	=						sequence.replace(self.pre_processor.tokenizer.eos_token       ,					""				)
         lowercase    :Tuple      	=						sequence.replace(self.pre_processor.tokenizer.pad_token       ,					""				)
         lowercase    :int      	=						re.sub(r"<.*?>"       ,					""       ,					_lowerCAmelCase       ,					count=1				).strip()  # remove first task start token
         lowercase    :List[Any]      	=						self.pre_processor.tokenajson(_lowerCAmelCase				)

         return sequence["answer"]









from collections.abc import Generator
from math import sin



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) != 32:
    raise ValueError("Input must be of length 32"   )

  lowercase    :Any      	=						B""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

  lowercase    :List[Any]      	=						format(lowerCamelCase,			"08x"   )[-8:]
  lowercase    :Tuple      	=						B""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8"   )
  return little_endian_hex



def       UpperCAmelCase__  (     lowerCamelCase   ):
  lowercase    :Union[str, Any]      	=						B""
  for char in message:
    bit_string += format(lowerCamelCase,			"08b"   ).encode("utf-8"   )
  lowercase    :str      	=						format(len(lowerCamelCase   ),			"064b"   ).encode("utf-8"   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(lowerCamelCase   ) % 512 != 448:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) % 512 != 0:
    raise ValueError("Input must have length that's a multiple of 512"   )

  for pos in range(0,			len(lowerCamelCase   ),			512   ):
    lowercase    :List[str]      	=						bit_string[pos : pos + 512]
    lowercase    :int      	=						[]
    for i in range(0,			512,			32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   ),			2   )   )
    yield block_words



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

  lowercase    :List[str]      	=						format(lowerCamelCase,			"032b"   )
  lowercase    :Optional[Any]      	=						""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(lowerCamelCase,			2   )



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  return (a + b) % 2**32



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )
  if shift < 0:
    raise ValueError("Shift must be non-negative"   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32



def       UpperCAmelCase__  (     lowerCamelCase   ):
  lowercase    :Tuple      	=						preprocess(lowerCamelCase   )

  lowercase    :Tuple      	=						[int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  lowercase    :Optional[Any]      	=						0X6745_2301
  lowercase    :Union[str, Any]      	=						0XEFCD_AB89
  lowercase    :Optional[int]      	=						0X98BA_DCFE
  lowercase    :str      	=						0X1032_5476

  lowercase    :str      	=						[
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(lowerCamelCase   ):
    lowercase    :str      	=						aa
    lowercase    :int      	=						ba
    lowercase    :int      	=						ca
    lowercase    :List[str]      	=						da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        lowercase    :Optional[int]      	=						d ^ (b & (c ^ d))
        lowercase    :Optional[Any]      	=						i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        lowercase    :Any      	=						c ^ (d & (b ^ c))
        lowercase    :Union[str, Any]      	=						(5 * i + 1) % 16
      elif i <= 47:
        lowercase    :Any      	=						b ^ c ^ d
        lowercase    :List[Any]      	=						(3 * i + 5) % 16
      else:
        lowercase    :List[Any]      	=						c ^ (b | not_aa(lowerCamelCase   ))
        lowercase    :Any      	=						(7 * i) % 16
      lowercase    :Dict      	=						(f + a + added_consts[i] + block_words[g]) % 2**32
      lowercase    :Any      	=						d
      lowercase    :str      	=						c
      lowercase    :Union[str, Any]      	=						b
      lowercase    :Union[str, Any]      	=						sum_aa(lowerCamelCase,			left_rotate_aa(lowerCamelCase,			shift_amounts[i]   )   )

    # Add hashed chunk to running total
    lowercase    :Optional[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[str]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :Union[str, Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )

  lowercase    :int      	=						reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()



