



import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						import jax.numpy as jnp

						from transformers.models.distilbert.modeling_flax_distilbert import (
						    FlaxDistilBertForMaskedLM,
						    FlaxDistilBertForMultipleChoice,
						    FlaxDistilBertForQuestionAnswering,
						    FlaxDistilBertForSequenceClassification,
						    FlaxDistilBertForTokenClassification,
						    FlaxDistilBertModel,
						)



class   UpperCAmelCase_    (       unittest.TestCase):







							def __init__(   self,			__a,			__a=13,			__a=7,			__a=True,			__a=True,			__a=True,			__a=True,			__a=99,			__a=32,			__a=5,			__a=4,			__a=37,			__a="gelu",			__a=0.1,			__a=0.1,			__a=512,			__a=16,			__a=2,			__a=0.02,			__a=4,			):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    parent
														_lowerCAmelCase     :							Tuple    =    batch_size
														_lowerCAmelCase     :							Any    =    seq_length
														_lowerCAmelCase     :							int    =    is_training
														_lowerCAmelCase     :							List[str]    =    use_attention_mask
														_lowerCAmelCase     :							str    =    use_token_type_ids
														_lowerCAmelCase     :							List[str]    =    use_labels
														_lowerCAmelCase     :							Dict    =    vocab_size
														_lowerCAmelCase     :							Any    =    hidden_size
														_lowerCAmelCase     :							Optional[int]    =    num_hidden_layers
														_lowerCAmelCase     :							Optional[int]    =    num_attention_heads
														_lowerCAmelCase     :							Tuple    =    intermediate_size
														_lowerCAmelCase     :							Optional[int]    =    hidden_act
														_lowerCAmelCase     :							int    =    hidden_dropout_prob
														_lowerCAmelCase     :							List[Any]    =    attention_probs_dropout_prob
														_lowerCAmelCase     :							int    =    max_position_embeddings
														_lowerCAmelCase     :							Optional[Any]    =    type_vocab_size
														_lowerCAmelCase     :							Tuple    =    type_sequence_label_size
														_lowerCAmelCase     :							List[str]    =    initializer_range
														_lowerCAmelCase     :							Dict    =    num_choices







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    ids_tensor([self.batch_size, self.seq_length],			self.vocab_size)

														_lowerCAmelCase     :							str    =    None
														if self.use_attention_mask:
																					_lowerCAmelCase     :							Optional[Any]    =    random_attention_mask([self.batch_size, self.seq_length])

														_lowerCAmelCase     :							Union[str, Any]    =    DistilBertConfig(
														    vocab_size=self.vocab_size,			dim=self.hidden_size,			n_layers=self.num_hidden_layers,			n_heads=self.num_attention_heads,			hidden_dim=self.intermediate_size,			hidden_act=self.hidden_act,			dropout=self.hidden_dropout_prob,			attention_dropout=self.attention_probs_dropout_prob,			max_position_embeddings=self.max_position_embeddings,			initializer_range=self.initializer_range,			tie_weights_=__a,			)

														return config, input_ids, attention_mask







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    self.prepare_config_and_inputs()
														_lowerCAmelCase   ,    _lowerCAmelCase   ,    _lowerCAmelCase     :							str    =    config_and_inputs
														_lowerCAmelCase     :							Tuple    =    {"input_ids": input_ids, "attention_mask": attention_mask}
														return config, inputs_dict



