






"""simple docstring"""





import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

  from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
  _SCREAMING_SNAKE_CASE   :							Optional[Any]          =		False

if is_vision_available():
  from PIL import Image

  from transformers import PixaStructImageProcessor






class 	a		(   unittest.TestCase						):






    def __init__(			self	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple=7			,		__SCREAMING_SNAKE_CASE	:				Any=3			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=18			,		__SCREAMING_SNAKE_CASE	:				Tuple=30			,		__SCREAMING_SNAKE_CASE	:				List[Any]=400			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=None			,		__SCREAMING_SNAKE_CASE	:				str=True			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=True			,		__SCREAMING_SNAKE_CASE	:				int=None			,		)	->						Union[str, Any]:
      lowerCamelCase_       	=		size if size is not None else {'height': 20, 'width': 20}
      lowerCamelCase_       	=		parent
      lowerCamelCase_       	=		batch_size
      lowerCamelCase_       	=		num_channels
      lowerCamelCase_       	=		image_size
      lowerCamelCase_       	=		min_resolution
      lowerCamelCase_       	=		max_resolution
      lowerCamelCase_       	=		size
      lowerCamelCase_       	=		do_normalize
      lowerCamelCase_       	=		do_convert_rgb
      lowerCamelCase_       	=		[512, 1024, 2048, 4096]
      lowerCamelCase_       	=		patch_size if patch_size is not None else {'height': 16, 'width': 16}






    def   UpperCamelCase			(			self	:				str   )	->						Dict:
      return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						Union[str, Any]:
      lowerCamelCase_       	=		'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
      lowerCamelCase_       	=		Image.open(requests.get(__SCREAMING_SNAKE_CASE			,		stream=__SCREAMING_SNAKE_CASE   ).raw   ).convert('RGB'   )
      return raw_image






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11    , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""    , )
@require_torch
@require_vision
class 	a		(   __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	List[str]		=					PixaStructImageProcessor if is_vision_available() else None






    def   UpperCamelCase			(			self	:				Dict   )	->						Tuple:
      lowerCamelCase_       	=		PixaStructImageProcessingTester(self   )






    @property
    def   UpperCamelCase			(			self	:				Any   )	->						Tuple:
      return self.image_processor_tester.prepare_image_processor_dict()






    def   UpperCamelCase			(			self	:				int   )	->						Tuple:
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'do_normalize'   )   )
      self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'do_convert_rgb'   )   )






    def   UpperCamelCase			(			self	:				List[Any]   )	->						List[Any]:
      lowerCamelCase_       	=		self.image_processor_tester.prepare_dummy_image()

      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      lowerCamelCase_       	=		2048

      lowerCamelCase_       	=		image_processor(__SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   )
      self.assertTrue(torch.allclose(inputs.flattened_patches.mean()			,		torch.tensor(0.0_606   )			,		atol=1e-3			,		rtol=1e-3   )   )






    def   UpperCamelCase			(			self	:				List[Any]   )	->						Optional[Any]:
      # Initialize image_processor
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      # create random PIL images
      lowerCamelCase_       	=		prepare_image_inputs(self.image_processor_tester			,		equal_resolution=__SCREAMING_SNAKE_CASE   )
      for image in image_inputs:
        self.assertIsInstance(__SCREAMING_SNAKE_CASE			,		Image.Image   )

      # Test not batched input
      lowerCamelCase_       	=		(
          (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        lowerCamelCase_       	=		image_processor(
            image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(1, max_patch, expected_hidden_dim)			,		)

        # Test batched
        lowerCamelCase_       	=		image_processor(
            __SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,		)






    def   UpperCamelCase			(			self	:				int   )	->						Tuple:
      # Initialize image_processor
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      # create random PIL images
      lowerCamelCase_       	=		prepare_image_inputs(self.image_processor_tester			,		equal_resolution=__SCREAMING_SNAKE_CASE   )
      for image in image_inputs:
        self.assertIsInstance(__SCREAMING_SNAKE_CASE			,		Image.Image   )

      # Test not batched input
      lowerCamelCase_       	=		(
          (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
          * self.image_processor_tester.num_channels
      ) + 2

      lowerCamelCase_       	=		True

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        with self.assertRaises(__SCREAMING_SNAKE_CASE   ):
          lowerCamelCase_       	=		image_processor(
              image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches

        lowerCamelCase_       	=		'Hello'

        lowerCamelCase_       	=		image_processor(
            image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE			,		header_text=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(1, max_patch, expected_hidden_dim)			,		)

        # Test batched
        lowerCamelCase_       	=		image_processor(
            __SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE			,		header_text=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,		)






    def   UpperCamelCase			(			self	:				List[Any]   )	->						str:
      # Initialize image_processor
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      # create random numpy tensors
      lowerCamelCase_       	=		prepare_image_inputs(self.image_processor_tester			,		equal_resolution=__SCREAMING_SNAKE_CASE			,		numpify=__SCREAMING_SNAKE_CASE   )
      for image in image_inputs:
        self.assertIsInstance(__SCREAMING_SNAKE_CASE			,		np.ndarray   )

      lowerCamelCase_       	=		(
          (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        lowerCamelCase_       	=		image_processor(
            image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(1, max_patch, expected_hidden_dim)			,		)

        # Test batched
        lowerCamelCase_       	=		image_processor(
            __SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,		)






    def   UpperCamelCase			(			self	:				List[str]   )	->						Union[str, Any]:
      # Initialize image_processor
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      # create random PyTorch tensors
      lowerCamelCase_       	=		prepare_image_inputs(self.image_processor_tester			,		equal_resolution=__SCREAMING_SNAKE_CASE			,		torchify=__SCREAMING_SNAKE_CASE   )
      for image in image_inputs:
        self.assertIsInstance(__SCREAMING_SNAKE_CASE			,		torch.Tensor   )

      # Test not batched input
      lowerCamelCase_       	=		(
          (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
          * self.image_processor_tester.num_channels
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        lowerCamelCase_       	=		image_processor(
            image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(1, max_patch, expected_hidden_dim)			,		)

        # Test batched
        lowerCamelCase_       	=		image_processor(
            __SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,		)






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11    , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""    , )
@require_torch
@require_vision
class 	a		(   __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	Tuple		=					PixaStructImageProcessor if is_vision_available() else None






    def   UpperCamelCase			(			self	:				str   )	->						str:
      lowerCamelCase_       	=		PixaStructImageProcessingTester(self			,		num_channels=4   )
      lowerCamelCase_       	=		3






    @property
    def   UpperCamelCase			(			self	:				List[str]   )	->						Any:
      return self.image_processor_tester.prepare_image_processor_dict()






    def   UpperCamelCase			(			self	:				Any   )	->						Optional[int]:
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'do_normalize'   )   )
      self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'do_convert_rgb'   )   )






    def   UpperCamelCase			(			self	:				int   )	->						int:
      # Initialize image_processor
      lowerCamelCase_       	=		self.image_processing_class(**self.image_processor_dict   )
      # create random PIL images
      lowerCamelCase_       	=		prepare_image_inputs(self.image_processor_tester			,		equal_resolution=__SCREAMING_SNAKE_CASE   )
      for image in image_inputs:
        self.assertIsInstance(__SCREAMING_SNAKE_CASE			,		Image.Image   )

      # Test not batched input
      lowerCamelCase_       	=		(
          (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
          * (self.image_processor_tester.num_channels - 1)
      ) + 2

      for max_patch in self.image_processor_tester.max_patches:
        # Test not batched input
        lowerCamelCase_       	=		image_processor(
            image_inputs[0]			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(1, max_patch, expected_hidden_dim)			,		)

        # Test batched
        lowerCamelCase_       	=		image_processor(
            __SCREAMING_SNAKE_CASE			,		return_tensors='pt'			,		max_patches=__SCREAMING_SNAKE_CASE   ).flattened_patches
        self.assertEqual(
            encoded_images.shape			,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,		)












"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE   :							List[str]          =		{}

try:
  if not is_sentencepiece_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _SCREAMING_SNAKE_CASE   :							str          =		['''NllbTokenizer''']

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _SCREAMING_SNAKE_CASE   :							Optional[Any]          =		['''NllbTokenizerFast''']


if TYPE_CHECKING:
  try:
    if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_nllb import NllbTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_nllb_fast import NllbTokenizerFast

else:
  import sys

  _SCREAMING_SNAKE_CASE   :							Any          =		_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




