





'''simple docstring'''







import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_       ,							unittest.TestCase      ):






				"""simple docstring"""







				__a            =ShapEPipeline
				__a            =['prompt']
				__a            =['prompt']
				__a            =[
				    'num_images_per_prompt',
				    'num_inference_steps',
				    'generator',
				    'latents',
				    'guidance_scale',
				    'frame_size',
				    'output_type',
				    'return_dict',
				]
				__a            =False




				@property
				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								return 32




				@property
				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								return 32




				@property
				def   UpperCamelCase__   (  self     :					List[Any]					):
								return self.time_input_dim * 4




				@property
				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								return 8




				@property
				def   UpperCamelCase__   (  self     :					Any					):
								_a								= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)
								return tokenizer




				@property
				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								torch.manual_seed(0					)
								_a								= CLIPTextConfig(
								    bos_token_id=0					,				eos_token_id=2					,				hidden_size=self.text_embedder_hidden_size					,				projection_dim=self.text_embedder_hidden_size					,				intermediate_size=37					,				layer_norm_eps=1e-0_5					,				num_attention_heads=4					,				num_hidden_layers=5					,				pad_token_id=1					,				vocab_size=10_00					,				)
								return CLIPTextModelWithProjection(__a					)




				@property
				def   UpperCamelCase__   (  self     :					int					):
								torch.manual_seed(0					)

								_a								= {
								    "num_attention_heads": 2,
								    "attention_head_dim": 16,
								    "embedding_dim": self.time_input_dim,
								    "num_embeddings": 32,
								    "embedding_proj_dim": self.text_embedder_hidden_size,
								    "time_embed_dim": self.time_embed_dim,
								    "num_layers": 1,
								    "clip_embed_dim": self.time_input_dim * 2,
								    "additional_embeddings": 0,
								    "time_embed_act_fn": "gelu",
								    "norm_in_type": "layer",
								    "encoder_hid_proj_type": None,
								    "added_emb_type": None,
								}

								_a								= PriorTransformer(**__a					)
								return model




				@property
				def   UpperCamelCase__   (  self     :					Any					):
								torch.manual_seed(0					)

								_a								= {
								    "param_shapes": (
								        (self.renderer_dim, 93),
								        (self.renderer_dim, 8),
								        (self.renderer_dim, 8),
								        (self.renderer_dim, 8),
								    ),
								    "d_latent": self.time_input_dim,
								    "d_hidden": self.renderer_dim,
								    "n_output": 12,
								    "background": (
								        0.1,
								        0.1,
								        0.1,
								    ),
								}
								_a								= ShapERenderer(**__a					)
								return model




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= self.dummy_prior
								_a								= self.dummy_text_encoder
								_a								= self.dummy_tokenizer
								_a								= self.dummy_renderer

								_a								= HeunDiscreteScheduler(
								    beta_schedule="exp"					,				num_train_timesteps=10_24					,				prediction_type="sample"					,				use_karras_sigmas=__a					,				clip_sample=__a					,				clip_sample_range=1.0					,				)
								_a								= {
								    "prior": prior,
								    "text_encoder": text_encoder,
								    "tokenizer": tokenizer,
								    "renderer": renderer,
								    "scheduler": scheduler,
								}

								return components




				def   UpperCamelCase__   (  self     :					int					,				__a     :					List[str]					,				__a     :					str=0					):
								if str(__a					).startswith("mps"					):
												_a								= torch.manual_seed(__a					)
								else:
												_a								= torch.Generator(device=__a					).manual_seed(__a					)
								_a								= {
								    "prompt": "horse",
								    "generator": generator,
								    "num_inference_steps": 1,
								    "frame_size": 32,
								    "output_type": "np",
								}
								return inputs




				def   UpperCamelCase__   (  self     :					Dict					):
								_a								= "cpu"

								_a								= self.get_dummy_components()

								_a								= self.pipeline_class(**__a					)
								_a								= pipe.to(__a					)

								pipe.set_progress_bar_config(disable=__a					)

								_a								= pipe(**self.get_dummy_inputs(__a					)					)
								_a								= output.images[0]
								_a								= image[0, -3:, -3:, -1]

								assert image.shape == (20, 32, 32, 3)

								_a								= np.array(
								    [
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								        0.00039216,
								    ]					)

								assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2




				def   UpperCamelCase__   (  self     :					List[str]					):
								# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
								self._test_inference_batch_consistent(batch_sizes=[1, 2]					)




				def   UpperCamelCase__   (  self     :					str					):
								_a								= torch_device == "cpu"
								_a								= True

								self._test_inference_batch_single_identical(
								    batch_size=2					,				test_max_difference=__a					,				relax_max_difference=__a					,				)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= self.get_dummy_components()
								_a								= self.pipeline_class(**__a					)
								_a								= pipe.to(__a					)
								pipe.set_progress_bar_config(disable=__a					)

								_a								= 1
								_a								= 2

								_a								= self.get_dummy_inputs(__a					)

								for key in inputs.keys():
												if key in self.batch_params:
																_a								= batch_size * [inputs[key]]

								_a								= pipe(**__a					,				num_images_per_prompt=__a					)[0]

								assert images.shape[0] == batch_size * num_images_per_prompt


