




from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor
class 						_A :






  def __init__(  self		:     Optional[Any]				,						_A		:     List[Any]				,						_A		:     Union[str, Any]=3				,						_A		:     str=32				,						_A		:     Optional[int]=3				,						_A		:     List[str]=10				,						_A		:     Tuple=[10, 20, 30, 40]				,						_A		:     Dict=[1, 1, 2, 1]				,						_A		:     Any=True				,						_A		:     Optional[int]=True				,						_A		:     str="relu"				,						_A		:     Any=3				,						_A		:     Any=None				,						)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       int       =			parent
       lowercase :       Any       =			batch_size
       lowercase :       List[Any]       =			image_size
       lowercase :       Dict       =			num_channels
       lowercase :       Union[str, Any]       =			embeddings_size
       lowercase :       List[Any]       =			hidden_sizes
       lowercase :       Tuple       =			depths
       lowercase :       int       =			is_training
       lowercase :       Union[str, Any]       =			use_labels
       lowercase :       List[Any]       =			hidden_act
       lowercase :       int       =			num_labels
       lowercase :       Any       =			scope
       lowercase :       Union[str, Any]       =			len(__UpperCAmelCase				)






  def  __a      (  self		:     str				)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       int       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

       lowercase :       str       =			None
       if self.use_labels:
            lowercase :       Union[str, Any]       =			ids_tensor([self.batch_size]				,						self.num_labels				)

       lowercase :       Any       =			self.get_config()

       return config, pixel_values, labels






  def  __a      (  self		:     int				)		->   List[str]:






       """simple docstring"""







       return ResNetConfig(
           num_channels=self.num_channels				,						embeddings_size=self.embeddings_size				,						hidden_sizes=self.hidden_sizes				,						depths=self.depths				,						hidden_act=self.hidden_act				,						num_labels=self.num_labels				,						image_size=self.image_size				,						)






  def  __a      (  self		:     Dict				,						_A		:     Optional[Any]				,						_A		:     Tuple				,						_A		:     Any				)		->   List[Any]:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			TFResNetModel(config=__UpperCAmelCase				)
       lowercase :       Optional[Any]       =			model(__UpperCAmelCase				)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape				,						(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,						)






  def  __a      (  self		:     Tuple				,						_A		:     Union[str, Any]				,						_A		:     List[str]				,						_A		:     int				)		->   Tuple:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			self.num_labels
       lowercase :       str       =			TFResNetForImageClassification(__UpperCAmelCase				)
       lowercase :       Tuple       =			model(__UpperCAmelCase				,						labels=__UpperCAmelCase				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.num_labels)				)






  def  __a      (  self		:     Tuple				)		->   List[str]:






       """simple docstring"""







       lowercase :       Optional[int]       =			self.prepare_config_and_inputs()
       lowercase :       int       =			config_and_inputs
       lowercase :       Dict       =			{"""pixel_values""": pixel_values}
       return config, inputs_dict


