
"""simple docstring"""






import copy
from collections import OrderedDict
from typing import Dict, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowerCamelCase__ :       Tuple						     =			logging.get_logger(__name__)

lowerCamelCase__ :       Dict						     =			{
    "facebook/detr-resnet-50": "https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json",
    # See all DETR models at https://huggingface.co/models?filter=detr
}




class 				lowercase__(				__lowerCAmelCase   ):
	'''simple docstring'''

	UpperCamelCase				=  """detr"""
	UpperCamelCase				=  ["""past_key_values"""]
	UpperCamelCase				=  {
	    """hidden_size""": """d_model""",
	    """num_attention_heads""": """encoder_attention_heads""",
	}





	def __init__(						self    :Any		, lowerCamelCase_    :Dict=True		, lowerCamelCase_    :List[Any]=None		, lowerCamelCase_    :Any=3		, lowerCamelCase_    :Optional[Any]=1_00		, lowerCamelCase_    :int=6		, lowerCamelCase_    :Optional[Any]=20_48		, lowerCamelCase_    :Union[str, Any]=8		, lowerCamelCase_    :str=6		, lowerCamelCase_    :List[str]=20_48		, lowerCamelCase_    :Optional[int]=8		, lowerCamelCase_    :str=0.0		, lowerCamelCase_    :List[Any]=0.0		, lowerCamelCase_    :Any=True		, lowerCamelCase_    :Optional[Any]="relu"		, lowerCamelCase_    :Tuple=2_56		, lowerCamelCase_    :Any=0.1		, lowerCamelCase_    :Optional[Any]=0.0		, lowerCamelCase_    :Dict=0.0		, lowerCamelCase_    :Dict=0.0_2		, lowerCamelCase_    :Dict=1.0		, lowerCamelCase_    :Optional[int]=False		, lowerCamelCase_    :Dict="sine"		, lowerCamelCase_    :Dict="resnet50"		, lowerCamelCase_    :Optional[int]=True		, lowerCamelCase_    :Tuple=False		, lowerCamelCase_    :str=1		, lowerCamelCase_    :int=5		, lowerCamelCase_    :Optional[int]=2		, lowerCamelCase_    :List[Any]=1		, lowerCamelCase_    :Union[str, Any]=1		, lowerCamelCase_    :str=5		, lowerCamelCase_    :List[Any]=2		, lowerCamelCase_    :List[str]=0.1		, **lowerCamelCase_    :Any		, )							->			str:







			'''simple docstring'''




			if backbone_config is not None and use_timm_backbone:
					raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''					)

			if not use_timm_backbone:
					if backbone_config is None:
							logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''					)
							SCREAMING_SNAKE_CASE       :     Optional[Any]				= CONFIG_MAPPING["""resnet"""](out_features=['''stage4''']					)
					elif isinstance(_UpperCamelCase		, _UpperCamelCase					):
							SCREAMING_SNAKE_CASE       :     Dict				= backbone_config.get('''model_type'''					)
							SCREAMING_SNAKE_CASE       :     List[str]				= CONFIG_MAPPING[backbone_model_type]
							SCREAMING_SNAKE_CASE       :     Tuple				= config_class.from_dict(_UpperCamelCase					)
					# set timm attributes to None
					SCREAMING_SNAKE_CASE       :     Union[str, Any]				= None, None, None

			SCREAMING_SNAKE_CASE       :     Optional[int]				= use_timm_backbone
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= backbone_config
			SCREAMING_SNAKE_CASE       :     Dict				= num_channels
			SCREAMING_SNAKE_CASE       :     Optional[int]				= num_queries
			SCREAMING_SNAKE_CASE       :     Tuple				= d_model
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= encoder_ffn_dim
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= encoder_layers
			SCREAMING_SNAKE_CASE       :     str				= encoder_attention_heads
			SCREAMING_SNAKE_CASE       :     List[Any]				= decoder_ffn_dim
			SCREAMING_SNAKE_CASE       :     List[str]				= decoder_layers
			SCREAMING_SNAKE_CASE       :     Tuple				= decoder_attention_heads
			SCREAMING_SNAKE_CASE       :     List[str]				= dropout
			SCREAMING_SNAKE_CASE       :     Any				= attention_dropout
			SCREAMING_SNAKE_CASE       :     List[str]				= activation_dropout
			SCREAMING_SNAKE_CASE       :     Optional[int]				= activation_function
			SCREAMING_SNAKE_CASE       :     List[Any]				= init_std
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= init_xavier_std
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= encoder_layerdrop
			SCREAMING_SNAKE_CASE       :     Optional[int]				= decoder_layerdrop
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= encoder_layers
			SCREAMING_SNAKE_CASE       :     List[Any]				= auxiliary_loss
			SCREAMING_SNAKE_CASE       :     int				= position_embedding_type
			SCREAMING_SNAKE_CASE       :     int				= backbone
			SCREAMING_SNAKE_CASE       :     Optional[int]				= use_pretrained_backbone
			SCREAMING_SNAKE_CASE       :     List[str]				= dilation
			# Hungarian matcher
			SCREAMING_SNAKE_CASE       :     int				= class_cost
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= bbox_cost
			SCREAMING_SNAKE_CASE       :     int				= giou_cost
			# Loss coefficients
			SCREAMING_SNAKE_CASE       :     str				= mask_loss_coefficient
			SCREAMING_SNAKE_CASE       :     List[str]				= dice_loss_coefficient
			SCREAMING_SNAKE_CASE       :     Dict				= bbox_loss_coefficient
			SCREAMING_SNAKE_CASE       :     Optional[int]				= giou_loss_coefficient
			SCREAMING_SNAKE_CASE       :     int				= eos_coefficient
			super().__init__(is_encoder_decoder=_UpperCamelCase		, **_UpperCamelCase					)





	@property
	def   __lowerCAmelCase (						self    :Union[str, Any]					)							->			int:







			'''simple docstring'''




			return self.encoder_attention_heads





	@property
	def   __lowerCAmelCase (						self    :Dict					)							->			int:







			'''simple docstring'''




			return self.d_model





	@classmethod
	def   __lowerCAmelCase (						cls    :List[str]		, lowerCamelCase_    :PretrainedConfig		, **lowerCamelCase_    :List[str]					)							->			List[Any]:







			'''simple docstring'''




			return cls(backbone_config=_UpperCamelCase		, **_UpperCamelCase					)







	def   __lowerCAmelCase (						self    :List[Any]					)							->			Dict[str, any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Tuple				= copy.deepcopy(self.__dict__					)
			if output["backbone_config"] is not None:
					SCREAMING_SNAKE_CASE       :     List[str]				= self.backbone_config.to_dict()
			SCREAMING_SNAKE_CASE       :     List[Any]				= self.__class__.model_type
			return output





class 				lowercase__(				__lowerCAmelCase   ):
	'''simple docstring'''

	UpperCamelCase				=  version.parse("""1.11"""   )





	@property
	def   __lowerCAmelCase (						self    :Tuple					)							->			Mapping[str, Mapping[int, str]]:







			'''simple docstring'''




			return OrderedDict(
			    [
			        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
			        ('''pixel_mask''', {0: '''batch'''}),
			    ]					)





	@property
	def   __lowerCAmelCase (						self    :int					)							->			float:







			'''simple docstring'''




			return 1E-5







	@property
	def   __lowerCAmelCase (						self    :List[str]					)							->			int:







			'''simple docstring'''




			return 12







"""simple docstring"""






from sklearn.metrics import fa_score

import datasets


lowerCamelCase__ :       List[Any]						     =			"\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n"


lowerCamelCase__ :       str						     =			"\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {'f1': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results['f1'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(round(results['f1'], 2))\n        0.35\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n        >>> print(round(results['f1'], 2))\n        0.33\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'f1': array([0.8, 0. , 0. ])}\n"


lowerCamelCase__ :       int						     =			"\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,						_KWARGS_DESCRIPTION   )
class 				lowercase__(				datasets.Metric   ):
	'''simple docstring'''

	def   __lowerCAmelCase (						self    :str					)							->			Any:







			'''simple docstring'''




			return datasets.MetricInfo(
			    description=_DESCRIPTION		, citation=_CITATION		, inputs_description=_KWARGS_DESCRIPTION		, features=datasets.Features(
			        {
			            '''predictions''': datasets.Sequence(datasets.Value('''int32'''					)					),
			            '''references''': datasets.Sequence(datasets.Value('''int32'''					)					),
			        }
			        if self.config_name == '''multilabel'''
			        else {
			            '''predictions''': datasets.Value('''int32'''					),
			            '''references''': datasets.Value('''int32'''					),
			        }					)		, reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html''']		, )







	def   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :int=None		, lowerCamelCase_    :str=1		, lowerCamelCase_    :Union[str, Any]="binary"		, lowerCamelCase_    :Dict=None					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= fa_score(
			    lowerCamelCase_		, lowerCamelCase_		, labels=lowerCamelCase_		, pos_label=lowerCamelCase_		, average=lowerCamelCase_		, sample_weight=lowerCamelCase_					)
			return {"f1": float(lowerCamelCase_					) if score.size == 1 else score}





