




'''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:
   A									=False

if is_vision_available():
   from PIL import Image

   from transformers import PixaStructImageProcessor


class     _a						(			unittest.TestCase				):
       def __init__(			self		:			Tuple     ,       lowercase		:			Dict     ,       lowercase		:			Optional[Any]=7     ,       lowercase		:			str=3     ,       lowercase		:			Optional[Any]=18     ,       lowercase		:			int=30     ,       lowercase		:			int=400     ,       lowercase		:			Tuple=None     ,       lowercase		:			Optional[int]=True     ,       lowercase		:			Union[str, Any]=True     ,       lowercase		:			List[Any]=None     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	size if size is not None else {'''height''': 20, '''width''': 20}
           UpperCAmelCase     =	parent
           UpperCAmelCase     =	batch_size
           UpperCAmelCase     =	num_channels
           UpperCAmelCase     =	image_size
           UpperCAmelCase     =	min_resolution
           UpperCAmelCase     =	max_resolution
           UpperCAmelCase     =	size
           UpperCAmelCase     =	do_normalize
           UpperCAmelCase     =	do_convert_rgb
           UpperCAmelCase     =	[512, 1_024, 2_048, 4_096]
           UpperCAmelCase     =	patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}







       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
           UpperCAmelCase     =	Image.open(requests.get(lowercase     ,       stream=lowercase       ).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						(			__a							,							unittest.TestCase				):
       __a       :  str            =      PixaStructImageProcessor if is_vision_available() else None
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	PixaStructImageProcessingTester(self       )
       @property
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           self.assertTrue(hasattr(lowercase     ,       '''do_normalize'''       )       )
           self.assertTrue(hasattr(lowercase     ,       '''do_convert_rgb'''       )       )
       def 					A   (			self		:			Tuple       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processor_tester.prepare_dummy_image()

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           UpperCAmelCase     =	2_048

           UpperCAmelCase     =	image_processor(lowercase     ,       return_tensors='''pt'''     ,       max_patches=lowercase       )
           self.assertTrue(torch.allclose(inputs.flattened_patches.mean()     ,       torch.tensor(0.0606       )     ,       atol=1E-3     ,       rtol=1E-3       )       )
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           UpperCAmelCase     =	prepare_image_inputs(self.image_processor_tester     ,       equal_resolution=lowercase       )
           for image in image_inputs:
               self.assertIsInstance(lowercase     ,       Image.Image       )

           # Test not batched input
           UpperCAmelCase     =	(
               (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
               UpperCAmelCase     =	image_processor(
                   image_inputs[0]     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (1, max_patch, expected_hidden_dim)     ,       )

               # Test batched
               UpperCAmelCase     =	image_processor(
                   lowercase     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     ,       )
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           UpperCAmelCase     =	prepare_image_inputs(self.image_processor_tester     ,       equal_resolution=lowercase       )
           for image in image_inputs:
               self.assertIsInstance(lowercase     ,       Image.Image       )

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

           UpperCAmelCase     =	True

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

               UpperCAmelCase     =	'''Hello'''

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

               # Test batched
               UpperCAmelCase     =	image_processor(
                   lowercase     ,       return_tensors='''pt'''     ,       max_patches=lowercase     ,       header_text=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)     ,       )
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           # create random numpy tensors
           UpperCAmelCase     =	prepare_image_inputs(self.image_processor_tester     ,       equal_resolution=lowercase     ,       numpify=lowercase       )
           for image in image_inputs:
               self.assertIsInstance(lowercase     ,       np.ndarray       )

           UpperCAmelCase     =	(
               (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
               UpperCAmelCase     =	image_processor(
                   image_inputs[0]     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (1, max_patch, expected_hidden_dim)     ,       )

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







       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           # create random PyTorch tensors
           UpperCAmelCase     =	prepare_image_inputs(self.image_processor_tester     ,       equal_resolution=lowercase     ,       torchify=lowercase       )
           for image in image_inputs:
               self.assertIsInstance(lowercase     ,       torch.Tensor       )

           # Test not batched input
           UpperCAmelCase     =	(
               (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
               UpperCAmelCase     =	image_processor(
                   image_inputs[0]     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (1, max_patch, expected_hidden_dim)     ,       )

               # Test batched
               UpperCAmelCase     =	image_processor(
                   lowercase     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).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						(			__a							,							unittest.TestCase				):
       __a       :  Tuple            =      PixaStructImageProcessor if is_vision_available() else None
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	PixaStructImageProcessingTester(self     ,       num_channels=4       )
           UpperCAmelCase     =	3
       @property
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           self.assertTrue(hasattr(lowercase     ,       '''do_normalize'''       )       )
           self.assertTrue(hasattr(lowercase     ,       '''do_convert_rgb'''       )       )







       def 					A   (			self		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           UpperCAmelCase     =	prepare_image_inputs(self.image_processor_tester     ,       equal_resolution=lowercase       )
           for image in image_inputs:
               self.assertIsInstance(lowercase     ,       Image.Image       )

           # Test not batched input
           UpperCAmelCase     =	(
               (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
               UpperCAmelCase     =	image_processor(
                   image_inputs[0]     ,       return_tensors='''pt'''     ,       max_patches=lowercase       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape     ,       (1, max_patch, expected_hidden_dim)     ,       )

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










'''simple docstring'''







import math
from typing import Optional

import numpy as np

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


A									=logging.get_logger(__name__)

A									={
    'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json',
    'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json',
}


class     _a						(			__a				):
       __a       :  Union[str, Any]            =      """encodec"""
       def __init__(			self		:			Optional[int]     ,       lowercase		:			Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0]     ,       lowercase		:			str=24_000     ,       lowercase		:			int=1     ,       lowercase		:			int=False     ,       lowercase		:			List[str]=None     ,       lowercase		:			Tuple=None     ,       lowercase		:			int=128     ,       lowercase		:			List[Any]=32     ,       lowercase		:			Optional[int]=1     ,       lowercase		:			Optional[int]=[8, 5, 4, 2]     ,       lowercase		:			Union[str, Any]="weight_norm"     ,       lowercase		:			Optional[int]=7     ,       lowercase		:			Tuple=7     ,       lowercase		:			Tuple=3     ,       lowercase		:			Union[str, Any]=2     ,       lowercase		:			Optional[Any]=True     ,       lowercase		:			Tuple="reflect"     ,       lowercase		:			Any=2     ,       lowercase		:			List[str]=2     ,       lowercase		:			str=1.0     ,       lowercase		:			List[str]=1_024     ,       lowercase		:			Optional[Any]=None     ,       lowercase		:			Any=True     ,       **lowercase		:			Optional[Any]     ,       ):



           '''simple docstring'''

           UpperCAmelCase     =	target_bandwidths
           UpperCAmelCase     =	sampling_rate
           UpperCAmelCase     =	audio_channels
           UpperCAmelCase     =	normalize
           UpperCAmelCase     =	chunk_length_s
           UpperCAmelCase     =	overlap
           UpperCAmelCase     =	hidden_size
           UpperCAmelCase     =	num_filters
           UpperCAmelCase     =	num_residual_layers
           UpperCAmelCase     =	upsampling_ratios
           UpperCAmelCase     =	norm_type
           UpperCAmelCase     =	kernel_size
           UpperCAmelCase     =	last_kernel_size
           UpperCAmelCase     =	residual_kernel_size
           UpperCAmelCase     =	dilation_growth_rate
           UpperCAmelCase     =	use_causal_conv
           UpperCAmelCase     =	pad_mode
           UpperCAmelCase     =	compress
           UpperCAmelCase     =	num_lstm_layers
           UpperCAmelCase     =	trim_right_ratio
           UpperCAmelCase     =	codebook_size
           UpperCAmelCase     =	codebook_dim if codebook_dim is not None else hidden_size
           UpperCAmelCase     =	use_conv_shortcut

           if self.norm_type not in ["weight_norm", "time_group_norm"]:
               raise ValueError(
                   f"self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}"       )

           super().__init__(**lowercase       )
       @property
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           if self.chunk_length_s is None:
               return None
           else:
               return int(self.chunk_length_s * self.sampling_rate       )
       @property
       def 					A   (			self		:			Optional[Any]       ):



           '''simple docstring'''

           if self.chunk_length_s is None or self.overlap is None:
               return None
           else:
               return max(1     ,       int((1.0 - self.overlap) * self.chunk_length       )       )
       @property
       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	np.prod(self.upsampling_ratios       )
           return math.ceil(self.sampling_rate / hop_length       )







       @property
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           return int(1_000 * self.target_bandwidths[-1] // (self.frame_rate * 10)       )




