




import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image

 from transformers.image_utils import load_image
else:







 class     A:



  '''simple docstring'''


  @staticmethod
  def 							a__					(							*A_   :    int		,				**A_   :    int    )  ->      Any:

        """simple docstring"""






        pass

 def      _SCREAMING_SNAKE_CASE     (				lowercase      :			List[str]	):


       '''simple docstring'''



       return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
lowerCamelCase							:						List[str]					       =  (
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)







@is_pipeline_test
@require_torch
@require_vision
class     A(		unittest.TestCase  ):



 '''simple docstring'''


 UpperCamelCase		  =		MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING

 @require_pytesseract
 @require_vision
 def 							a__					(							self   :    Optional[Any]		,				A_   :    Optional[Any]		,				A_   :    List[str]		,				A_   :    int    )  ->      int:

       """simple docstring"""






       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model=A_		,				tokenizer=A_		,				image_processor=A_    )

       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       list(zip(*apply_tesseract(load_image(A_    )		,				A_		,				''    )    )    )
       lowerCamelCase_							=       'What is the placebo?'
       lowerCamelCase_							=       [
           {
               'image': load_image(A_    ),
               'question': question,
           },
           {
               'image': image,
               'question': question,
           },
           {
               'image': image,
               'question': question,
               'word_boxes': word_boxes,
           },
       ]
       return dqa_pipeline, examples

 def 							a__					(							self   :    Any		,				A_   :    Dict		,				A_   :    List[Any]    )  ->      List[Any]:

       """simple docstring"""






       lowerCamelCase_							=       dqa_pipeline(A_		,				top_k=2    )
       self.assertEqual(
           A_		,				[
               [
                   {'score': ANY(A_    ), 'answer': ANY(A_    ), 'start': ANY(A_    ), 'end': ANY(A_    )},
                   {'score': ANY(A_    ), 'answer': ANY(A_    ), 'start': ANY(A_    ), 'end': ANY(A_    )},
               ]
           ]
           * 3		,				)

 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							a__					(							self   :    str    )  ->      List[Any]:

       """simple docstring"""






       lowerCamelCase_							=       pipeline('document-question-answering'		,				model='hf-internal-testing/tiny-random-layoutlmv2'    )
       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'How many cats are there?'

       lowerCamelCase_							=       [
           {'score': 0.0001, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
           {'score': 0.0001, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
       ]
       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(nested_simplify(A_		,				decimals=4    )		,				A_    )

       lowerCamelCase_							=       dqa_pipeline({'image': image, 'question': question}		,				top_k=2    )
       self.assertEqual(nested_simplify(A_		,				decimals=4    )		,				A_    )

       # This image does not detect ANY text in it, meaning layoutlmv2 should fail.
       # Empty answer probably
       lowerCamelCase_							=       './tests/fixtures/tests_samples/COCO/000000039769.png'
       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(A_		,				[]    )

       # We can optionnally pass directly the words and bounding boxes
       lowerCamelCase_							=       './tests/fixtures/tests_samples/COCO/000000039769.png'
       lowerCamelCase_							=       []
       lowerCamelCase_							=       []
       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				words=A_		,				boxes=A_		,				top_k=2    )
       self.assertEqual(A_		,				[]    )

 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							a__					(							self   :    List[str]    )  ->      Optional[Any]:

       """simple docstring"""






       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,				revision='9977165'		,				)
       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'What is the invoice number?'

       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline({'image': image, 'question': question}		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline(
           [{'image': image, 'question': question}, {'image': image, 'question': question}]		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               [
                   {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
                   {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
               ],
           ]
           * 2		,				)

 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 							a__					(							self   :    int    )  ->      str:

       """simple docstring"""






       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,				revision='9977165'		,				max_seq_len=50		,				)
       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'What is the invoice number?'

       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
               {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline({'image': image, 'question': question}		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
               {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline(
           [{'image': image, 'question': question}, {'image': image, 'question': question}]		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               [
                   {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
                   {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
               ]
           ]
           * 2		,				)

 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 							a__					(							self   :    List[str]    )  ->      Optional[int]:

       """simple docstring"""






       lowerCamelCase_							=       AutoTokenizer.from_pretrained(
           'impira/layoutlm-document-qa'		,				revision='3dc6de3'		,				add_prefix_space=A_    )
       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model='impira/layoutlm-document-qa'		,				tokenizer=A_		,				revision='3dc6de3'		,				)
       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'What is the invoice number?'

       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline({'image': image, 'question': question}		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline(
           [{'image': image, 'question': question}, {'image': image, 'question': question}]		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               [
                   {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
                   {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
               ]
           ]
           * 2		,				)

       lowerCamelCase_							=       list(zip(*apply_tesseract(load_image(A_    )		,				A_		,				''    )    )    )

       # This model should also work if `image` is set to None
       lowerCamelCase_							=       dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
           ]		,				)

 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 							a__					(							self   :    List[Any]    )  ->      List[Any]:

       """simple docstring"""






       lowerCamelCase_							=       AutoTokenizer.from_pretrained(
           'impira/layoutlm-document-qa'		,				revision='3dc6de3'		,				add_prefix_space=A_    )
       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model='impira/layoutlm-document-qa'		,				tokenizer=A_		,				revision='3dc6de3'		,				max_seq_len=50		,				)
       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'What is the invoice number?'

       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

       lowerCamelCase_							=       dqa_pipeline(
           [{'image': image, 'question': question}, {'image': image, 'question': question}]		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               [
                   {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
                   {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
               ]
           ]
           * 2		,				)

       lowerCamelCase_							=       list(zip(*apply_tesseract(load_image(A_    )		,				A_		,				''    )    )    )

       # This model should also work if `image` is set to None
       lowerCamelCase_							=       dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,				top_k=2    )
       self.assertEqual(
           nested_simplify(A_		,				decimals=4    )		,				[
               {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
               {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
           ]		,				)

 @slow
 @require_torch
 def 							a__					(							self   :    Tuple    )  ->      List[Any]:

       """simple docstring"""






       lowerCamelCase_							=       pipeline(
           'document-question-answering'		,				model='naver-clova-ix/donut-base-finetuned-docvqa'		,				tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa'    )		,				feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa'		,				)

       lowerCamelCase_							=       INVOICE_URL
       lowerCamelCase_							=       'What is the invoice number?'
       lowerCamelCase_							=       dqa_pipeline(image=A_		,				question=A_		,				top_k=2    )
       self.assertEqual(nested_simplify(A_		,				decimals=4    )		,				[{'answer': 'us-001'}]    )





 @require_tf
 @unittest.skip('Document question answering not implemented in TF'    )
 def 							a__					(							self   :    Dict    )  ->      List[Any]:

       """simple docstring"""






       pass









'''simple docstring'''







from typing import List, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase      :   Optional[Any]      =       logging.get_logger(__name__)

lowercase      :   Any      =       {
    """huggingface/autoformer-tourism-monthly""": """https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json""",
}







class 					_a (a__	):





     '''simple docstring'''



     lowerCAmelCase_  :     List[str]          =					"""autoformer"""
     lowerCAmelCase_  :     int          =					{
         """hidden_size""": """d_model""",
         """num_attention_heads""": """encoder_attention_heads""",
         """num_hidden_layers""": """encoder_layers""",
     }







     def __init__(				self							,__a = None							,__a = None							,__a = "student_t"							,__a = "nll"							,__a = 1							,__a = [1, 2, 3, 4, 5, 6, 7]							,__a = True							,__a = 0							,__a = 0							,__a = 0							,__a = 0							,__a = None							,__a = None							,__a = 64							,__a = 2							,__a = 2							,__a = 2							,__a = 2							,__a = 32							,__a = 32							,__a = "gelu"							,__a = 0.1							,__a = 0.1							,__a = 0.1							,__a = 0.1							,__a = 0.1							,__a = 100							,__a = 0.02							,__a = True							,__a=True							,__a = 10							,__a = 25							,__a = 3							,**__a							,)      ->				Union[str, Any]:
          # time series specific configuration
          snake_case			:      List[str]        =			prediction_length
          snake_case			:      str        =			context_length if context_length is not None else prediction_length
          snake_case			:      List[Any]        =			distribution_output
          snake_case			:      Any        =			loss
          snake_case			:      Union[str, Any]        =			input_size
          snake_case			:      Optional[int]        =			num_time_features
          snake_case			:      Union[str, Any]        =			lags_sequence
          snake_case			:      Any        =			scaling
          snake_case			:      str        =			num_dynamic_real_features
          snake_case			:      Union[str, Any]        =			num_static_real_features
          snake_case			:      Optional[int]        =			num_static_categorical_features
          if cardinality is not None and num_static_categorical_features > 0:
               if len(__a							) != num_static_categorical_features:
                    raise ValueError(
                        """The cardinality should be a list of the same length as `num_static_categorical_features`"""							)
               snake_case			:      int        =			cardinality
          else:
               snake_case			:      Optional[Any]        =			[0]
          if embedding_dimension is not None and num_static_categorical_features > 0:
               if len(__a							) != num_static_categorical_features:
                    raise ValueError(
                        """The embedding dimension should be a list of the same length as `num_static_categorical_features`"""							)
               snake_case			:      int        =			embedding_dimension
          else:
               snake_case			:      List[str]        =			[min(50							,(cat + 1) // 2							) for cat in self.cardinality]
          snake_case			:      Optional[int]        =			num_parallel_samples

          # Transformer architecture configuration
          snake_case			:      Any        =			input_size * len(self.lags_sequence							) + self._number_of_features
          snake_case			:      Union[str, Any]        =			d_model
          snake_case			:      Any        =			encoder_attention_heads
          snake_case			:      Union[str, Any]        =			decoder_attention_heads
          snake_case			:      Optional[Any]        =			encoder_ffn_dim
          snake_case			:      Any        =			decoder_ffn_dim
          snake_case			:      List[Any]        =			encoder_layers
          snake_case			:      List[str]        =			decoder_layers

          snake_case			:      str        =			dropout
          snake_case			:      Union[str, Any]        =			attention_dropout
          snake_case			:      Optional[Any]        =			activation_dropout
          snake_case			:      Tuple        =			encoder_layerdrop
          snake_case			:      Any        =			decoder_layerdrop

          snake_case			:      Any        =			activation_function
          snake_case			:      int        =			init_std

          snake_case			:      Optional[Any]        =			use_cache

          # Autoformer
          snake_case			:      int        =			label_length
          snake_case			:      str        =			moving_average
          snake_case			:      Tuple        =			autocorrelation_factor

          super().__init__(is_encoder_decoder=__a							,**__a							)







     @property
     def 			snake_case_      (				self							)      ->				int:
          return (
              sum(self.embedding_dimension							)
              + self.num_dynamic_real_features
              + self.num_time_features
              + self.num_static_real_features
              + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
          )



