


'''simple docstring'''

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
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.models.swin.modeling_tf_swin import (
         TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
         TFSwinForImageClassification,
         TFSwinForMaskedImageModeling,
         TFSwinModel,
     )


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor





class 					snake_case   :





  """simple docstring"""




  def __init__(   self      ,  UpperCamelCase      ,  UpperCamelCase=13      ,  UpperCamelCase=32      ,  UpperCamelCase=2      ,  UpperCamelCase=3      ,  UpperCamelCase=16      ,  UpperCamelCase=[1, 2, 1]      ,  UpperCamelCase=[2, 2, 4]      ,  UpperCamelCase=2      ,  UpperCamelCase=2.0      ,  UpperCamelCase=True      ,  UpperCamelCase=0.0      ,  UpperCamelCase=0.0      ,  UpperCamelCase=0.1      ,  UpperCamelCase="gelu"      ,  UpperCamelCase=False      ,  UpperCamelCase=True      ,  UpperCamelCase=0.02      ,  UpperCamelCase=1e-5      ,  UpperCamelCase=True      ,  UpperCamelCase=None      ,  UpperCamelCase=True      ,  UpperCamelCase=10      ,  UpperCamelCase=8      ,  ):







   """simple docstring"""
   lowerCamelCase_								=  parent
   lowerCamelCase_								=  batch_size
   lowerCamelCase_								=  image_size
   lowerCamelCase_								=  patch_size
   lowerCamelCase_								=  num_channels
   lowerCamelCase_								=  embed_dim
   lowerCamelCase_								=  depths
   lowerCamelCase_								=  num_heads
   lowerCamelCase_								=  window_size
   lowerCamelCase_								=  mlp_ratio
   lowerCamelCase_								=  qkv_bias
   lowerCamelCase_								=  hidden_dropout_prob
   lowerCamelCase_								=  attention_probs_dropout_prob
   lowerCamelCase_								=  drop_path_rate
   lowerCamelCase_								=  hidden_act
   lowerCamelCase_								=  use_absolute_embeddings
   lowerCamelCase_								=  patch_norm
   lowerCamelCase_								=  layer_norm_eps
   lowerCamelCase_								=  initializer_range
   lowerCamelCase_								=  is_training
   lowerCamelCase_								=  scope
   lowerCamelCase_								=  use_labels
   lowerCamelCase_								=  type_sequence_label_size
   lowerCamelCase_								=  encoder_stride






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

   lowerCamelCase_								=  None
   if self.use_labels:
    lowerCamelCase_								=  ids_tensor([self.batch_size]      ,  self.type_sequence_label_size					)

   lowerCamelCase_								=  self.get_config()

   return config, pixel_values, labels






  def   snake_case		(   self					):







   """simple docstring"""
   return SwinConfig(
       image_size=self.image_size      ,  patch_size=self.patch_size      ,  num_channels=self.num_channels      ,  embed_dim=self.embed_dim      ,  depths=self.depths      ,  num_heads=self.num_heads      ,  window_size=self.window_size      ,  mlp_ratio=self.mlp_ratio      ,  qkv_bias=self.qkv_bias      ,  hidden_dropout_prob=self.hidden_dropout_prob      ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,  drop_path_rate=self.drop_path_rate      ,  hidden_act=self.hidden_act      ,  use_absolute_embeddings=self.use_absolute_embeddings      ,  path_norm=self.patch_norm      ,  layer_norm_eps=self.layer_norm_eps      ,  initializer_range=self.initializer_range      ,  encoder_stride=self.encoder_stride      ,  )






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  TFSwinModel(config=UpperCamelCase					)
   lowerCamelCase_								=  model(UpperCamelCase					)

   lowerCamelCase_								=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
   lowerCamelCase_								=  int(config.embed_dim * 2 ** (len(config.depths					) - 1)					)

   self.parent.assertEqual(result.last_hidden_state.shape      ,  (self.batch_size, expected_seq_len, expected_dim)					)






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  TFSwinForMaskedImageModeling(config=UpperCamelCase					)
   lowerCamelCase_								=  model(UpperCamelCase					)
   self.parent.assertEqual(
       result.logits.shape      ,  (self.batch_size, self.num_channels, self.image_size, self.image_size)					)

   # test greyscale images
   lowerCamelCase_								=  1
   lowerCamelCase_								=  TFSwinForMaskedImageModeling(UpperCamelCase					)

   lowerCamelCase_								=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
   lowerCamelCase_								=  model(UpperCamelCase					)
   self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, 1, self.image_size, self.image_size)					)






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  self.type_sequence_label_size
   lowerCamelCase_								=  TFSwinForImageClassification(UpperCamelCase					)
   lowerCamelCase_								=  model(UpperCamelCase      ,  labels=UpperCamelCase					)
   self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.type_sequence_label_size)					)

   # test greyscale images
   lowerCamelCase_								=  1
   lowerCamelCase_								=  TFSwinForImageClassification(UpperCamelCase					)
   lowerCamelCase_								=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
   lowerCamelCase_								=  model(UpperCamelCase					)
   self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.type_sequence_label_size)					)







  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.prepare_config_and_inputs()
   lowerCamelCase_			,lowerCamelCase_			,lowerCamelCase_								=  config_and_inputs
   lowerCamelCase_								=  {"pixel_values": pixel_values}
   return config, inputs_dict