@require_tf
class 						_A (  __SCREAMING_SNAKE_CASE      ,       __SCREAMING_SNAKE_CASE      ,       unittest.TestCase				):
  _UpperCamelCase       :      int			=      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
  _UpperCamelCase       :      Union[str, Any]			=      (
      {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
      if is_tf_available()
      else {}
  )

  _UpperCamelCase       :      str			=      False
  _UpperCamelCase       :      Dict			=      False
  _UpperCamelCase       :      Optional[Any]			=      False
  _UpperCamelCase       :      Union[str, Any]			=      False
  _UpperCamelCase       :      int			=      False






  def  __a      (  self		:     Optional[Any]				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       str       =			TFResNetModelTester(self				)
       lowercase :       Tuple       =			ConfigTester(self				,						config_class=__UpperCAmelCase				,						has_text_modality=__UpperCAmelCase				)






  def  __a      (  self		:     str				)		->   List[str]:






       """simple docstring"""







       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()






  def  __a      (  self		:     Tuple				)		->   Optional[int]:






       """simple docstring"""







       return






  @unittest.skip(reason='''ResNet does not use inputs_embeds'''				)
  def  __a      (  self		:     Union[str, Any]				)		->   Tuple:






       """simple docstring"""







       pass






  @unittest.skip(reason='''ResNet does not support input and output embeddings'''				)
  def  __a      (  self		:     List[str]				)		->   Dict:






       """simple docstring"""







       pass






  def  __a      (  self		:     Optional[Any]				)		->   str:






       """simple docstring"""







       lowercase :       int       =			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowercase :       str       =			model_class(__UpperCAmelCase				)
            lowercase :       Tuple       =			inspect.signature(model.call				)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            lowercase :       List[Any]       =			[*signature.parameters.keys()]

            lowercase :       Optional[Any]       =			["""pixel_values"""]
            self.assertListEqual(arg_names[:1]				,						__UpperCAmelCase				)






  def  __a      (  self		:     Dict				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__UpperCAmelCase				)






  def  __a      (  self		:     List[Any]				)		->   List[str]:






       """simple docstring"""







       def check_hidden_states_output(_A		:     Optional[Any]				,						_A		:     Union[str, Any]				,						_A		:     Tuple				):
            lowercase :       Optional[int]       =			model_class(__UpperCAmelCase				)
            lowercase :       Optional[Any]       =			model(**self._prepare_for_class(__UpperCAmelCase				,						__UpperCAmelCase				)				)

            lowercase :       str       =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            lowercase :       Optional[Any]       =			self.model_tester.num_stages
            self.assertEqual(len(__UpperCAmelCase				)				,						expected_num_stages + 1				)

            # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
            self.assertListEqual(
                list(hidden_states[0].shape[-2:]				)				,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]				,						)

       lowercase :       List[str]       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       Union[str, Any]       =			["""basic""", """bottleneck"""]
       for model_class in self.all_model_classes:
            for layer_type in layers_type:
                 lowercase :       Optional[Any]       =			layer_type
                 lowercase :       int       =			True
                 check_hidden_states_output(__UpperCAmelCase				,						__UpperCAmelCase				,						__UpperCAmelCase				)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 lowercase :       Optional[int]       =			True

                 check_hidden_states_output(__UpperCAmelCase				,						__UpperCAmelCase				,						__UpperCAmelCase				)






  def  __a      (  self		:     Tuple				)		->   List[Any]:






       """simple docstring"""







       lowercase :       Optional[Any]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase				)






  @slow
  def  __a      (  self		:     int				)		->   int:






       """simple docstring"""







       for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowercase :       Optional[Any]       =			TFResNetModel.from_pretrained(__UpperCAmelCase				)
            self.assertIsNotNone(__UpperCAmelCase				)






def  snake_case(    )			->							Any:





     '''simple docstring'''


     lowercase :       Any       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
     return image





@require_tf
@require_vision
class 						_A (  unittest.TestCase				):






  @cached_property
  def  __a      (  self		:     List[str]				)		->   Any:






       """simple docstring"""







       return (
           AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
           if is_vision_available()
           else None
       )






  @slow
  def  __a      (  self		:     Any				)		->   Tuple:






       """simple docstring"""







       lowercase :       Dict       =			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

       lowercase :       Any       =			self.default_image_processor
       lowercase :       Optional[Any]       =			prepare_img()
       lowercase :       Dict       =			image_processor(images=__UpperCAmelCase				,						return_tensors='''tf'''				)

       # forward pass
       lowercase :       Dict       =			model(**__UpperCAmelCase				)

       # verify the logits
       lowercase :       Dict       =			tf.TensorShape((1, 1_000)				)
       self.assertEqual(outputs.logits.shape				,						__UpperCAmelCase				)

       lowercase :       str       =			tf.constant([-11.1_069, -9.7_877, -8.3_777]				)

       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()				,						__UpperCAmelCase				,						atol=1E-4				)				)





import os
from pathlib import Path
from unittest.mock import patch

import pytest
import zstandard as zstd

from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
    OfflineModeIsEnabled,
    cached_path,
    fsspec_get,
    fsspec_head,
    ftp_get,
    ftp_head,
    get_from_cache,
    http_get,
    http_head,
)


lowerCAmelCase_						=			'\\n    Text data.\n    Second line of data.'

lowerCAmelCase_						=			'file'






@pytest.fixture(scope='''session'''   )
def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Any       =			tmp_path_factory.mktemp('''data'''   ) / (FILE_PATH + '''.zstd''')
     lowercase :       List[Any]       =			bytes(__magic_name__			,		'''utf-8'''   )
     with zstd.open(__magic_name__			,		'''wb'''   ) as f:
          f.write(__magic_name__   )
     return path