@require_flax
class   UpperCAmelCase_    (       a   ,					unittest.TestCase):
							lowerCamelCase__   			=		(
							    (
							        FlaxDistilBertModel,
							        FlaxDistilBertForMaskedLM,
							        FlaxDistilBertForMultipleChoice,
							        FlaxDistilBertForQuestionAnswering,
							        FlaxDistilBertForSequenceClassification,
							        FlaxDistilBertForTokenClassification,
							        FlaxDistilBertForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    FlaxDistilBertModelTester(self)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														for model_class_name in self.all_model_classes:
																					_lowerCAmelCase     :							List[Any]    =    model_class_name.from_pretrained("distilbert-base-uncased")
																					_lowerCAmelCase     :							str    =    model(np.ones((1, 1)))
																					self.assertIsNotNone(__a)



@require_flax
class   UpperCAmelCase_    (       unittest.TestCase):







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							List[str]    =    FlaxDistilBertModel.from_pretrained("distilbert-base-uncased")
														_lowerCAmelCase     :							str    =    np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
														_lowerCAmelCase     :							Dict    =    np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
														_lowerCAmelCase     :							Dict    =    model(__a,			attention_mask=__a)[0]
														_lowerCAmelCase     :							List[Any]    =    (1, 11, 768)
														self.assertEqual(output.shape,			__a)
														_lowerCAmelCase     :							Optional[Any]    =    np.array([[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]])

														self.assertTrue(jnp.allclose(output[:, 1:4, 1:4],			__a,			atol=1E-4))





import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


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

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


_snake_case		=  get_tests_dir("fixtures")



class   UpperCAmelCase_    (       unittest.TestCase):







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    mock.Mock()
														_lowerCAmelCase     :							int    =    500
														_lowerCAmelCase     :							Tuple    =    {}
														_lowerCAmelCase     :							str    =    HTTPError
														_lowerCAmelCase     :							Union[str, Any]    =    {}

														# Download this model to make sure it's in the cache.
														_lowerCAmelCase     :							Tuple    =    ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit")
														# Under the mock environment we get a 500 error when trying to reach the model.
														with mock.patch("requests.Session.request",			return_value=__a) as mock_head:
																					_lowerCAmelCase     :							Optional[int]    =    ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit")
																					# This check we did call the fake head request
																					mock_head.assert_called()







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    ViTImageProcessor.from_pretrained(
														    "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json")







							def    snake_case__      (   self):

														'''simple docstring'''

														with self.assertRaises(__a):
																					# config is in subfolder, the following should not work without specifying the subfolder
																					_lowerCAmelCase     :							int    =    AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants")

														_lowerCAmelCase     :							Optional[Any]    =    AutoImageProcessor.from_pretrained(
														    "hf-internal-testing/stable-diffusion-all-variants",			subfolder="feature_extractor")

														self.assertIsNotNone(__a)



@is_staging_test
class   UpperCAmelCase_    (       unittest.TestCase):







							@classmethod
							def    snake_case__      (   cls):

														'''simple docstring'''

														_lowerCAmelCase     :							Union[str, Any]    =    TOKEN
														HfFolder.save_token(__a)







							@classmethod
							def    snake_case__      (   cls):

														'''simple docstring'''

														try:
																					delete_repo(token=cls._token,			repo_id="test-image-processor")
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token,			repo_id="valid_org/test-image-processor-org")
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token,			repo_id="test-dynamic-image-processor")
														except HTTPError:
																					pass







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    ViTImageProcessor.from_pretrained(__a)
														image_processor.push_to_hub("test-image-processor",			use_auth_token=self._token)

														_lowerCAmelCase     :							str    =    ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor")
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__a,			getattr(__a,			__a))

														# Reset repo
														delete_repo(token=self._token,			repo_id="test-image-processor")

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					image_processor.save_pretrained(
																					    __a,			repo_id="test-image-processor",			push_to_hub=__a,			use_auth_token=self._token)

														_lowerCAmelCase     :							Optional[int]    =    ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor")
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__a,			getattr(__a,			__a))







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Any    =    ViTImageProcessor.from_pretrained(__a)
														image_processor.push_to_hub("valid_org/test-image-processor",			use_auth_token=self._token)

														_lowerCAmelCase     :							Tuple    =    ViTImageProcessor.from_pretrained("valid_org/test-image-processor")
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__a,			getattr(__a,			__a))

														# Reset repo
														delete_repo(token=self._token,			repo_id="valid_org/test-image-processor")

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					image_processor.save_pretrained(
																					    __a,			repo_id="valid_org/test-image-processor-org",			push_to_hub=__a,			use_auth_token=self._token)

														_lowerCAmelCase     :							Optional[int]    =    ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org")
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__a,			getattr(__a,			__a))







							def    snake_case__      (   self):

														'''simple docstring'''

														CustomImageProcessor.register_for_auto_class()
														_lowerCAmelCase     :							List[str]    =    CustomImageProcessor.from_pretrained(__a)

														image_processor.push_to_hub("test-dynamic-image-processor",			use_auth_token=self._token)

														# This has added the proper auto_map field to the config
														self.assertDictEqual(
														    image_processor.auto_map,			{"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"},			)

														_lowerCAmelCase     :							Tuple    =    AutoImageProcessor.from_pretrained(
														    f"{USER}/test-dynamic-image-processor",			trust_remote_code=__a)
														# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
														self.assertEqual(new_image_processor.__class__.__name__,			"CustomImageProcessor")