@require_tf
class 					snake_case   (   lowercase      ,						lowercase      ,						unittest.TestCase      ):





  """simple docstring"""




  _lowerCamelCase		   =  (
      (
          TFSwinModel,
          TFSwinForImageClassification,
          TFSwinForMaskedImageModeling,
      )
      if is_tf_available()
      else ()
  )
  _lowerCamelCase		   =  (
      {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
      if is_tf_available()
      else {}
  )

  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  TFSwinModelTester(self					)
   lowerCamelCase_								=  ConfigTester(self      ,  config_class=UpperCamelCase      ,  embed_dim=37					)






  def   snake_case		(   self					):







   """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   snake_case		(   self					):







   """simple docstring"""
   return






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCamelCase					)






  @unittest.skip(reason="Swin does not use inputs_embeds"					)
  def   snake_case		(   self					):







   """simple docstring"""
   pass






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    self.assertIsInstance(model.get_input_embeddings()      ,  tf.keras.layers.Layer					)
    lowerCamelCase_								=  model.get_output_embeddings()
    self.assertTrue(x is None or isinstance(UpperCamelCase      ,  tf.keras.layers.Dense					)					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    lowerCamelCase_								=  inspect.signature(model.call					)
    # signature.parameters is an OrderedDict => so arg_names order is deterministic
    lowerCamelCase_								=  [*signature.parameters.keys()]

    lowerCamelCase_								=  ["pixel_values"]
    self.assertListEqual(arg_names[:1]      ,  UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_								=  True

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  True
    lowerCamelCase_								=  False
    lowerCamelCase_								=  True
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    lowerCamelCase_								=  model(**self._prepare_for_class(UpperCamelCase      ,  UpperCamelCase					)					)
    lowerCamelCase_								=  outputs.attentions
    lowerCamelCase_								=  len(self.model_tester.depths					)
    self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

    # check that output_attentions also work using config
    del inputs_dict["output_attentions"]
    lowerCamelCase_								=  True
    lowerCamelCase_								=  config.window_size**2
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    lowerCamelCase_								=  model(**self._prepare_for_class(UpperCamelCase      ,  UpperCamelCase					)					)
    lowerCamelCase_								=  outputs.attentions
    self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

    self.assertListEqual(
        list(attentions[0].shape[-3:]					)      ,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,  )
    lowerCamelCase_								=  len(UpperCamelCase					)

    # Check attention is always last and order is fine
    lowerCamelCase_								=  True
    lowerCamelCase_								=  True
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    lowerCamelCase_								=  model(**self._prepare_for_class(UpperCamelCase      ,  UpperCamelCase					)					)

    if hasattr(self.model_tester      ,  "num_hidden_states_types"					):
     lowerCamelCase_								=  self.model_tester.num_hidden_states_types
    else:
     # also another +1 for reshaped_hidden_states
     lowerCamelCase_								=  2
    self.assertEqual(out_len + added_hidden_states      ,  len(UpperCamelCase					)					)

    lowerCamelCase_								=  outputs.attentions

    self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

    self.assertListEqual(
        list(self_attentions[0].shape[-3:]					)      ,  [self.model_tester.num_heads[0], window_size_squared, window_size_squared]      ,  )






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  model_class(UpperCamelCase					)
   lowerCamelCase_								=  model(**self._prepare_for_class(UpperCamelCase      ,  UpperCamelCase					)					)
   lowerCamelCase_								=  outputs.hidden_states

   lowerCamelCase_								=  getattr(
       self.model_tester      ,  "expected_num_hidden_layers"      ,  len(self.model_tester.depths					) + 1					)
   self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

   # Swin has a different seq_length
   lowerCamelCase_								=  to_atuple(config.patch_size					)

   lowerCamelCase_								=  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

   self.assertListEqual(
       list(hidden_states[0].shape[-2:]					)      ,  [num_patches, self.model_tester.embed_dim]      ,  )

   lowerCamelCase_								=  outputs.reshaped_hidden_states
   self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

   lowerCamelCase_			,lowerCamelCase_			,lowerCamelCase_			,lowerCamelCase_								=  reshaped_hidden_states[0].shape

   lowerCamelCase_								=  tf.reshape(reshaped_hidden_states[0]      ,  (batch_size, num_channels, height * width)					)
   lowerCamelCase_								=  tf.transpose(UpperCamelCase      ,  (0, 2, 1)					)

   self.assertListEqual(
       list(reshaped_hidden_states.shape[-2:]					)      ,  [num_patches, self.model_tester.embed_dim]      ,  )






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

   lowerCamelCase_								=  to_atuple(self.model_tester.image_size					)

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  True
    self.check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					)

    # check that output_hidden_states also work using config
    del inputs_dict["output_hidden_states"]
    lowerCamelCase_								=  True

    self.check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()
   lowerCamelCase_								=  3

   lowerCamelCase_								=  to_atuple(self.model_tester.image_size					)
   lowerCamelCase_								=  to_atuple(config.patch_size					)

   lowerCamelCase_								=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
   lowerCamelCase_								=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  True
    self.check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  (padded_height, padded_width)					)

    # check that output_hidden_states also work using config
    del inputs_dict["output_hidden_states"]
    lowerCamelCase_								=  True
    self.check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase      ,  (padded_height, padded_width)					)







  @slow
  def   snake_case		(   self					):







   """simple docstring"""
   for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    lowerCamelCase_								=  TFSwinModel.from_pretrained(UpperCamelCase					)
    self.assertIsNotNone(UpperCamelCase					)





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





  """simple docstring"""




  @cached_property
  def   snake_case		(   self					):







   """simple docstring"""
   return (
       AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224"					)
       if is_vision_available()
       else None
   )







  @slow
  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  TFSwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224"					)
   lowerCamelCase_								=  self.default_image_processor

   lowerCamelCase_								=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
   lowerCamelCase_								=  image_processor(images=UpperCamelCase      ,  return_tensors="tf"					)

   # forward pass
   lowerCamelCase_								=  model(UpperCamelCase					)

   # verify the logits
   lowerCamelCase_								=  tf.TensorShape((1, 1000)					)
   self.assertEqual(outputs.logits.shape      ,  UpperCamelCase					)
   lowerCamelCase_								=  tf.constant([-0.0_948, -0.6_454, -0.0_921]					)
   self.assertTrue(np.allclose(outputs.logits[0, :3]      ,  UpperCamelCase      ,  atol=1e-4					)					)







'''simple docstring'''

import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
a_  :    Any      =			"""\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
a_  :    Optional[Any]      =			"""\
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
"""

# TODO: Add a link to an official homepage for the dataset here
a_  :    List[str]      =			""""""

# TODO: Add the licence for the dataset here if you can find it
a_  :    Dict      =			""""""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
a_  :    Optional[int]      =			{
    """first_domain""": """https://huggingface.co/great-new-dataset-first_domain.zip""",
    """second_domain""": """https://huggingface.co/great-new-dataset-second_domain.zip""",
}





class 					snake_case   (   datasets.GeneratorBasedBuilder      ):





  """simple docstring"""




  _lowerCamelCase		   =  datasets.Version("1.1.0"      )

  # This is an example of a dataset with multiple configurations.
  # If you don't want/need to define several sub-sets in your dataset,
  # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

  # If you need to make complex sub-parts in the datasets with configurable options
  # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
  # BUILDER_CONFIG_CLASS = MyBuilderConfig

  # You will be able to load one or the other configurations in the following list with
  # data = datasets.load_dataset('my_dataset', 'first_domain')
  # data = datasets.load_dataset('my_dataset', 'second_domain')
  _lowerCamelCase		   =  [
      datasets.BuilderConfig(name="first_domain"      ,						version=lowercase      ,						description="This part of my dataset covers a first domain"      ),
      datasets.BuilderConfig(name="second_domain"      ,						version=lowercase      ,						description="This part of my dataset covers a second domain"      ),
  ]

  _lowerCamelCase		   =  "first_domain"  # It's not mandatory to have a default configuration. Just use one if it make sense.






  def   snake_case		(   self					):







   """simple docstring"""
   # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
   if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
    lowerCamelCase_								=  datasets.Features(
        {
            "sentence": datasets.Value("string"					),
            "option1": datasets.Value("string"					),
            "answer": datasets.Value("string"					)
            # These are the features of your dataset like images, labels ...
        }					)
   else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
    lowerCamelCase_								=  datasets.Features(
        {
            "sentence": datasets.Value("string"					),
            "option2": datasets.Value("string"					),
            "second_domain_answer": datasets.Value("string"					)
            # These are the features of your dataset like images, labels ...
        }					)
   return datasets.DatasetInfo(
       # This is the description that will appear on the datasets page.
       description=_DESCRIPTION      ,  features=UpperCamelCase      ,  homepage=_HOMEPAGE      ,  license=_LICENSE      ,  citation=_CITATION      ,  )






  def   snake_case		(   self      ,  UpperCamelCase					):







   """simple docstring"""
   # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
   # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

   # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
   # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
   # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
   lowerCamelCase_								=  _URLS[self.config.name]
   lowerCamelCase_								=  dl_manager.download_and_extract(UpperCamelCase					)
   return [
       datasets.SplitGenerator(
           name=datasets.Split.TRAIN      ,  gen_kwargs={
               "filepath": os.path.join(UpperCamelCase      ,  "train.jsonl"					),
               "split": "train",
           }      ,  ),
       datasets.SplitGenerator(
           name=datasets.Split.VALIDATION      ,  gen_kwargs={
               "filepath": os.path.join(UpperCamelCase      ,  "dev.jsonl"					),
               "split": "dev",
           }      ,  ),
       datasets.SplitGenerator(
           name=datasets.Split.TEST      ,  gen_kwargs={
               "filepath": os.path.join(UpperCamelCase      ,  "test.jsonl"					),
               "split": "test"
           }      ,  ),
   ]







  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
   # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
   with open(UpperCamelCase      ,  encoding="utf-8"					) as f:
    for key, row in enumerate(UpperCamelCase					):
     lowerCamelCase_								=  json.loads(UpperCamelCase					)
     if self.config.name == "first_domain":
      # Yields examples as (key, example) tuples
      yield key, {
          "sentence": data["sentence"],
          "option1": data["option1"],
          "answer": "" if split == "test" else data["answer"],
      }
     else:
      yield key, {
          "sentence": data["sentence"],
          "option2": data["option2"],
          "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
      }



