



"""simple docstring"""
import unittest

import numpy as np

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


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import TvltImageProcessor
def   A_    (     _lowercase,   _lowercase=10,   _lowercase=10,   _lowercase=False,   _lowercase=False      ):







						'''simple docstring'''


						snake_case_					:List[Any]		=     []
						for i in range(image_processor_tester.num_frames      ):
												video.append(np.random.randint(255,   size=(image_processor_tester.num_channels, width, height),   dtype=np.uinta      )      )

						if not numpify and not torchify:
												# PIL expects the channel dimension as last dimension
												snake_case_					:Dict		=     [Image.fromarray(np.moveaxis(_lowercase,   0,   -1      )      ) for frame in video]

						if torchify:
												snake_case_					:List[Any]		=     [torch.from_numpy(_lowercase      ) for frame in video]

						return video
def   A_    (     _lowercase,   _lowercase=False,   _lowercase=False,   _lowercase=False      ):







						'''simple docstring'''


						assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

						snake_case_					:Tuple		=     []
						for i in range(image_processor_tester.batch_size      ):
												if equal_resolution:
																		snake_case_					:Dict		=     image_processor_tester.max_resolution
												else:
																		snake_case_					:str		=     np.random.choice(
																		    np.arange(image_processor_tester.min_resolution,   image_processor_tester.max_resolution      ),   2      )
																		snake_case_					:List[str]		=     prepare_video(
																		    image_processor_tester=_lowercase,   width=_lowercase,   height=_lowercase,   numpify=_lowercase,   torchify=_lowercase,   )
												video_inputs.append(_lowercase      )

						return video_inputs
class 							lowerCamelCase    (     unittest.TestCase							):






					'''simple docstring'''





					def __init__(			self:				Tuple		,	snake_case:				Dict		,	snake_case:				Tuple=7		,	snake_case:				List[Any]=3		,	snake_case:				Optional[int]=4		,	snake_case:				Optional[Any]=18		,	snake_case:				Optional[Any]=30		,	snake_case:				Dict=400		,	snake_case:				List[str]=True		,	snake_case:				Optional[int]=None		,	snake_case:				str=True		,	snake_case:				List[Any]=[0.5, 0.5, 0.5]		,	snake_case:				Optional[Any]=[0.5, 0.5, 0.5]		,	snake_case:				List[Any]=True		,	snake_case:				Union[str, Any]=None		,	)  ->      List[Any]:
											snake_case_					:Union[str, Any]		=     size if size is not None else {"shortest_edge": 18}
											snake_case_					:Dict		=     crop_size if crop_size is not None else {"height": 18, "width": 18}

											snake_case_					:str		=     parent
											snake_case_					:Dict		=     batch_size
											snake_case_					:Tuple		=     num_channels
											snake_case_					:Optional[Any]		=     num_frames
											snake_case_					:Optional[int]		=     image_size
											snake_case_					:Union[str, Any]		=     min_resolution
											snake_case_					:Optional[Any]		=     max_resolution
											snake_case_					:Tuple		=     do_resize
											snake_case_					:List[Any]		=     size
											snake_case_					:Optional[Any]		=     do_normalize
											snake_case_					:Dict		=     image_mean
											snake_case_					:List[Any]		=     image_std
											snake_case_					:Tuple		=     do_center_crop
											snake_case_					:Tuple		=     crop_size






					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      Union[str, Any]:
											return {
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_normalize": self.do_normalize,
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											}

