

import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType



class     lowercase						(       _UpperCamelCase					):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE												=				["""image_processor""", """tokenizer"""]
 __SCREAMING_SNAKE_CASE												=				"""LayoutLMv2ImageProcessor"""
 __SCREAMING_SNAKE_CASE												=				("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")




 def __init__(self       ,       __a=None       ,       __a=None       ,       **__a ) ->					Union[str, Any]:






  """simple docstring"""





  UpperCAmelCase__							=				None
  if "feature_extractor" in kwargs:
   warnings.warn(
       'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
       ' instead.'       ,       __a       ,       )
   UpperCAmelCase__							=				kwargs.pop('feature_extractor' )

  UpperCAmelCase__							=				image_processor if image_processor is not None else feature_extractor
  if image_processor is None:
   raise ValueError('You need to specify an `image_processor`.' )
  if tokenizer is None:
   raise ValueError('You need to specify a `tokenizer`.' )

  super().__init__(__a       ,       __a )




 def __call__(self       ,       __a       ,       __a = None       ,       __a = None       ,       __a = None       ,       __a = None       ,       __a = True       ,       __a = False       ,       __a = False       ,       __a = None       ,       __a = 0       ,       __a = None       ,       __a = None       ,       __a = None       ,       __a = False       ,       __a = False       ,       __a = False       ,       __a = False       ,       __a = True       ,       __a = None       ,       **__a       ,       ) ->					BatchEncoding:






  """simple docstring"""





  if self.image_processor.apply_ocr and (boxes is not None):
   raise ValueError(
       'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' )

  if self.image_processor.apply_ocr and (word_labels is not None):
   raise ValueError(
       'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' )

  if return_overflowing_tokens is True and return_offsets_mapping is False:
   raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.' )

  # first, apply the image processor
  UpperCAmelCase__							=				self.image_processor(images=__a       ,       return_tensors=__a )

  # second, apply the tokenizer
  if text is not None and self.image_processor.apply_ocr and text_pair is None:
   if isinstance(__a       ,       __a ):
    UpperCAmelCase__							=				[text]  # add batch dimension (as the image processor always adds a batch dimension)
   UpperCAmelCase__							=				features['words']

  UpperCAmelCase__							=				self.tokenizer(
      text=text if text is not None else features['words']       ,       text_pair=text_pair if text_pair is not None else None       ,       boxes=boxes if boxes is not None else features['boxes']       ,       word_labels=__a       ,       add_special_tokens=__a       ,       padding=__a       ,       truncation=__a       ,       max_length=__a       ,       stride=__a       ,       pad_to_multiple_of=__a       ,       return_token_type_ids=__a       ,       return_attention_mask=__a       ,       return_overflowing_tokens=__a       ,       return_special_tokens_mask=__a       ,       return_offsets_mapping=__a       ,       return_length=__a       ,       verbose=__a       ,       return_tensors=__a       ,       **__a       ,       )

  # add pixel values
  UpperCAmelCase__							=				features.pop('pixel_values' )
  if return_overflowing_tokens is True:
   UpperCAmelCase__							=				self.get_overflowing_images(__a       ,       encoded_inputs['overflow_to_sample_mapping'] )
  UpperCAmelCase__							=				images

  return encoded_inputs




 def   UpperCamelCase__							(self       ,       __a       ,       __a ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				[]
  for sample_idx in overflow_to_sample_mapping:
   images_with_overflow.append(images[sample_idx] )

  if len(__a ) != len(__a ):
   raise ValueError(
       'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
       F" {len(__a )} and {len(__a )}" )

  return images_with_overflow




 def   UpperCamelCase__							(self       ,       *__a       ,       **__a ) ->					Tuple:






  """simple docstring"""





  return self.tokenizer.batch_decode(*__a       ,       **__a )




 def   UpperCamelCase__							(self       ,       *__a       ,       **__a ) ->					List[str]:






  """simple docstring"""





  return self.tokenizer.decode(*__a       ,       **__a )




 @property
 def   UpperCamelCase__							(self ) ->					Optional[int]:






  """simple docstring"""





  return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]




 @property
 def   UpperCamelCase__							(self ) ->					Dict:






  """simple docstring"""





  warnings.warn(
      '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'       ,       __a       ,       )
  return self.image_processor_class




 @property
 def   UpperCamelCase__							(self ) ->					Optional[int]:






  """simple docstring"""





  warnings.warn(
      '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'       ,       __a       ,       )
  return self.image_processor






