






from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
			from .deepspeed import (
			    DeepSpeedEngineWrapper,
			    DeepSpeedOptimizerWrapper,
			    DeepSpeedSchedulerWrapper,
			    DummyOptim,
			    DummyScheduler,
			    HfDeepSpeedConfig,
			)

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers


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 _UpperCamelCase							:
						'''simple docstring'''







						@staticmethod
						def 							__UpperCamelCase (			*a							: Any      ,      **a							: Optional[int]	)							->       Optional[Any]:

							"""simple docstring"""

							pass

			def  lowerCamelCase__ (					_a):
				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.
a_						     =    (
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)






@is_pipeline_test
@require_torch
@require_vision
class _UpperCamelCase							(							unittest.TestCase   ):
			'''simple docstring'''







			lowerCamelCase__           =MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
			@require_pytesseract
			@require_vision
			def 							__UpperCamelCase (			self							: Tuple      ,      a							: Union[str, Any]      ,      a							: Any      ,      a							: Optional[Any]	)							->       List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      int				     =       pipeline(
				    "document-question-answering"      ,      model=a      ,      tokenizer=a      ,      image_processor=a	)

				SCREAMING_SNAKE_CASE   :      Dict				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      int				     =       list(zip(*apply_tesseract(load_image(a	)      ,      a      ,      ""	)	)	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       "What is the placebo?"
				SCREAMING_SNAKE_CASE   :      List[str]				     =       [
				    {
				        "image": load_image(a	),
				        "question": question,
				    },
				    {
				        "image": image,
				        "question": question,
				    },
				    {
				        "image": image,
				        "question": question,
				        "word_boxes": word_boxes,
				    },
				]
				return dqa_pipeline, examples
			def 							__UpperCamelCase (			self							: List[str]      ,      a							: List[Any]      ,      a							: Any	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       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 							__UpperCamelCase (			self							: Optional[int]	)							->       Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       pipeline("document-question-answering"      ,      model="hf-internal-testing/tiny-random-layoutlmv2"	)
				SCREAMING_SNAKE_CASE   :      int				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      int				     =       "How many cats are there?"

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       [
				    {"score": 0.0001, "answer": "oy 2312/2019", "start": 38, "end": 39},
				    {"score": 0.0001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
				]
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       dqa_pipeline(image=a      ,      question=a      ,      top_k=2	)
				self.assertEqual(nested_simplify(a      ,      decimals=4	)      ,      a	)

				SCREAMING_SNAKE_CASE   :      Any				     =       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
				SCREAMING_SNAKE_CASE   :      Tuple				     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
				SCREAMING_SNAKE_CASE   :      str				     =       dqa_pipeline(image=a      ,      question=a      ,      top_k=2	)
				self.assertEqual(a      ,      []	)

				# We can optionnally pass directly the words and bounding boxes
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       []
				SCREAMING_SNAKE_CASE   :      int				     =       []
				SCREAMING_SNAKE_CASE   :      str				     =       dqa_pipeline(image=a      ,      question=a      ,      words=a      ,      boxes=a      ,      top_k=2	)
				self.assertEqual(a      ,      []	)
			@slow
			@require_torch
			@require_detectrona
			@require_pytesseract
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       pipeline(
				    "document-question-answering"      ,      model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"      ,      revision="9977165"      ,      )
				SCREAMING_SNAKE_CASE   :      Any				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      Any				     =       "What is the invoice number?"

				SCREAMING_SNAKE_CASE   :      Dict				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Any				     =       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 							__UpperCamelCase (			self							: Tuple	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       pipeline(
				    "document-question-answering"      ,      model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"      ,      revision="9977165"      ,      max_seq_len=50      ,      )
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      int				     =       "What is the invoice number?"

				SCREAMING_SNAKE_CASE   :      Any				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Tuple				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       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 							__UpperCamelCase (			self							: Union[str, Any]	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       AutoTokenizer.from_pretrained(
				    "impira/layoutlm-document-qa"      ,      revision="3dc6de3"      ,      add_prefix_space=a	)
				SCREAMING_SNAKE_CASE   :      List[str]				     =       pipeline(
				    "document-question-answering"      ,      model="impira/layoutlm-document-qa"      ,      tokenizer=a      ,      revision="3dc6de3"      ,      )
				SCREAMING_SNAKE_CASE   :      List[str]				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      int				     =       "What is the invoice number?"

				SCREAMING_SNAKE_CASE   :      str				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      Dict				     =       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      ,      )

				SCREAMING_SNAKE_CASE   :      int				     =       list(zip(*apply_tesseract(load_image(a	)      ,      a      ,      ""	)	)	)

				# This model should also work if `image` is set to None
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       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 							__UpperCamelCase (			self							: Tuple	)							->       List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      int				     =       AutoTokenizer.from_pretrained(
				    "impira/layoutlm-document-qa"      ,      revision="3dc6de3"      ,      add_prefix_space=a	)
				SCREAMING_SNAKE_CASE   :      Dict				     =       pipeline(
				    "document-question-answering"      ,      model="impira/layoutlm-document-qa"      ,      tokenizer=a      ,      revision="3dc6de3"      ,      max_seq_len=50      ,      )
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       "What is the invoice number?"

				SCREAMING_SNAKE_CASE   :      Dict				     =       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},
				    ]      ,      )

				SCREAMING_SNAKE_CASE   :      int				     =       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      ,      )

				SCREAMING_SNAKE_CASE   :      int				     =       list(zip(*apply_tesseract(load_image(a	)      ,      a      ,      ""	)	)	)

				# This model should also work if `image` is set to None
				SCREAMING_SNAKE_CASE   :      Any				     =       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 							__UpperCamelCase (			self							: str	)							->       int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[str]				     =       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"      ,      )

				SCREAMING_SNAKE_CASE   :      int				     =       INVOICE_URL
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       "What is the invoice number?"
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       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 							__UpperCamelCase (			self							: List[str]	)							->       int:

				"""simple docstring"""

				pass