






"""simple docstring"""


import logging
from pathlib import Path
from typing import Any, List, Tuple

import yaml


# loading package files: https://stackoverflow.com/a/20885799
try:
   import importlib.resources as pkg_resources
except ImportError:
   # Try backported to PY<37 `importlib_resources`.
   import importlib_resources as pkg_resources

from . import resources


_UpperCamelCase				:    Optional[Any]     =						'https://github.com/huggingface/datasets/tree/main/src/datasets/utils'
_UpperCamelCase				:    Optional[int]     =						f'''{BASE_REF_URL}/{__file__}'''
_UpperCamelCase				:    List[str]     =						logging.getLogger(__name__)




def 			snake_case  (A_      :str      ):







  '''simple docstring'''

  a     :			Any				=   pkg_resources.read_text(A_	,			A_      )
  return yaml.safe_load(A_      ), f'''{BASE_REF_URL}/resources/{resource}'''


_UpperCamelCase ,     _UpperCamelCase				:    Tuple     =						load_yaml_resource('readme_structure.yaml')

_UpperCamelCase				:    int     =						[
    '[Needs More Information]',
    '[More Information Needed]',
    '(https://github.com/huggingface/datasets/blob/main/CONTRIBUTING.md#how-to-contribute-to-the-dataset-cards)',
]

# Dictionary representation of section/readme, error_list, warning_list
_UpperCamelCase				:    str     =						Tuple[dict, List[str], List[str]]






class 						snake_case  :





    def __init__(							self	:					List[Any]				,		A	:					str				,		A	:					str				,		A	:					List[str] = None				,		A	:					bool = False			):


      '''simple docstring'''




      a     :			Optional[Any]				=   name
      a     :			Dict				=   level
      a     :			Any				=   lines
      a     :			str				=   ''
      a     :			Union[str, Any]				=   True
      a     :			Optional[Any]				=   {}
      a     :			str				=   []
      a     :			List[Any]				=   []
      if self.lines is not None:
        self.parse(suppress_parsing_errors=A			)





    def 				lowerCamelCase__      (							self	:					str				,		A	:					bool = False			):


      '''simple docstring'''




      a     :			Union[str, Any]				=   ''
      a     :			Optional[int]				=   []
      a     :			int				=   False
      for line in self.lines:
        if line.strip(' \n'			) == "":
          continue
        elif line.strip(' \n'			)[:3] == "```":
          a     :			int				=   not code_start
        elif line.split()[0] == self.level + "#" and not code_start:
          if current_sub_level != "":
            a     :			Union[str, Any]				=   Section(A				,		self.level + '#'				,		A			)
            a     :			Union[str, Any]				=   []
          else:
            if current_lines != []:
              self.text += "".join(A			).strip()
              if self.text != "" and self.text not in FILLER_TEXT:
                a     :			Optional[Any]				=   False
              a     :			int				=   []

          a     :			List[str]				=   ' '.join(line.split()[1:]			).strip(' \n'			)
        else:
          current_lines.append(A			)
      else:
        if current_sub_level != "":
          if current_sub_level in self.content:
            self.parsing_error_list.append(
                F'''Multiple sections with the same heading `{current_sub_level}` have been found. Please keep only one of these sections.'''			)
          a     :			List[Any]				=   Section(A				,		self.level + '#'				,		A			)
        else:
          if current_lines != []:
            self.text += "".join(A			).strip()
            if self.text != "" and self.text not in FILLER_TEXT:
              a     :			Tuple				=   False

      if self.level == "" and not suppress_parsing_errors:
        if self.parsing_error_list != [] or self.parsing_warning_list != []:
          a     :			Dict				=   '\n'.join('-\t' + x for x in self.parsing_error_list + self.parsing_warning_list			)
          a     :			List[str]				=   F'''The following issues were found while parsing the README at `{self.name}`:\n''' + errors
          raise ValueError(A			)





    def 				lowerCamelCase__      (							self	:					str				,		A	:					dict			):


      '''simple docstring'''




      a     :			Any				=   []
      a     :			List[str]				=   []
      if structure["allow_empty"] is False:
        # If content is expected
        if self.is_empty_text and self.content == {}:
          # If no content is found, mention it in the error_list
          error_list.append(F'''Expected some content in section `{self.name}` but it is empty.'''			)

      if structure["allow_empty_text"] is False:
        # If some text is expected
        if self.is_empty_text:
          # If no text is found, mention it in the error_list
          error_list.append(
              F'''Expected some text in section `{self.name}` but it is empty (text in subsections are ignored).'''			)
        # Subsections Validation
      if structure["subsections"] is not None:
        # If subsections are expected
        if self.content == {}:
          # If no subsections are present
          a     :			int				=   [subsection['name'] for subsection in structure['subsections']]
          # Mention the expected values in the error_list
          error_list.append(
              F'''Section `{self.name}` expected the following subsections: {', '.join(['`'+x+'`' for x in values]			)}. Found \'None\'.'''			)
        else:
          # If some subsections are present
          a     :			Dict				=   [subsection['name'] for subsection in structure['subsections']]
          a     :			Optional[int]				=   False
          for idx, name in enumerate(A			):
            if name not in self.content:
              # If the expected subsection is not present
              error_list.append(F'''Section `{self.name}` is missing subsection: `{name}`.'''			)
              a     :			int				=   True
            else:
              # If the subsection is present, validate subsection, return the result
              # and concat the errors from subsection to section error_list

              # Skip sublevel validation if current level is `###`
              if self.level == "###":
                continue
              else:
                a,     a,     a     :			Tuple				=   self.content[name].validate(
                    structure['subsections'][idx]			)
              error_list += subsec_error_list
              warning_list += subsec_warning_list

          if has_missing_subsections:  # we only allow to have extra subsections if all the other ones are here
            for name in self.content:
              if name not in structure_names:
                # If an extra subsection is present
                warning_list.append(
                    F'''`{self.name}` has an extra subsection: `{name}`. Skipping further validation checks for this subsection as expected structure is unknown.'''			)
      if error_list:
        # If there are errors, do not return the dictionary as it is invalid
        return {}, error_list, warning_list
      else:
        return self.to_dict(), error_list, warning_list





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      return {
          "name": self.name,
          "text": self.text,
          "is_empty_text": self.is_empty_text,
          "subsections": [value.to_dict() for value in self.content.values()],
      }






