"""simple docstring"""



import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union

class SCREAMING_SNAKE_CASE     (    enum.Enum	):







 """simple docstring"""


 a_       :	Any  			="timm"
 a_       :	Union[str, Any]  			="transformers"





def   _lowerCamelCase ( UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__					)							->     List[str]:


   '''simple docstring'''


   if stage_names is None:
      raise ValueError('Stage_names must be set for transformers backbones'					)

   if out_features is not None:
      if not isinstance(UpperCAmelCase__,(list,)					):
         raise ValueError(f'''out_features must be a list {type(UpperCAmelCase__					)}'''					)
      if any(feat not in stage_names for feat in out_features					):
         raise ValueError(f'''out_features must be a subset of stage_names: {stage_names} got {out_features}'''					)

   if out_indices is not None:
      if not isinstance(UpperCAmelCase__,(list, tuple)					):
         raise ValueError(f'''out_indices must be a list or tuple, got {type(UpperCAmelCase__					)}'''					)
      if any(idx >= len(UpperCAmelCase__					) for idx in out_indices					):
         raise ValueError('out_indices must be valid indices for stage_names {stage_names}, got {out_indices}'					)

   if out_features is not None and out_indices is not None:
      if len(UpperCAmelCase__					) != len(UpperCAmelCase__					):
         raise ValueError('out_features and out_indices should have the same length if both are set'					)
      if out_features != [stage_names[idx] for idx in out_indices]:
         raise ValueError('out_features and out_indices should correspond to the same stages if both are set'					)





def   _lowerCamelCase ( UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,)							->     Dict:


   '''simple docstring'''


   if out_indices is None and out_features is None:
      a__     				=		[len(UpperCAmelCase__					) - 1]
      a__     				=		[stage_names[-1]]
   elif out_indices is None and out_features is not None:
      a__     				=		[stage_names.index(UpperCAmelCase__					) for layer in out_features]
   elif out_features is None and out_indices is not None:
      a__     				=		[stage_names[idx] for idx in out_indices]
   return out_features, out_indices





def   _lowerCamelCase ( UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,)							->     Tuple[List[str], List[int]]:


   '''simple docstring'''


   verify_out_features_out_indices(out_features=UpperCAmelCase__,out_indices=UpperCAmelCase__,stage_names=UpperCAmelCase__					)
   a__				,       a__     				=		_align_output_features_output_indices(
       out_features=UpperCAmelCase__,out_indices=UpperCAmelCase__,stage_names=UpperCAmelCase__					)
   # Verify that the aligned out_features and out_indices are valid
   verify_out_features_out_indices(out_features=UpperCAmelCase__,out_indices=UpperCAmelCase__,stage_names=UpperCAmelCase__					)
   return output_features, output_indices

class SCREAMING_SNAKE_CASE     :







 """simple docstring"""


 a_       :	Optional[BackboneType]  			=None


 def        _lowerCAmelCase				(   self		:      Union[str, Any]					,   _snake_case		:      Dict				)				->			None:




    '''simple docstring'''






    if getattr(self					,   '_backbone'					,   _snake_case				) is None:
       raise ValueError('self._backbone must be set before calling _init_timm_backbone'				)

    # These will diagree with the defaults for the transformers models e.g. for resnet50
    # the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
    # the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
    a__     				=		[stage['module'] for stage in self._backbone.feature_info.info]
    a__     				=		[stage['num_chs'] for stage in self._backbone.feature_info.info]
    a__     				=		self._backbone.feature_info.out_indices
    a__     				=		self._backbone.feature_info.module_name()

    # We verify the out indices and out features are valid
    verify_out_features_out_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=self.stage_names				)
    a__				,       a__     				=		out_features, out_indices


 def        _lowerCAmelCase				(   self		:      List[str]					,   _snake_case		:      Any				)				->			None:




    '''simple docstring'''






    a__     				=		getattr(_snake_case					,   'stage_names'				)
    a__     				=		getattr(_snake_case					,   'out_features'					,   _snake_case				)
    a__     				=		getattr(_snake_case					,   'out_indices'					,   _snake_case				)

    a__     				=		stage_names
    a__				,       a__     				=		get_aligned_output_features_output_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=_snake_case				)
    # Number of channels for each stage. This is set in the transformer backbone model init
    a__     				=		None


 def        _lowerCAmelCase				(   self		:      str					,   _snake_case		:      int				)				->			None:




    '''simple docstring'''






    a__     				=		config

    a__     				=		getattr(_snake_case					,   'use_timm_backbone'					,   _snake_case				)
    a__     				=		BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

    if self.backbone_type == BackboneType.TIMM:
       self._init_timm_backbone(_snake_case				)
    elif self.backbone_type == BackboneType.TRANSFORMERS:
       self._init_transformers_backbone(_snake_case				)
    else:
       raise ValueError(F'''backbone_type {self.backbone_type} not supported.'''				)


 @property
 def        _lowerCAmelCase				(   self		:      List[Any]				)				->			Tuple:




    '''simple docstring'''






    return self._out_features


 @out_features.setter
 def        _lowerCAmelCase				(   self		:      List[Any]					,   _snake_case		:      List[str]				)				->			Tuple:




    '''simple docstring'''






    a__				,       a__     				=		get_aligned_output_features_output_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=self.stage_names				)


 @property
 def        _lowerCAmelCase				(   self		:      str				)				->			Any:




    '''simple docstring'''






    return self._out_indices


 @out_indices.setter
 def        _lowerCAmelCase				(   self		:      Union[str, Any]					,   _snake_case		:      Union[Tuple[int], List[int]]				)				->			Optional[int]:




    '''simple docstring'''






    a__				,       a__     				=		get_aligned_output_features_output_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=self.stage_names				)


 @property
 def        _lowerCAmelCase				(   self		:      Tuple				)				->			Any:




    '''simple docstring'''






    return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names				)}


 @property
 def        _lowerCAmelCase				(   self		:      str				)				->			List[Any]:




    '''simple docstring'''






    return [self.out_feature_channels[name] for name in self.out_features]


 def        _lowerCAmelCase				(   self		:      Tuple					,   *_snake_case		:      str					,   **_snake_case		:      List[Any]				)				->			int:




    '''simple docstring'''






    a__     				=		dict(inspect.signature(self.forward				).parameters				)
    a__     				=		{k: v for k, v in kwargs.items() if k in signature}
    return self(*_snake_case					,   **_snake_case				)


 def        _lowerCAmelCase				(   self		:      List[str]					,   _snake_case		:      str					,   _snake_case		:      Optional[bool] = None					,   _snake_case		:      Optional[bool] = None					,   _snake_case		:      Optional[bool] = None					,   )				->			Optional[Any]:




    '''simple docstring'''






    raise NotImplementedError('This method should be implemented by the derived class.'				)



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




    '''simple docstring'''






    a__     				=		super().to_dict()
    a__     				=		output.pop('_out_features'				)
    a__     				=		output.pop('_out_indices'				)
    return output