@pytest.fixture
def  snake_case(    __magic_name__   )			->							List[Any]:





     '''simple docstring'''


     with open(os.path.join(tmpfs.local_root_dir			,		__magic_name__   )			,		'''w'''   ) as f:
          f.write(__magic_name__   )
     return FILE_PATH






@pytest.mark.parametrize('''compression_format'''			,		['''gzip''', '''xz''', '''zstd''']   )
def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Optional[int]       =			{'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path}
     lowercase :       int       =			input_paths[compression_format]
     lowercase :       Any       =			tmp_path / '''cache'''
     lowercase :       int       =			DownloadConfig(cache_dir=__magic_name__			,		extract_compressed_file=__magic_name__   )
     lowercase :       Optional[Any]       =			cached_path(__magic_name__			,		download_config=__magic_name__   )
     with open(__magic_name__   ) as f:
          lowercase :       Optional[int]       =			f.read()
     with open(__magic_name__   ) as f:
          lowercase :       str       =			f.read()
     assert extracted_file_content == expected_file_content






@pytest.mark.parametrize('''default_extracted'''			,		[True, False]   )
@pytest.mark.parametrize('''default_cache_dir'''			,		[True, False]   )
def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       Dict       =			'''custom_cache'''
     lowercase :       Union[str, Any]       =			'''custom_extracted_dir'''
     lowercase :       str       =			tmp_path / '''custom_extracted_path'''
     if default_extracted:
          lowercase :       Tuple       =			('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''')
     else:
          monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR'''			,		__magic_name__   )
          monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH'''			,		str(__magic_name__   )   )
          lowercase :       int       =			custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)

     lowercase :       List[str]       =			xz_file
     lowercase :       Any       =			(
         DownloadConfig(extract_compressed_file=__magic_name__   )
         if default_cache_dir
         else DownloadConfig(cache_dir=tmp_path / custom_cache_dir			,		extract_compressed_file=__magic_name__   )
     )
     lowercase :       Optional[int]       =			cached_path(__magic_name__			,		download_config=__magic_name__   )
     assert Path(__magic_name__   ).parent.parts[-2:] == expected






def  snake_case(    __magic_name__   )			->							List[Any]:





     '''simple docstring'''


     lowercase :       Any       =			str(Path(__magic_name__   ).resolve()   )
     assert cached_path(__magic_name__   ) == text_file
     # relative path
     lowercase :       Union[str, Any]       =			str(Path(__magic_name__   ).resolve().relative_to(Path(os.getcwd()   )   )   )
     assert cached_path(__magic_name__   ) == text_file






def  snake_case(    __magic_name__   )			->							Union[str, Any]:





     '''simple docstring'''


     lowercase :       List[Any]       =			str(tmp_path.resolve() / '''__missing_file__.txt'''   )
     with pytest.raises(__magic_name__   ):
          cached_path(__magic_name__   )
     # relative path
     lowercase :       Optional[int]       =			'''./__missing_file__.txt'''
     with pytest.raises(__magic_name__   ):
          cached_path(__magic_name__   )






def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       List[str]       =			get_from_cache(F"""tmp://{tmpfs_file}"""   )
     with open(__magic_name__   ) as f:
          lowercase :       List[Any]       =			f.read()
     assert output_file_content == FILE_CONTENT






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    )			->							List[Any]:





     '''simple docstring'''


     with pytest.raises(__magic_name__   ):
          cached_path('''https://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							Tuple:





     '''simple docstring'''


     lowercase :       Any       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          http_get('''https://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          http_head('''https://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							Optional[Any]:





     '''simple docstring'''


     lowercase :       Optional[Any]       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          ftp_get('''ftp://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          ftp_head('''ftp://huggingface.co'''   )






@patch('''datasets.config.HF_DATASETS_OFFLINE'''			,		__magic_name__   )
def  snake_case(    __magic_name__   )			->							List[str]:





     '''simple docstring'''


     lowercase :       str       =			tmp_path_factory.mktemp('''data'''   ) / '''file.html'''
     with pytest.raises(__magic_name__   ):
          fsspec_get('''s3://huggingface.co'''			,		temp_file=__magic_name__   )
     with pytest.raises(__magic_name__   ):
          fsspec_head('''s3://huggingface.co'''   )