class 						snake_case  (  UpperCAmelCase       ):  # Level 0





    def __init__(							self	:					Optional[int]				,		A	:					str				,		A	:					List[str]				,		A	:					dict = None				,		A	:					bool = False			):


      '''simple docstring'''




      super().__init__(name=A				,		level=''			)  # Not using lines here as we need to use a child class parse
      a     :			Optional[int]				=   structure
      a     :			Any				=   -2
      a     :			Any				=   0
      a     :			Union[str, Any]				=   lines
      if self.lines is not None:
        self.parse(suppress_parsing_errors=A			)





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      if self.structure is None:
        a,     a,     a     :			Dict				=   self._validate(A			)
      else:
        a,     a,     a     :			Optional[Any]				=   self._validate(self.structure			)
      if error_list != [] or warning_list != []:
        a     :			str				=   '\n'.join(['-\t' + x for x in error_list + warning_list]			)
        a     :			Tuple				=   F'''The following issues were found for the README at `{self.name}`:\n''' + errors
        raise ValueError(A			)





    @classmethod
    def 				lowerCamelCase__      (							cls	:					Tuple				,		A	:					Path				,		A	:					dict = None				,		A	:					bool = False			):


      '''simple docstring'''




      with open(A				,		encoding='utf-8'			) as f:
        a     :			Union[str, Any]				=   f.readlines()
      return cls(A				,		A				,		A				,		suppress_parsing_errors=A			)





    @classmethod
    def 				lowerCamelCase__      (							cls	:					str				,		A	:					str				,		A	:					dict = None				,		A	:					str = "root"				,		A	:					bool = False			):


      '''simple docstring'''




      a     :			Dict				=   string.split('\n'			)
      return cls(A				,		A				,		A				,		suppress_parsing_errors=A			)





    def 				lowerCamelCase__      (							self	:					List[Any]				,		A	:					bool = False			):


      '''simple docstring'''




      a     :			List[str]				=   0

      for line in self.lines:
        self.yaml_tags_line_count += 1
        if line.strip(' \n'			) == "---":
          self.tag_count += 1
          if self.tag_count == 2:
            break
        line_count += 1
      if self.tag_count == 2:
        a     :			Union[str, Any]				=   self.lines[line_count + 1 :]  # Get the last + 1 th item.
      else:
        a     :			Optional[Any]				=   self.lines[self.tag_count :]
      super().parse(suppress_parsing_errors=A			)





    def __str__(							self	:					Any			):


      '''simple docstring'''




      return str(self.to_dict()			)





    def 				lowerCamelCase__      (							self	:					List[str]				,		A	:					Tuple			):


      '''simple docstring'''




      a     :			Optional[int]				=   []
      a     :			int				=   []
      if self.yaml_tags_line_count == 0:
        warning_list.append('Empty YAML markers are present in the README.'			)
      elif self.tag_count == 0:
        warning_list.append('No YAML markers are present in the README.'			)
      elif self.tag_count == 1:
        warning_list.append('Only the start of YAML tags present in the README.'			)
      # Check how many first level sections are present.
      a     :			Any				=   len(self.content.keys()			)
      if num_first_level_keys > 1:
        # If more than one, add to the error list, continue
        error_list.append(
            F'''The README has several first-level headings: {', '.join(['`'+x+'`' for x in list(self.content.keys()			)]			)}. Only one heading is expected. Skipping further validation for this README.'''			)
      elif num_first_level_keys < 1:
        # If less than one, append error.
        error_list.append(
            'The README has no first-level headings. One heading is expected. Skipping further validation for this README.'			)

      else:
        # If one exactly
        a     :			Union[str, Any]				=   list(self.content.keys()			)[0]  # Get the key
        if start_key.startswith('Dataset Card for'			):  # Check correct start
          # If the starting is correct, validate all the sections
          a,     a,     a     :			Dict				=   self.content[start_key].validate(
              readme_structure['subsections'][0]			)
          error_list += sec_error_list
          warning_list += sec_warning_list
        else:
          # If not found, append error
          error_list.append(
              'No first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.'			)
      if error_list:
        # If there are errors, do not return the dictionary as it is invalid
        return {}, error_list, warning_list
      else:
        return self.to_dict(), error_list, warning_list