@require_torch
@require_vision
class 							lowerCamelCase    (     a__       ,		unittest.TestCase							):






					'''simple docstring'''





					_A						:     List[Any]		=	TvltImageProcessor if is_vision_available() else None






					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      Dict:
											snake_case_					:str		=     TvltImageProcessorTester(self		)






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






					def   lowerCAmelCase_							(			self:				str		)  ->      str:
											snake_case_					:Any		=     self.image_processing_class(**self.image_processor_dict		)
											self.assertTrue(hasattr(__A		,	"""image_mean"""		)		)
											self.assertTrue(hasattr(__A		,	"""image_std"""		)		)
											self.assertTrue(hasattr(__A		,	"""do_normalize"""		)		)
											self.assertTrue(hasattr(__A		,	"""do_resize"""		)		)
											self.assertTrue(hasattr(__A		,	"""do_center_crop"""		)		)
											self.assertTrue(hasattr(__A		,	"""size"""		)		)






					def   lowerCAmelCase_							(			self:				Tuple		)  ->      Union[str, Any]:
											snake_case_					:Union[str, Any]		=     self.image_processing_class(**self.image_processor_dict		)
											# create random PIL videos
											snake_case_					:Dict		=     prepare_video_inputs(self.image_processor_tester		,	equal_resolution=__A		)
											for video in video_inputs:
																	self.assertIsInstance(__A		,	__A		)
																	self.assertIsInstance(video[0]		,	Image.Image		)

											# Test not batched input
											snake_case_					:Optional[Any]		=     image_processor(video_inputs[0]		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)

											# Test batched
											snake_case_					:str		=     image_processor(__A		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)






					def   lowerCAmelCase_							(			self:				str		)  ->      Optional[Any]:
											snake_case_					:Tuple		=     self.image_processing_class(**self.image_processor_dict		)
											# create random numpy tensors
											snake_case_					:int		=     prepare_video_inputs(self.image_processor_tester		,	equal_resolution=__A		,	numpify=__A		)
											for video in video_inputs:
																	self.assertIsInstance(__A		,	__A		)
																	self.assertIsInstance(video[0]		,	np.ndarray		)

											# Test not batched input
											snake_case_					:List[str]		=     image_processor(video_inputs[0]		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)

											# Test batched
											snake_case_					:List[Any]		=     image_processor(__A		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)






					def   lowerCAmelCase_							(			self:				str		)  ->      Optional[Any]:
											snake_case_					:Tuple		=     self.image_processing_class(**self.image_processor_dict		)
											# create random PyTorch tensors
											snake_case_					:Tuple		=     prepare_video_inputs(self.image_processor_tester		,	equal_resolution=__A		,	torchify=__A		)
											for video in video_inputs:
																	self.assertIsInstance(__A		,	__A		)
																	self.assertIsInstance(video[0]		,	torch.Tensor		)

											# Test not batched input
											snake_case_					:Dict		=     image_processor(video_inputs[0]		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)

											# Test batched
											snake_case_					:str		=     image_processor(__A		,	return_tensors="""pt"""		).pixel_values
											self.assertEqual(
											    encoded_videos.shape		,	(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size["""height"""],
											        self.image_processor_tester.crop_size["""width"""],
											    )		,	)




'''simple docstring'''




import argparse
import copy
import json
import multiprocessing
import os
import time

from create_dummy_models import COMPOSITE_MODELS, create_tiny_models
from huggingface_hub import ModelFilter, hf_api

import transformers
from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer
from transformers.image_processing_utils import BaseImageProcessor





def 				a_							(    )      ->List[Any]:






				'''simple docstring'''

				__lowerCamelCase		:   Optional[Any]           =       set()
				# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
				for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
								__lowerCamelCase		:   Dict           =       getattr(transformers.models.auto				,    lowercase				,    lowercase     )
								if module is None:
												continue
								# all mappings in a single auto modeling file
								__lowerCamelCase		:   Any           =       [
								    x
								    for x in dir(lowercase     )
								    if x.endswith("_MAPPING_NAMES"     )
								    and (x.startswith("MODEL_"     ) or x.startswith("TF_MODEL_"     ) or x.startswith("FLAX_MODEL_"     ))
								]
								for name in mapping_names:
												__lowerCamelCase		:   Union[str, Any]           =       getattr(lowercase				,    lowercase     )
												if mapping is not None:
																for v in mapping.values():
																				if isinstance(lowercase				,    (list, tuple)     ):
																								model_names.update(lowercase     )
																				elif isinstance(lowercase				,    lowercase     ):
																								model_names.add(lowercase     )

				return sorted(lowercase     )





def 				a_							(    )      ->int:






				'''simple docstring'''

				__lowerCamelCase		:   Tuple           =       set(get_all_model_names()     )

				with open("tests/utils/tiny_model_summary.json"     ) as fp:
								__lowerCamelCase		:   Optional[int]           =       json.load(lowercase     )
				__lowerCamelCase		:   Union[str, Any]           =       set()
				for model_base_name in tiny_model_info:
								tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"]     )

				# Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub.
				__lowerCamelCase		:   List[str]           =       model_names.difference(lowercase     )
				for model_name in copy.copy(lowercase     ):
								if not model_name.startswith("TF"     ) and F'TF{model_name}' in not_on_hub:
												tiny_models_names.remove(lowercase     )
								elif model_name.startswith("TF"     ) and model_name[2:] in not_on_hub:
												tiny_models_names.remove(lowercase     )

				return sorted(lowercase     )





