


from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
		import PIL

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




def _a (  SCREAMING_SNAKE_CASE__      :  Any       )	->    int:

							'''simple docstring'''






							if isinstance(SCREAMING_SNAKE_CASE__			,				(list, tuple)       ) and isinstance(videos[0]			,				(list, tuple)       ) and is_valid_image(videos[0][0]       ):
														return videos

							elif isinstance(SCREAMING_SNAKE_CASE__			,				(list, tuple)       ) and is_valid_image(videos[0]       ):
														return [videos]

							elif is_valid_image(SCREAMING_SNAKE_CASE__       ):
														return [[videos]]

							raise ValueError(f'''Could not make batched video from {videos}'''       )







class 						lowerCamelCase       (UpperCAmelCase__      ):







							"""simple docstring"""




							UpperCAmelCase_      						=   ['pixel_values']






							def __init__( self     :					List[Any],			_UpperCAmelCase     :					Union[str, Any] = True,			_UpperCAmelCase     :					List[str] = None,			_UpperCAmelCase     :					Tuple = PILImageResampling.BILINEAR,			_UpperCAmelCase     :					Optional[int] = True,			_UpperCAmelCase     :					Any = None,			_UpperCAmelCase     :					int = True,			_UpperCAmelCase     :					Union[str, Any] = 1 / 2_5_5,			_UpperCAmelCase     :					Any = True,			_UpperCAmelCase     :					int = True,			_UpperCAmelCase     :					Dict = None,			_UpperCAmelCase     :					Optional[Any] = None,			**_UpperCAmelCase     :					Dict,			)				->			None:





														"""simple docstring"""
														super().__init__(**_SCREAMING_SNAKE_CASE						)
														SCREAMING_SNAKE_CASE__       :      List[str]     =						size if size is not None else {"""shortest_edge""": 2_5_6}
														SCREAMING_SNAKE_CASE__       :      Dict     =						get_size_dict(_SCREAMING_SNAKE_CASE,			default_to_square=_SCREAMING_SNAKE_CASE						)
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						get_size_dict(_SCREAMING_SNAKE_CASE,			param_name="crop_size"						)

														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						do_resize
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						size
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						do_center_crop
														SCREAMING_SNAKE_CASE__       :      Any     =						crop_size
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						resample
														SCREAMING_SNAKE_CASE__       :      List[str]     =						do_rescale
														SCREAMING_SNAKE_CASE__       :      str     =						rescale_factor
														SCREAMING_SNAKE_CASE__       :      Dict     =						offset
														SCREAMING_SNAKE_CASE__       :      List[str]     =						do_normalize
														SCREAMING_SNAKE_CASE__       :      int     =						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
														SCREAMING_SNAKE_CASE__       :      List[str]     =						image_std if image_std is not None else IMAGENET_STANDARD_STD






							def  A_     ( self     :					Tuple,			_UpperCAmelCase     :					Optional[Any],			_UpperCAmelCase     :					Optional[Any],			_UpperCAmelCase     :					List[str] = PILImageResampling.BILINEAR,			_UpperCAmelCase     :					Optional[int] = None,			**_UpperCAmelCase     :					Optional[Any],			)				->			np.ndarray:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Tuple     =						get_size_dict(_SCREAMING_SNAKE_CASE,			default_to_square=_SCREAMING_SNAKE_CASE						)
														if "shortest_edge" in size:
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						get_resize_output_image_size(_SCREAMING_SNAKE_CASE,			size["shortest_edge"],			default_to_square=_SCREAMING_SNAKE_CASE						)
														elif "height" in size and "width" in size:
																					SCREAMING_SNAKE_CASE__       :      Tuple     =						(size["""height"""], size["""width"""])
														else:
																					raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''						)
														return resize(_SCREAMING_SNAKE_CASE,			size=_SCREAMING_SNAKE_CASE,			resample=_SCREAMING_SNAKE_CASE,			data_format=_SCREAMING_SNAKE_CASE,			**_SCREAMING_SNAKE_CASE						)






							def  A_     ( self     :					List[str],			_UpperCAmelCase     :					Optional[int],			_UpperCAmelCase     :					int,			_UpperCAmelCase     :					List[str] = None,			**_UpperCAmelCase     :					Union[str, Any],			)				->			np.ndarray:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						get_size_dict(_SCREAMING_SNAKE_CASE						)
														if "height" not in size or "width" not in size:
																					raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''						)
														return center_crop(_SCREAMING_SNAKE_CASE,			size=(size["height"], size["width"]),			data_format=_SCREAMING_SNAKE_CASE,			**_SCREAMING_SNAKE_CASE						)






							def  A_     ( self     :					Any,			_UpperCAmelCase     :					Union[str, Any],			_UpperCAmelCase     :					Tuple,			_UpperCAmelCase     :					List[str] = True,			_UpperCAmelCase     :					Dict = None,			**_UpperCAmelCase     :					Any,			)				->			List[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Tuple     =						image.astype(np.floataa						)
														if offset:
																					SCREAMING_SNAKE_CASE__       :      Any     =						image - (scale / 2)
														return rescale(_SCREAMING_SNAKE_CASE,			scale=_SCREAMING_SNAKE_CASE,			data_format=_SCREAMING_SNAKE_CASE,			**_SCREAMING_SNAKE_CASE						)






							def  A_     ( self     :					Optional[int],			_UpperCAmelCase     :					List[Any],			_UpperCAmelCase     :					Optional[int],			_UpperCAmelCase     :					str,			_UpperCAmelCase     :					List[Any] = None,			**_UpperCAmelCase     :					int,			)				->			np.ndarray:





														"""simple docstring"""
														return normalize(_SCREAMING_SNAKE_CASE,			mean=_SCREAMING_SNAKE_CASE,			std=_SCREAMING_SNAKE_CASE,			data_format=_SCREAMING_SNAKE_CASE,			**_SCREAMING_SNAKE_CASE						)






							def  A_     ( self     :					Union[str, Any],			_UpperCAmelCase     :					Optional[Any],			_UpperCAmelCase     :					List[Any] = None,			_UpperCAmelCase     :					Tuple = None,			_UpperCAmelCase     :					List[Any] = None,			_UpperCAmelCase     :					Optional[int] = None,			_UpperCAmelCase     :					int = None,			_UpperCAmelCase     :					str = None,			_UpperCAmelCase     :					Union[str, Any] = None,			_UpperCAmelCase     :					List[Any] = None,			_UpperCAmelCase     :					List[Any] = None,			_UpperCAmelCase     :					Dict = None,			_UpperCAmelCase     :					List[str] = None,			_UpperCAmelCase     :					Optional[int] = ChannelDimension.FIRST,			)				->			np.ndarray:





														"""simple docstring"""




														if do_resize and size is None or resample is None:
																					raise ValueError("Size and resample must be specified if do_resize is True."						)

														if do_center_crop and crop_size is None:
																					raise ValueError("Crop size must be specified if do_center_crop is True."						)

														if do_rescale and rescale_factor is None:
																					raise ValueError("Rescale factor must be specified if do_rescale is True."						)

														if do_normalize and (image_mean is None or image_std is None):
																					raise ValueError("Image mean and std must be specified if do_normalize is True."						)

														if offset and not do_rescale:
																					raise ValueError("For offset, do_rescale must also be set to True."						)

														# All transformations expect numpy arrays.
														SCREAMING_SNAKE_CASE__       :      int     =						to_numpy_array(_SCREAMING_SNAKE_CASE						)

														if do_resize:
																					SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						self.resize(image=_SCREAMING_SNAKE_CASE,			size=_SCREAMING_SNAKE_CASE,			resample=_SCREAMING_SNAKE_CASE						)

														if do_center_crop:
																					SCREAMING_SNAKE_CASE__       :      Optional[int]     =						self.center_crop(_SCREAMING_SNAKE_CASE,			size=_SCREAMING_SNAKE_CASE						)

														if do_rescale:
																					SCREAMING_SNAKE_CASE__       :      int     =						self.rescale(image=_SCREAMING_SNAKE_CASE,			scale=_SCREAMING_SNAKE_CASE,			offset=_SCREAMING_SNAKE_CASE						)

														if do_normalize:
																					SCREAMING_SNAKE_CASE__       :      List[str]     =						self.normalize(image=_SCREAMING_SNAKE_CASE,			mean=_SCREAMING_SNAKE_CASE,			std=_SCREAMING_SNAKE_CASE						)

														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						to_channel_dimension_format(_SCREAMING_SNAKE_CASE,			_SCREAMING_SNAKE_CASE						)
														return image






							def  A_     ( self     :					Optional[Any],			_UpperCAmelCase     :					Any,			_UpperCAmelCase     :					Dict = None,			_UpperCAmelCase     :					Tuple = None,			_UpperCAmelCase     :					Tuple = None,			_UpperCAmelCase     :					Dict = None,			_UpperCAmelCase     :					int = None,			_UpperCAmelCase     :					Optional[int] = None,			_UpperCAmelCase     :					List[str] = None,			_UpperCAmelCase     :					Optional[int] = None,			_UpperCAmelCase     :					Union[str, Any] = None,			_UpperCAmelCase     :					Optional[int] = None,			_UpperCAmelCase     :					Union[str, Any] = None,			_UpperCAmelCase     :					List[Any] = None,			_UpperCAmelCase     :					Any = ChannelDimension.FIRST,			**_UpperCAmelCase     :					str,			)				->			PIL.Image.Image:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Tuple     =						do_resize if do_resize is not None else self.do_resize
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						resample if resample is not None else self.resample
														SCREAMING_SNAKE_CASE__       :      Tuple     =						do_center_crop if do_center_crop is not None else self.do_center_crop
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						do_rescale if do_rescale is not None else self.do_rescale
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						rescale_factor if rescale_factor is not None else self.rescale_factor
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						offset if offset is not None else self.offset
														SCREAMING_SNAKE_CASE__       :      int     =						do_normalize if do_normalize is not None else self.do_normalize
														SCREAMING_SNAKE_CASE__       :      str     =						image_mean if image_mean is not None else self.image_mean
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						image_std if image_std is not None else self.image_std

														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						size if size is not None else self.size
														SCREAMING_SNAKE_CASE__       :      str     =						get_size_dict(_SCREAMING_SNAKE_CASE,			default_to_square=_SCREAMING_SNAKE_CASE						)
														SCREAMING_SNAKE_CASE__       :      List[str]     =						crop_size if crop_size is not None else self.crop_size
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						get_size_dict(_SCREAMING_SNAKE_CASE,			param_name="crop_size"						)

														if not valid_images(_SCREAMING_SNAKE_CASE						):
																					raise ValueError(
																					    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
																					    "torch.Tensor, tf.Tensor or jax.ndarray."						)

														SCREAMING_SNAKE_CASE__       :      Any     =						make_batched(_SCREAMING_SNAKE_CASE						)

														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						[
														    [
														        self._preprocess_image(
														            image=_SCREAMING_SNAKE_CASE,			do_resize=_SCREAMING_SNAKE_CASE,			size=_SCREAMING_SNAKE_CASE,			resample=_SCREAMING_SNAKE_CASE,			do_center_crop=_SCREAMING_SNAKE_CASE,			crop_size=_SCREAMING_SNAKE_CASE,			do_rescale=_SCREAMING_SNAKE_CASE,			rescale_factor=_SCREAMING_SNAKE_CASE,			offset=_SCREAMING_SNAKE_CASE,			do_normalize=_SCREAMING_SNAKE_CASE,			image_mean=_SCREAMING_SNAKE_CASE,			image_std=_SCREAMING_SNAKE_CASE,			data_format=_SCREAMING_SNAKE_CASE,			)
														        for img in video
														    ]
														    for video in videos
														]

														SCREAMING_SNAKE_CASE__       :      Any     =						{"""pixel_values""": videos}
														return BatchFeature(data=_SCREAMING_SNAKE_CASE,			tensor_type=_SCREAMING_SNAKE_CASE						)













import json
import os
from typing import Optional

import numpy as np

from ...feature_extraction_utils import BatchFeature
from ...processing_utils import ProcessorMixin
from ...utils import logging
from ...utils.hub import get_file_from_repo
from ..auto import AutoTokenizer


_lowerCamelCase :    Optional[int]  							= logging.get_logger(__name__)


class 						lowerCamelCase       (__lowerCamelCase      ):







							"""simple docstring"""




							UpperCAmelCase_      						=   "AutoTokenizer"
							UpperCAmelCase_      						=   ["tokenizer"]

							UpperCAmelCase_      						=   {
							    "semantic_prompt": 1,
							    "coarse_prompt": 2,
							    "fine_prompt": 2,
							}






							def __init__( self     :					Union[str, Any],			_UpperCAmelCase     :					Optional[int],			_UpperCAmelCase     :					Union[str, Any]=None						)				->			Union[str, Any]:





														"""simple docstring"""
														super().__init__(_UpperCAmelCase						)

														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						speaker_embeddings






							@classmethod
							def  A_     ( cls     :					Any,			_UpperCAmelCase     :					List[str],			_UpperCAmelCase     :					Dict="speaker_embeddings_path.json",			**_UpperCAmelCase     :					Optional[Any]						)				->			List[Any]:





														"""simple docstring"""

														if speaker_embeddings_dict_path is not None:
																					SCREAMING_SNAKE_CASE__       :      Any     =						get_file_from_repo(
																					    _UpperCAmelCase,			_UpperCAmelCase,			subfolder=kwargs.pop("subfolder",			_UpperCAmelCase						),			cache_dir=kwargs.pop("cache_dir",			_UpperCAmelCase						),			force_download=kwargs.pop("force_download",			_UpperCAmelCase						),			proxies=kwargs.pop("proxies",			_UpperCAmelCase						),			resume_download=kwargs.pop("resume_download",			_UpperCAmelCase						),			local_files_only=kwargs.pop("local_files_only",			_UpperCAmelCase						),			use_auth_token=kwargs.pop("use_auth_token",			_UpperCAmelCase						),			revision=kwargs.pop("revision",			_UpperCAmelCase						),			)
																					if speaker_embeddings_path is None:
																												logger.warning(
																												    F'''`{os.path.join(_UpperCAmelCase,			_UpperCAmelCase						)}` does not exists
                    , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json
                    dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.'''						)
																												SCREAMING_SNAKE_CASE__       :      Dict     =						None
																					else:
																												with open(_UpperCAmelCase						) as speaker_embeddings_json:
																																			SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						json.load(_UpperCAmelCase						)
														else:
																					SCREAMING_SNAKE_CASE__       :      List[Any]     =						None

														SCREAMING_SNAKE_CASE__       :      List[str]     =						AutoTokenizer.from_pretrained(_UpperCAmelCase,			**_UpperCAmelCase						)

														return cls(tokenizer=_UpperCAmelCase,			speaker_embeddings=_UpperCAmelCase						)






							def  A_     ( self     :					str,			_UpperCAmelCase     :					Optional[int],			_UpperCAmelCase     :					List[str]="speaker_embeddings_path.json",			_UpperCAmelCase     :					Optional[Any]="speaker_embeddings",			_UpperCAmelCase     :					bool = False,			**_UpperCAmelCase     :					List[str],			)				->			Union[str, Any]:





														"""simple docstring"""
														if self.speaker_embeddings is not None:
																					os.makedirs(os.path.join(_UpperCAmelCase,			_UpperCAmelCase,			"v2"						),			exist_ok=_UpperCAmelCase						)

																					SCREAMING_SNAKE_CASE__       :      Optional[int]     =						{}

																					SCREAMING_SNAKE_CASE__       :      Any     =						save_directory

																					for prompt_key in self.speaker_embeddings:
																												if prompt_key != "repo_or_path":
																																			SCREAMING_SNAKE_CASE__       :      List[Any]     =						self._load_voice_preset(_UpperCAmelCase						)

																																			SCREAMING_SNAKE_CASE__       :      int     =						{}
																																			for key in self.speaker_embeddings[prompt_key]:
																																										np.save(
																																										    os.path.join(
																																										        embeddings_dict["repo_or_path"],			_UpperCAmelCase,			F'''{prompt_key}_{key}'''						),			voice_preset[key],			allow_pickle=_UpperCAmelCase,			)
																																										SCREAMING_SNAKE_CASE__       :      List[str]     =						os.path.join(_UpperCAmelCase,			F'''{prompt_key}_{key}.npy'''						)

																																			SCREAMING_SNAKE_CASE__       :      Optional[int]     =						tmp_dict

																					with open(os.path.join(_UpperCAmelCase,			_UpperCAmelCase						),			"w"						) as fp:
																												json.dump(_UpperCAmelCase,			_UpperCAmelCase						)

														super().save_pretrained(_UpperCAmelCase,			_UpperCAmelCase,			**_UpperCAmelCase						)






							def  A_     ( self     :					List[Any],			_UpperCAmelCase     :					str = None,			**_UpperCAmelCase     :					List[Any]						)				->			List[str]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      str     =						self.speaker_embeddings[voice_preset]

														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						{}
														for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
																					if key not in voice_preset_paths:
																												raise ValueError(
																												    F'''Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].'''						)

																					SCREAMING_SNAKE_CASE__       :      List[Any]     =						get_file_from_repo(
																					    self.speaker_embeddings.get("repo_or_path",			"/"						),			voice_preset_paths[key],			subfolder=kwargs.pop("subfolder",			_UpperCAmelCase						),			cache_dir=kwargs.pop("cache_dir",			_UpperCAmelCase						),			force_download=kwargs.pop("force_download",			_UpperCAmelCase						),			proxies=kwargs.pop("proxies",			_UpperCAmelCase						),			resume_download=kwargs.pop("resume_download",			_UpperCAmelCase						),			local_files_only=kwargs.pop("local_files_only",			_UpperCAmelCase						),			use_auth_token=kwargs.pop("use_auth_token",			_UpperCAmelCase						),			revision=kwargs.pop("revision",			_UpperCAmelCase						),			)
																					if path is None:
																												raise ValueError(
																												    F'''`{os.path.join(self.speaker_embeddings.get("repo_or_path",			"/"						),			voice_preset_paths[key]						)}` does not exists
                    , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}
                    embeddings.'''						)

																					SCREAMING_SNAKE_CASE__       :      int     =						np.load(_UpperCAmelCase						)

														return voice_preset_dict






							def  A_     ( self     :					int,			_UpperCAmelCase     :					Optional[dict] = None						)				->			Optional[int]:





														"""simple docstring"""
														for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
																					if key not in voice_preset:
																												raise ValueError(F'''Voice preset unrecognized, missing {key} as a key.'''						)

																					if not isinstance(voice_preset[key],			np.ndarray						):
																												raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key]						)}D ndarray.'''						)

																					if len(voice_preset[key].shape						) != self.preset_shape[key]:
																												raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key]						)}D ndarray.'''						)






							def __call__( self     :					List[Any],			_UpperCAmelCase     :					Optional[Any]=None,			_UpperCAmelCase     :					Union[str, Any]=None,			_UpperCAmelCase     :					Optional[int]="pt",			_UpperCAmelCase     :					List[str]=2_5_6,			_UpperCAmelCase     :					int=False,			_UpperCAmelCase     :					Optional[int]=True,			_UpperCAmelCase     :					Any=False,			**_UpperCAmelCase     :					List[str],			)				->			List[Any]:





														"""simple docstring"""
														if voice_preset is not None and not isinstance(_UpperCAmelCase,			_UpperCAmelCase						):
																					if (
																					    isinstance(_UpperCAmelCase,			_UpperCAmelCase						)
																					    and self.speaker_embeddings is not None
																					    and voice_preset in self.speaker_embeddings
																					):
																												SCREAMING_SNAKE_CASE__       :      List[str]     =						self._load_voice_preset(_UpperCAmelCase						)

																					else:
																												if isinstance(_UpperCAmelCase,			_UpperCAmelCase						) and not voice_preset.endswith(".npz"						):
																																			SCREAMING_SNAKE_CASE__       :      Optional[int]     =						voice_preset + ".npz"

																												SCREAMING_SNAKE_CASE__       :      List[str]     =						np.load(_UpperCAmelCase						)

														if voice_preset is not None:
																					self._validate_voice_preset_dict(_UpperCAmelCase,			**_UpperCAmelCase						)
																					SCREAMING_SNAKE_CASE__       :      Any     =						BatchFeature(data=_UpperCAmelCase,			tensor_type=_UpperCAmelCase						)

														SCREAMING_SNAKE_CASE__       :      Dict     =						self.tokenizer(
														    _UpperCAmelCase,			return_tensors=_UpperCAmelCase,			padding="max_length",			max_length=_UpperCAmelCase,			return_attention_mask=_UpperCAmelCase,			return_token_type_ids=_UpperCAmelCase,			add_special_tokens=_UpperCAmelCase,			**_UpperCAmelCase,			)

														if voice_preset is not None:
																					SCREAMING_SNAKE_CASE__       :      str     =						voice_preset

														return encoded_text






