





import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING





def      lowerCAmelCase_ (       __a		)     ->		int:







  """simple docstring"""





  return 1.0 / (1.0 + np.exp(-_outputs		))





def      lowerCAmelCase_ (       __a		)     ->		Tuple:







  """simple docstring"""





  lowerCamelCase__:      List[str]			  =np.max(_outputs	,    axis=-1	,    keepdims=_SCREAMING_SNAKE_CASE		)
  lowerCamelCase__:      List[Any]			  =np.exp(_outputs - maxes		)
  return shifted_exp / shifted_exp.sum(axis=-1	,    keepdims=_SCREAMING_SNAKE_CASE		)



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			"""sigmoid"""
 lowercase_		=			"""softmax"""
 lowercase_		=			"""none"""



@add_end_docstrings(
    __SCREAMING_SNAKE_CASE    ,							R"\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `\"sigmoid\"`: Applies the sigmoid function on the output.\n            - `\"softmax\"`: Applies the softmax function on the output.\n            - `\"none\"`: Does not apply any function on the output.\n    "    ,							)
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			False
 lowercase_		=			ClassificationFunction.NONE

 def __init__(self				:   Optional[Any]       , **UpperCAmelCase_				:   Tuple)       ->Any:



   '''simple docstring'''



   super().__init__(**__UpperCAmelCase)

   self.check_model_type(
       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
       if self.framework == "tf"
       else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING)

 def 							SCREAMING_SNAKE_CASE_					(self				:   int       , UpperCAmelCase_				:   Any=None       , UpperCAmelCase_				:   Optional[int]=None       , UpperCAmelCase_				:   int=""       , **UpperCAmelCase_				:   Dict)       ->int:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =tokenizer_kwargs

   lowerCamelCase__:      List[Any]			  ={}
   if hasattr(self.model.config       , "return_all_scores") and return_all_scores is None:
     lowerCamelCase__:      List[Any]			  =self.model.config.return_all_scores

   if isinstance(__UpperCAmelCase       , __UpperCAmelCase) or top_k is None:
     lowerCamelCase__:      int			  =top_k
     lowerCamelCase__:      Dict			  =False
   elif return_all_scores is not None:
     warnings.warn(
         "`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"
         " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."       , __UpperCAmelCase       , )
     if return_all_scores:
       lowerCamelCase__:      List[Any]			  =None
     else:
       lowerCamelCase__:      Union[str, Any]			  =1

   if isinstance(__UpperCAmelCase       , __UpperCAmelCase):
     lowerCamelCase__:      Union[str, Any]			  =ClassificationFunction[function_to_apply.upper()]

   if function_to_apply is not None:
     lowerCamelCase__:      List[Any]			  =function_to_apply
   return preprocess_params, {}, postprocess_params

 def __call__(self				:   Dict       , *UpperCAmelCase_				:   str       , **UpperCAmelCase_				:   Any)       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =super().__call__(*__UpperCAmelCase       , **__UpperCAmelCase)
   # TODO try and retrieve it in a nicer way from _sanitize_parameters.
   lowerCamelCase__:      Optional[Any]			  ='top_k' not in kwargs
   if isinstance(args[0]       , __UpperCAmelCase) and _legacy:
     # This pipeline is odd, and return a list when single item is run
     return [result]
   else:
     return result

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any]       , UpperCAmelCase_				:   Union[str, Any]       , **UpperCAmelCase_				:   int)       ->str:



   '''simple docstring'''



   lowerCamelCase__:      Dict			  =self.framework
   if isinstance(__UpperCAmelCase       , __UpperCAmelCase):
     return self.tokenizer(**__UpperCAmelCase       , return_tensors=__UpperCAmelCase       , **__UpperCAmelCase)
   elif isinstance(__UpperCAmelCase       , __UpperCAmelCase) and len(__UpperCAmelCase) == 1 and isinstance(inputs[0]       , __UpperCAmelCase) and len(inputs[0]) == 2:
     # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
     return self.tokenizer(
         text=inputs[0][0]       , text_pair=inputs[0][1]       , return_tensors=__UpperCAmelCase       , **__UpperCAmelCase)
   elif isinstance(__UpperCAmelCase       , __UpperCAmelCase):
     # This is likely an invalid usage of the pipeline attempting to pass text pairs.
     raise ValueError(
         "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
         " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair.")
   return self.tokenizer(__UpperCAmelCase       , return_tensors=__UpperCAmelCase       , **__UpperCAmelCase)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Union[str, Any]       , UpperCAmelCase_				:   Optional[int])       ->str:



   '''simple docstring'''



   return self.model(**__UpperCAmelCase)







 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   str       , UpperCAmelCase_				:   str=None       , UpperCAmelCase_				:   Any=1       , UpperCAmelCase_				:   List[Any]=True)       ->List[str]:



   '''simple docstring'''



   if function_to_apply is None:
     if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
       lowerCamelCase__:      str			  =ClassificationFunction.SIGMOID
     elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
       lowerCamelCase__:      int			  =ClassificationFunction.SOFTMAX
     elif hasattr(self.model.config       , "function_to_apply") and function_to_apply is None:
       lowerCamelCase__:      Optional[Any]			  =self.model.config.function_to_apply
     else:
       lowerCamelCase__:      Dict			  =ClassificationFunction.NONE

   lowerCamelCase__:      int			  =model_outputs['logits'][0]
   lowerCamelCase__:      Union[str, Any]			  =outputs.numpy()

   if function_to_apply == ClassificationFunction.SIGMOID:
     lowerCamelCase__:      Dict			  =sigmoid(__UpperCAmelCase)
   elif function_to_apply == ClassificationFunction.SOFTMAX:
     lowerCamelCase__:      int			  =softmax(__UpperCAmelCase)
   elif function_to_apply == ClassificationFunction.NONE:
     lowerCamelCase__:      Tuple			  =outputs
   else:
     raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}""")

   if top_k == 1 and _legacy:
     return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

   lowerCamelCase__:      Any			  =[
       {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__UpperCAmelCase)
   ]
   if not _legacy:
     dict_scores.sort(key=lambda UpperCAmelCase_: x["score"]       , reverse=__UpperCAmelCase)
     if top_k is not None:
       lowerCamelCase__:      List[str]			  =dict_scores[:top_k]
   return dict_scores








"""simple docstring"""





from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml






class 					_lowerCAmelCase   (     yaml.SafeLoader       ):
       """simple docstring"""




       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:List[Any]											=							[self.constructed_objects[key_node] for key_node, _ in node.value]
         lowerCAmelCase__			:str											=							[tuple(__UpperCAmelCase      ) if isinstance(__UpperCAmelCase    , __UpperCAmelCase      ) else key for key in keys]
         lowerCAmelCase__			:Optional[int]											=							Counter(__UpperCAmelCase      )
         lowerCAmelCase__			:int											=							[key for key in counter if counter[key] > 1]
         if duplicate_keys:
           raise TypeError(F"Got duplicate yaml keys: {duplicate_keys}"      )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase=False      ):



         '''simple docstring'''

         lowerCAmelCase__			:Union[str, Any]											=							super().construct_mapping(__UpperCAmelCase    , deep=__UpperCAmelCase      )
         self._check_no_duplicates_on_constructed_node(__UpperCAmelCase      )
         return mapping






def  __A   (_SCREAMING_SNAKE_CASE			)					->Tuple[Optional[str], str]:





  """simple docstring"""


  lowerCAmelCase__			:Optional[Any]											=							list(readme_content.splitlines()			)
  if full_content and full_content[0] == "---" and "---" in full_content[1:]:
    lowerCAmelCase__			:Optional[int]											=							full_content[1:].index('---'			) + 1
    lowerCAmelCase__			:Union[str, Any]											=							'\n'.join(full_content[1:sep_idx]			)
    return yamlblock, "\n".join(full_content[sep_idx + 1 :]			)

  return None, "\n".join(_SCREAMING_SNAKE_CASE			)






class 					_lowerCAmelCase   (     a       ):
       """simple docstring"""




       __magic_name__     :List[str]		  =					{"""train_eval_index"""}  # train-eval-index in the YAML metadata






       @classmethod
       def      snake_case						(    cls    , __UpperCAmelCase      ):



         '''simple docstring'''

         with open(__UpperCAmelCase    , encoding='utf-8'      ) as readme_file:
           lowerCAmelCase__							,				lowerCAmelCase__			:Union[str, Any]											=							_split_yaml_from_readme(readme_file.read()      )
         if yaml_string is not None:
           return cls.from_yaml_string(__UpperCAmelCase      )
         else:
           return cls()






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         if path.exists():
           with open(__UpperCAmelCase    , encoding='utf-8'      ) as readme_file:
             lowerCAmelCase__			:Optional[Any]											=							readme_file.read()
         else:
           lowerCAmelCase__			:Union[str, Any]											=							None
         lowerCAmelCase__			:Union[str, Any]											=							self._to_readme(__UpperCAmelCase      )
         with open(__UpperCAmelCase    , 'w'    , encoding='utf-8'      ) as readme_file:
           readme_file.write(__UpperCAmelCase      )






       def      snake_case						(    self    , __UpperCAmelCase = None      ):



         '''simple docstring'''

         if readme_content is not None:
           lowerCAmelCase__							,				lowerCAmelCase__			:Optional[int]											=							_split_yaml_from_readme(__UpperCAmelCase      )
           lowerCAmelCase__			:Optional[Any]											=							'---\n' + self.to_yaml_string() + '---\n' + content
         else:
           lowerCAmelCase__			:str											=							'---\n' + self.to_yaml_string() + '---\n'
         return full_content






       @classmethod
       def      snake_case						(    cls    , __UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Dict											=							yaml.load(__UpperCAmelCase    , Loader=_NoDuplicateSafeLoader      ) or {}

         # Convert the YAML keys to DatasetMetadata fields
         lowerCAmelCase__			:int											=							{
             (key.replace('-'    , '_'      ) if key.replace('-'    , '_'      ) in cls._FIELDS_WITH_DASHES else key): value
             for key, value in metadata_dict.items()
         }
         return cls(**__UpperCAmelCase      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         return yaml.safe_dump(
             {
                 (key.replace('_'    , '-'      ) if key in self._FIELDS_WITH_DASHES else key): value
                 for key, value in self.items()
             }    , sort_keys=__UpperCAmelCase    , allow_unicode=__UpperCAmelCase    , encoding='utf-8'    , ).decode('utf-8'      )






__A											=		{
    """image-classification""": [],
    """translation""": [],
    """image-segmentation""": [],
    """fill-mask""": [],
    """automatic-speech-recognition""": [],
    """token-classification""": [],
    """sentence-similarity""": [],
    """audio-classification""": [],
    """question-answering""": [],
    """summarization""": [],
    """zero-shot-classification""": [],
    """table-to-text""": [],
    """feature-extraction""": [],
    """other""": [],
    """multiple-choice""": [],
    """text-classification""": [],
    """text-to-image""": [],
    """text2text-generation""": [],
    """zero-shot-image-classification""": [],
    """tabular-classification""": [],
    """tabular-regression""": [],
    """image-to-image""": [],
    """tabular-to-text""": [],
    """unconditional-image-generation""": [],
    """text-retrieval""": [],
    """text-to-speech""": [],
    """object-detection""": [],
    """audio-to-audio""": [],
    """text-generation""": [],
    """conversational""": [],
    """table-question-answering""": [],
    """visual-question-answering""": [],
    """image-to-text""": [],
    """reinforcement-learning""": [],
    """voice-activity-detection""": [],
    """time-series-forecasting""": [],
    """document-question-answering""": [],
}


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

  __A											=		ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""")
  ap.add_argument("""readme_filepath""")
  __A											=		ap.parse_args()

  __A											=		Path(args.readme_filepath)
  __A											=		DatasetMetadata.from_readme(readme_filepath)
  print(dataset_metadata)
  dataset_metadata.to_readme(readme_filepath)