def 				a_							(    lowercase     )      ->str:






				'''simple docstring'''

				__lowerCamelCase		:   Optional[int]           =       COMPOSITE_MODELS.values()

				# All tiny model base names on Hub
				__lowerCamelCase		:   List[Any]           =       get_all_model_names()
				__lowerCamelCase		:   Any           =       hf_api.list_models(
				    filter=ModelFilter(
				        author="hf-internal-testing"				,    )     )
				__lowerCamelCase		:   str           =       set()
				for x in models:
								__lowerCamelCase		:   Any           =       x.modelId
								__lowerCamelCase    ,       __lowerCamelCase		:   List[Any]           =       model.split("/"     )
								if not model.startswith("tiny-random-"     ):
												continue
								__lowerCamelCase		:   int           =       model.replace("tiny-random-"				,    ""     )
								if not model[0].isupper():
												continue
								if model not in model_names and model not in special_models:
												continue
								_models.add(lowercase     )

				__lowerCamelCase		:   Tuple           =       sorted(_models     )
				# All tiny model names on Hub
				__lowerCamelCase		:   Union[str, Any]           =       {}
				for model in models:
								__lowerCamelCase		:   List[str]           =       F'hf-internal-testing/tiny-random-{model}'
								__lowerCamelCase		:   Any           =       model.split("-"     )[0]
								try:
												__lowerCamelCase		:   str           =       hf_api.repo_info(lowercase     )
												__lowerCamelCase		:   str           =       {
												    "tokenizer_classes": set(),
												    "processor_classes": set(),
												    "model_classes": set(),
												    "sha": repo_info.sha,
												}
								except Exception:
												continue
								try:
												time.sleep(1     )
												__lowerCamelCase		:   Optional[int]           =       AutoTokenizer.from_pretrained(lowercase     )
												content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__     )
								except Exception:
												pass
								try:
												time.sleep(1     )
												__lowerCamelCase		:   List[Any]           =       AutoTokenizer.from_pretrained(lowercase				,    use_fast=lowercase     )
												content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__     )
								except Exception:
												pass
								try:
												time.sleep(1     )
												__lowerCamelCase		:   List[Any]           =       AutoImageProcessor.from_pretrained(lowercase     )
												content["processor_classes"].add(img_p.__class__.__name__     )
								except Exception:
												pass
								try:
												time.sleep(1     )
												__lowerCamelCase		:   Tuple           =       AutoFeatureExtractor.from_pretrained(lowercase     )
												if not isinstance(lowercase				,    lowercase     ):
																content["processor_classes"].add(feat_p.__class__.__name__     )
								except Exception:
												pass
								try:
												time.sleep(1     )
												__lowerCamelCase		:   Optional[Any]           =       getattr(lowercase				,    lowercase     )
												__lowerCamelCase		:   Optional[Any]           =       model_class.from_pretrained(lowercase     )
												content["model_classes"].add(m.__class__.__name__     )
								except Exception:
												pass
								try:
												time.sleep(1     )
												__lowerCamelCase		:   List[str]           =       getattr(lowercase				,    F'TF{model}'     )
												__lowerCamelCase		:   Dict           =       model_class.from_pretrained(lowercase     )
												content["model_classes"].add(m.__class__.__name__     )
								except Exception:
												pass

								__lowerCamelCase		:   List[Any]           =       sorted(content["tokenizer_classes"]     )
								__lowerCamelCase		:   str           =       sorted(content["processor_classes"]     )
								__lowerCamelCase		:   Union[str, Any]           =       sorted(content["model_classes"]     )

								__lowerCamelCase		:   Tuple           =       content
								with open(os.path.join(lowercase				,    "hub_tiny_model_summary.json"     )				,    "w"     ) as fp:
												json.dump(lowercase				,    lowercase				,    ensure_ascii=lowercase				,    indent=4     )


if __name__ == "__main__":
				__lowercase	:   Any   		=					argparse.ArgumentParser()
				parser.add_argument("""--num_workers""", default=1, type=int, help="""The number of workers to run.""")
				__lowercase	:   Optional[int]   		=					parser.parse_args()

				# This has to be `spawn` to avoid hanging forever!
				multiprocessing.set_start_method("""spawn""")

				__lowercase	:   str   		=					"""tiny_models"""
				__lowercase	:   List[Any]   		=					True
				__lowercase	:   Optional[int]   		=					None
				__lowercase	:   List[Any]   		=					get_tiny_model_names_from_repo()
				__lowercase	:   List[Any]   		=					True
				__lowercase	:   Dict   		=					True
				__lowercase	:   Tuple   		=					"""hf-internal-testing"""

				create_tiny_models(
				    output_path,
				    all,
				    model_types,
				    models_to_skip,
				    no_check,
				    upload,
				    organization,
				    token=os.environ.get("""TOKEN""", None),
				    num_workers=args.num_workers,
				)