import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_UpperCamelCase			       =			namedtuple('''ExampleNamedTuple''', '''a b c''')



class     lowercase						(       unittest.TestCase					):



 '''simple docstring'''


 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				torch.randn(5       ,       2 )
  UpperCAmelCase__							=				torch.device('cuda' ) if torch.cuda.is_available() else torch.device('cpu' )

  UpperCAmelCase__							=				send_to_device(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.cpu()       ,       __a ) )

  UpperCAmelCase__							=				send_to_device((tensor, [tensor, tensor], 1)       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta[0].cpu()       ,       __a ) )
  self.assertIsInstance(resulta[1]       ,       __a )
  self.assertTrue(torch.equal(resulta[1][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta[1][1].cpu()       ,       __a ) )
  self.assertEqual(resulta[2]       ,       1 )

  UpperCAmelCase__							=				send_to_device({'a': tensor, 'b': [tensor, tensor], 'c': 1}       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )

  UpperCAmelCase__							=				send_to_device(ExampleNamedTuple(a=__a       ,       b=[tensor, tensor]       ,       c=1 )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.a.cpu()       ,       __a ) )
  self.assertIsInstance(resulta.b       ,       __a )
  self.assertTrue(torch.equal(resulta.b[0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta.b[1].cpu()       ,       __a ) )
  self.assertEqual(resulta.c       ,       1 )

  UpperCAmelCase__							=				send_to_device(UserDict({'a': tensor, 'b': [tensor, tensor], 'c': 1} )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  with self.assertRaises(__a ) as cm:
   UpperCAmelCase__							=				recursively_apply(torch.tensor       ,       (torch.tensor(1 ), 1)       ,       error_on_other_type=__a )
  self.assertEqual(
      str(cm.exception )       ,       'Unsupported types (<class \'int\'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.'       ,       )




 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				torch.tensor([1, 2, 3, 4, 5] )
  self.assertEqual(listify(__a )       ,       [1, 2, 3, 4, 5] )

  UpperCAmelCase__							=				torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )
  self.assertEqual(listify(__a )       ,       [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )

  UpperCAmelCase__							=				torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )
  self.assertEqual(
      listify(__a )       ,       [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )




 def   UpperCamelCase__							(self ) ->					int:






  """simple docstring"""





  with patch_environment(aa=1       ,       BB=2 ):
   self.assertEqual(os.environ.get('AA' )       ,       '1' )
   self.assertEqual(os.environ.get('BB' )       ,       '2' )

  self.assertNotIn('AA'       ,       os.environ )
  self.assertNotIn('BB'       ,       os.environ )




 def   UpperCamelCase__							(self ) ->					Dict:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				torch.compile(model.forward       ,       backend='inductor' )
  UpperCAmelCase__							=				torch.randn(4       ,       10 ).cuda()
  UpperCAmelCase__							=				model(__a )




 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(__a       ,       __a )




 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				torch.compile(__a )

  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				torch.compile(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(compiled_model._orig_mod       ,       compiled_model_unwrapped._orig_mod )




 def   UpperCamelCase__							(self ) ->					str:






  """simple docstring"""





  self.assertEqual(find_device([1, 'a', torch.tensor([1, 2, 3] )] )       ,       torch.device('cpu' ) )
  self.assertEqual(find_device({'a': 1, 'b': torch.tensor([1, 2, 3] )} )       ,       torch.device('cpu' ) )
  self.assertIsNone(find_device([1, 'a'] ) )