@slow
@require_torch_gpu
class 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					Any					):
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




				def   UpperCamelCase__   (  self     :					int					):
								_a								= load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/shap_e/test_shap_e_np_out.npy"					)
								_a								= ShapEPipeline.from_pretrained("openai/shap-e"					)
								_a								= pipe.to(__a					)
								pipe.set_progress_bar_config(disable=__a					)

								_a								= torch.Generator(device=__a					).manual_seed(0					)

								_a								= pipe(
								    "a shark"					,				generator=__a					,				guidance_scale=15.0					,				num_inference_steps=64					,				frame_size=64					,				output_type="np"					,				).images[0]

								assert images.shape == (20, 64, 64, 3)

								assert_mean_pixel_difference(__a					,				__a					)







'''simple docstring'''







import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase_					:    Any      	=			get_tests_dir('fixtures')
lowerCAmelCase_					:    Union[str, Any]      	=			get_tests_dir('fixtures/dummy_feature_extractor_config.json')
lowerCAmelCase_					:    Dict      	=			get_tests_dir('fixtures/dummy-config.json')
class 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= 0




				def   UpperCamelCase__   (  self     :					str					):
								_a								= AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h"					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= AutoFeatureExtractor.from_pretrained(__a					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								with tempfile.TemporaryDirectory() as tmpdirname:
												_a								= WavaVecaConfig()

												# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
												_a								= AutoFeatureExtractor.from_pretrained(__a					).to_dict()

												config_dict.pop("feature_extractor_type"					)
												_a								= WavaVecaFeatureExtractor(**__a					)

												# save in new folder
												model_config.save_pretrained(__a					)
												config.save_pretrained(__a					)

												_a								= AutoFeatureExtractor.from_pretrained(__a					)

												# make sure private variable is not incorrectly saved
												_a								= json.loads(config.to_json_string()					)
												self.assertTrue("_processor_class" not in dict_as_saved					)

								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= AutoFeatureExtractor.from_pretrained(__a					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								with self.assertRaisesRegex(
								    __a					,				"bert-base is not a local folder and is not a valid model identifier"					):
												_a								= AutoFeatureExtractor.from_pretrained("bert-base"					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								with self.assertRaisesRegex(
								    __a					,				r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"					):
												_a								= AutoFeatureExtractor.from_pretrained(__a					,				revision="aaaaaa"					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								with self.assertRaisesRegex(
								    __a					,				"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."					,				):
												_a								= AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model"					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								# If remote code is not set, we will time out when asking whether to load the model.
								with self.assertRaises(__a					):
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					)
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(__a					):
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)

								_a								= AutoFeatureExtractor.from_pretrained(
								    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
								self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)

								# Test feature extractor can be reloaded.
								with tempfile.TemporaryDirectory() as tmp_dir:
												feature_extractor.save_pretrained(__a					)
												_a								= AutoFeatureExtractor.from_pretrained(__a					,				trust_remote_code=__a					)
								self.assertEqual(reloaded_feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)




				def   UpperCamelCase__   (  self     :					Any					):
								try:
												AutoConfig.register("custom"					,				__a					)
												AutoFeatureExtractor.register(__a					,				__a					)
												# Trying to register something existing in the Transformers library will raise an error
												with self.assertRaises(__a					):
																AutoFeatureExtractor.register(__a					,				__a					)

												# Now that the config is registered, it can be used as any other config with the auto-API
												_a								= CustomFeatureExtractor.from_pretrained(__a					)
												with tempfile.TemporaryDirectory() as tmp_dir:
																feature_extractor.save_pretrained(__a					)
																_a								= AutoFeatureExtractor.from_pretrained(__a					)
																self.assertIsInstance(__a					,				__a					)

								finally:
												if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]
												if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]




				def   UpperCamelCase__   (  self     :					Tuple					):
								class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_      ):






												"""simple docstring"""







												__a            =True

								try:
												AutoConfig.register("custom"					,				__a					)
												AutoFeatureExtractor.register(__a					,				__a					)
												# If remote code is not set, the default is to use local
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(feature_extractor.is_local					)

												# If remote code is disabled, we load the local one.
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(feature_extractor.is_local					)

												# If remote is enabled, we load from the Hub
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(not hasattr(__a					,				"is_local"					)					)

								finally:
												if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]
												if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