if __name__ == "__main__":
   from argparse import ArgumentParser

   _UpperCamelCase				:    Union[str, Any]     =						ArgumentParser(usage='Validate the content (excluding YAML tags) of a README.md file.')
   ap.add_argument('readme_filepath')
   _UpperCamelCase				:    int     =						ap.parse_args()
   _UpperCamelCase				:    Tuple     =						Path(args.readme_filepath)
   _UpperCamelCase				:    int     =						ReadMe.from_readme(readme_filepath)












"""simple docstring"""


import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
   from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
   from PIL import Image

   from transformers import SwinaSRImageProcessor






class 						snake_case  :





    def __init__(							self	:					Tuple				,		A	:					Any				,		A	:					List[Any]=1_3				,		A	:					Union[str, Any]=3_2				,		A	:					Optional[Any]=1				,		A	:					Union[str, Any]=3				,		A	:					List[str]=1_6				,		A	:					Optional[Any]=[1, 2, 1]				,		A	:					Any=[2, 2, 4]				,		A	:					int=2				,		A	:					List[str]=2.0				,		A	:					Dict=True				,		A	:					Union[str, Any]=0.0				,		A	:					Union[str, Any]=0.0				,		A	:					Optional[int]=0.1				,		A	:					Optional[int]="gelu"				,		A	:					Any=False				,		A	:					Dict=True				,		A	:					int=0.02				,		A	:					Tuple=1E-5				,		A	:					List[str]=True				,		A	:					List[str]=None				,		A	:					str=False				,		A	:					Any=2				,		):


      '''simple docstring'''




      a     :			Tuple				=   parent
      a     :			Union[str, Any]				=   batch_size
      a     :			Tuple				=   image_size
      a     :			List[str]				=   patch_size
      a     :			Union[str, Any]				=   num_channels
      a     :			str				=   embed_dim
      a     :			int				=   depths
      a     :			Tuple				=   num_heads
      a     :			Any				=   window_size
      a     :			List[Any]				=   mlp_ratio
      a     :			str				=   qkv_bias
      a     :			Any				=   hidden_dropout_prob
      a     :			List[Any]				=   attention_probs_dropout_prob
      a     :			int				=   drop_path_rate
      a     :			List[Any]				=   hidden_act
      a     :			Union[str, Any]				=   use_absolute_embeddings
      a     :			Dict				=   patch_norm
      a     :			Optional[Any]				=   layer_norm_eps
      a     :			Dict				=   initializer_range
      a     :			Optional[Any]				=   is_training
      a     :			str				=   scope
      a     :			List[Any]				=   use_labels
      a     :			Union[str, Any]				=   upscale

      # here we set some attributes to make tests pass
      a     :			str				=   len(A			)
      a     :			List[Any]				=   embed_dim
      a     :			List[Any]				=   (image_size // patch_size) ** 2





    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




      a     :			List[Any]				=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      a     :			List[str]				=   None
      if self.use_labels:
        a     :			Tuple				=   ids_tensor([self.batch_size]				,		self.type_sequence_label_size			)

      a     :			Any				=   self.get_config()

      return config, pixel_values, labels





    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




      return SwinaSRConfig(
          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				,		upscale=self.upscale				,		)





    def 				lowerCamelCase__      (							self	:					Union[str, Any]				,		A	:					Dict				,		A	:					Union[str, Any]				,		A	:					List[str]			):


      '''simple docstring'''




      a     :			List[Any]				=   SwinaSRModel(config=A			)
      model.to(A			)
      model.eval()
      a     :			Optional[int]				=   model(A			)

      self.parent.assertEqual(
          result.last_hidden_state.shape				,		(self.batch_size, self.embed_dim, self.image_size, self.image_size)			)





    def 				lowerCamelCase__      (							self	:					List[str]				,		A	:					Tuple				,		A	:					str				,		A	:					Tuple			):


      '''simple docstring'''




      a     :			Optional[Any]				=   SwinaSRForImageSuperResolution(A			)
      model.to(A			)
      model.eval()
      a     :			List[str]				=   model(A			)

      a     :			Any				=   self.image_size * self.upscale
      self.parent.assertEqual(
          result.reconstruction.shape				,		(self.batch_size, self.num_channels, expected_image_size, expected_image_size)			)





    def 				lowerCamelCase__      (							self	:					Union[str, Any]			):


      '''simple docstring'''




      a     :			Tuple				=   self.prepare_config_and_inputs()
      a,     a,     a     :			Union[str, Any]				=   config_and_inputs
      a     :			List[str]				=   {'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 						snake_case  (  UpperCAmelCase   , UpperCAmelCase   , unittest.TestCase       ):
    __magic_name__         =     (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
    __magic_name__         =     {'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

    __magic_name__         =     False
    __magic_name__         =     False
    __magic_name__         =     False
    __magic_name__         =     False
    __magic_name__         =     False





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a     :			List[str]				=   SwinaSRModelTester(self			)
      a     :			int				=   ConfigTester(self				,		config_class=A				,		embed_dim=3_7			)





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      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 				lowerCamelCase__      (							self	:					List[Any]			):


      '''simple docstring'''




      a     :			str				=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A			)





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      a     :			Any				=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_super_resolution(*A			)





    @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'			)
    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not use inputs_embeds'			)
    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not support training yet'			)
    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not support training yet'			)
    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      pass





    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      a,     a     :			Optional[int]				=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a     :			Union[str, Any]				=   model_class(A			)
        self.assertIsInstance(model.get_input_embeddings()				,		(nn.Module)			)
        a     :			Optional[int]				=   model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(A				,		nn.Linear			)			)





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a,     a     :			int				=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a     :			Dict				=   model_class(A			)
        a     :			Union[str, Any]				=   inspect.signature(model.forward			)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        a     :			Any				=   [*signature.parameters.keys()]

        a     :			Tuple				=   ['pixel_values']
        self.assertListEqual(arg_names[:1]				,		A			)





    @slow
    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a     :			Optional[int]				=   SwinaSRModel.from_pretrained(A			)
        self.assertIsNotNone(A			)





    def 				lowerCamelCase__      (							self	:					Dict			):


      '''simple docstring'''




      a,     a     :			str				=   self.model_tester.prepare_config_and_inputs_for_common()

      a     :			int				=   _config_zero_init(A			)
      for model_class in self.all_model_classes:
        a     :			List[str]				=   model_class(config=A			)
        for name, param in model.named_parameters():
          if "logit_scale" in name:
            continue
          if param.requires_grad:
            self.assertIn(
                ((param.data.mean() * 1E9).round() / 1E9).item()				,		[0.0, 1.0]				,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''				,		)





    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      a,     a     :			Union[str, Any]				=   self.model_tester.prepare_config_and_inputs_for_common()
      a     :			List[str]				=   True

      for model_class in self.all_model_classes:
        a     :			Dict				=   True
        a     :			int				=   False
        a     :			str				=   True
        a     :			Optional[int]				=   model_class(A			)
        model.to(A			)
        model.eval()
        with torch.no_grad():
          a     :			Tuple				=   model(**self._prepare_for_class(A				,		A			)			)
        a     :			Optional[Any]				=   outputs.attentions
        a     :			int				=   len(self.model_tester.depths			)
        self.assertEqual(len(A			)				,		A			)

        # check that output_attentions also work using config
        del inputs_dict["output_attentions"]
        a     :			List[str]				=   True
        a     :			List[Any]				=   config.window_size**2
        a     :			List[str]				=   model_class(A			)
        model.to(A			)
        model.eval()
        with torch.no_grad():
          a     :			str				=   model(**self._prepare_for_class(A				,		A			)			)
        a     :			int				=   outputs.attentions
        self.assertEqual(len(A			)				,		A			)

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

        # Check attention is always last and order is fine
        a     :			List[str]				=   True
        a     :			List[Any]				=   True
        a     :			str				=   model_class(A			)
        model.to(A			)
        model.eval()
        with torch.no_grad():
          a     :			List[Any]				=   model(**self._prepare_for_class(A				,		A			)			)

        self.assertEqual(out_len + 1				,		len(A			)			)

        a     :			Tuple				=   outputs.attentions

        self.assertEqual(len(A			)				,		A			)

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






@require_vision
@require_torch
@slow
class 						snake_case  (  unittest.TestCase       ):





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a     :			Optional[int]				=   SwinaSRImageProcessor()
      a     :			Optional[int]				=   SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'			).to(A			)

      a     :			str				=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
      a     :			Union[str, Any]				=   processor(images=A				,		return_tensors='pt'			).to(A			)

      # forward pass
      with torch.no_grad():
        a     :			Tuple				=   model(**A			)

      # verify the logits
      a     :			Optional[int]				=   torch.Size([1, 3, 9_7_6, 1_2_9_6]			)
      self.assertEqual(outputs.reconstruction.shape				,		A			)
      a     :			Tuple				=   torch.tensor(
          [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]			).to(A			)
      self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]				,		A				,		atol=1E-4			)			)