class SCREAMING_SNAKE_CASE     :







 """simple docstring"""


 @property
 def        _lowerCAmelCase				(   self		:      Optional[int]				)				->			Optional[Any]:




    '''simple docstring'''






    return self._out_features


 @out_features.setter
 def        _lowerCAmelCase				(   self		:      Union[str, Any]					,   _snake_case		:      List[str]				)				->			List[Any]:




    '''simple docstring'''






    a__				,       a__     				=		get_aligned_output_features_output_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=self.stage_names				)


 @property
 def        _lowerCAmelCase				(   self		:      Tuple				)				->			Optional[Any]:




    '''simple docstring'''






    return self._out_indices


 @out_indices.setter
 def        _lowerCAmelCase				(   self		:      Optional[Any]					,   _snake_case		:      Union[Tuple[int], List[int]]				)				->			Union[str, Any]:




    '''simple docstring'''






    a__				,       a__     				=		get_aligned_output_features_output_indices(
        out_features=_snake_case					,   out_indices=_snake_case					,   stage_names=self.stage_names				)



 def        _lowerCAmelCase				(   self		:      Any				)				->			List[Any]:




    '''simple docstring'''






    a__     				=		super().to_dict()
    a__     				=		output.pop('_out_features'				)
    a__     				=		output.pop('_out_indices'				)
    return output



"""simple docstring"""



import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata





def   _lowerCamelCase ( UpperCAmelCase__					)							->     str:


   '''simple docstring'''


   a__     				=		min(re.search('^ +',UpperCAmelCase__					).end() if t.startswith(' '					) else 0 for t in string.splitlines()					)
   return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(UpperCAmelCase__					)]					)


__magic_name__    				=					"\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

__magic_name__    				=					"\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"


__magic_name__    				=					"\\n# Begin of markdown\n\nSome cool dataset card\n"




class SCREAMING_SNAKE_CASE     (    unittest.TestCase	):







 """simple docstring"""


 def        _lowerCAmelCase				(   self		:      Tuple				)				->			Dict:




    '''simple docstring'''






    with tempfile.TemporaryDirectory() as tmp_dir:
       a__     				=		Path(_snake_case				) / 'README.md'
       with open(_snake_case					,   'w+'				) as readme_file:
          readme_file.write(_snake_case				)
       a__     				=		DatasetMetadata.from_readme(_snake_case				)
       self.assertDictEqual(_snake_case					,   {'language': ['zh', 'en'], 'task_ids': ['sentiment-classification']}				)

       with open(_snake_case					,   'w+'				) as readme_file:
          readme_file.write(_snake_case				)
       a__     				=		DatasetMetadata.from_readme(_snake_case				)
       self.assertDictEqual(_snake_case					,   {}				)

       with open(_snake_case					,   'w+'				) as readme_file:
          readme_file.write(_snake_case				)
       a__     				=		DatasetMetadata.from_readme(_snake_case				)
       self.assertEqual(_snake_case					,   {}				)



 def        _lowerCAmelCase				(   self		:      List[Any]				)				->			List[Any]:




    '''simple docstring'''






    a__     				=		_dedent(
        '\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            '				)
    assert DatasetMetadata.from_yaml_string(_snake_case				)

    a__     				=		_dedent(
        '\\n            annotations_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            task_ids:\n            - open-domain-qa\n            '				)
    with self.assertRaises(_snake_case				):
       DatasetMetadata.from_yaml_string(_snake_case				)

    a__     				=		_dedent(
        '\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - text-classification\n            task_ids:\n            - multi-class-classification\n            paperswithcode_id:\n            - squad\n            configs:\n            - en\n            train-eval-index:\n            - config: en\n              task: text-classification\n              task_id: multi_class_classification\n              splits:\n                train_split: train\n                eval_split: test\n              col_mapping:\n                text: text\n                label: target\n              metrics:\n                - type: accuracy\n                  name: Accuracy\n            extra_gated_prompt: |\n              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:\n              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:\n              1. Researcher shall use the Database only for non-commercial research and educational purposes.\n            extra_gated_fields:\n              Company: text\n              Country: text\n              I agree to use this model for non-commerical use ONLY: checkbox\n            '				)
    assert DatasetMetadata.from_yaml_string(_snake_case				)


