"""simple docstring"""

import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import OwlViTImageProcessor, OwlViTProcessor







@require_vision
class      UpperCAmelCase_       (						unittest.TestCase):






							def       _UpperCamelCase			(		self :      Tuple  )       ->       Tuple:
												_UpperCamelCase      						=	tempfile.mkdtemp()

												# fmt: off
												_UpperCamelCase      						=	["", "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
												# fmt: on
												_UpperCamelCase      						=	dict(zip(A_     ,						range(len(A_  )  )  )  )
												_UpperCamelCase      						=	["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
												_UpperCamelCase      						=	{"unk_token": "<unk>"}

												_UpperCamelCase      						=	os.path.join(self.tmpdirname     ,						VOCAB_FILES_NAMES['''vocab_file''']  )
												_UpperCamelCase      						=	os.path.join(self.tmpdirname     ,						VOCAB_FILES_NAMES['''merges_file''']  )
												with open(self.vocab_file     ,						'''w'''     ,						encoding='''utf-8'''  ) as fp:
																	fp.write(json.dumps(A_  ) + '''\n'''  )
												with open(self.merges_file     ,						'''w'''     ,						encoding='''utf-8'''  ) as fp:
																	fp.write('''\n'''.join(A_  )  )

												_UpperCamelCase      						=	{
												    "do_resize": True,
												    "size": 20,
												    "do_center_crop": True,
												    "crop_size": 18,
												    "do_normalize": True,
												    "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
												    "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
												}
												_UpperCamelCase      						=	os.path.join(self.tmpdirname     ,						A_  )
												with open(self.image_processor_file     ,						'''w'''     ,						encoding='''utf-8'''  ) as fp:
																	json.dump(A_     ,						A_  )






							def       _UpperCamelCase			(		self :      Dict     ,						**__UpperCamelCase :      List[str]  )       ->       Dict:
												return CLIPTokenizer.from_pretrained(self.tmpdirname     ,						pad_token='''!'''     ,						**A_  )






							def       _UpperCamelCase			(		self :      str     ,						**__UpperCamelCase :      Union[str, Any]  )       ->       Optional[Any]:
												return CLIPTokenizerFast.from_pretrained(self.tmpdirname     ,						pad_token='''!'''     ,						**A_  )






							def       _UpperCamelCase			(		self :      int     ,						**__UpperCamelCase :      List[Any]  )       ->       List[str]:
												return OwlViTImageProcessor.from_pretrained(self.tmpdirname     ,						**A_  )






							def       _UpperCamelCase			(		self :      Optional[Any]  )       ->       List[str]:
												shutil.rmtree(self.tmpdirname  )






							def       _UpperCamelCase			(		self :      Tuple  )       ->       int:
												_UpperCamelCase      						=	[np.random.randint(255     ,						size=(3, 30, 400)     ,						dtype=np.uinta  )]

												_UpperCamelCase      						=	[Image.fromarray(np.moveaxis(A_     ,						0     ,						-1  )  ) for x in image_inputs]

												return image_inputs






							def       _UpperCamelCase			(		self :      Optional[int]  )       ->       str:
												_UpperCamelCase      						=	self.get_tokenizer()
												_UpperCamelCase      						=	self.get_rust_tokenizer()
												_UpperCamelCase      						=	self.get_image_processor()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )
												processor_slow.save_pretrained(self.tmpdirname  )
												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(self.tmpdirname     ,						use_fast=A_  )

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )
												processor_fast.save_pretrained(self.tmpdirname  )
												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(self.tmpdirname  )

												self.assertEqual(processor_slow.tokenizer.get_vocab()     ,						tokenizer_slow.get_vocab()  )
												self.assertEqual(processor_fast.tokenizer.get_vocab()     ,						tokenizer_fast.get_vocab()  )
												self.assertEqual(tokenizer_slow.get_vocab()     ,						tokenizer_fast.get_vocab()  )
												self.assertIsInstance(processor_slow.tokenizer     ,						A_  )
												self.assertIsInstance(processor_fast.tokenizer     ,						A_  )

												self.assertEqual(processor_slow.image_processor.to_json_string()     ,						image_processor.to_json_string()  )
												self.assertEqual(processor_fast.image_processor.to_json_string()     ,						image_processor.to_json_string()  )
												self.assertIsInstance(processor_slow.image_processor     ,						A_  )
												self.assertIsInstance(processor_fast.image_processor     ,						A_  )






							def       _UpperCamelCase			(		self :      List[str]  )       ->       Tuple:
												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=self.get_tokenizer()     ,						image_processor=self.get_image_processor()  )
												processor.save_pretrained(self.tmpdirname  )

												_UpperCamelCase      						=	self.get_tokenizer(bos_token='''(BOS)'''     ,						eos_token='''(EOS)'''  )
												_UpperCamelCase      						=	self.get_image_processor(do_normalize=A_  )

												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(
												    self.tmpdirname     ,						bos_token='''(BOS)'''     ,						eos_token='''(EOS)'''     ,						do_normalize=A_  )

												self.assertEqual(processor.tokenizer.get_vocab()     ,						tokenizer_add_kwargs.get_vocab()  )
												self.assertIsInstance(processor.tokenizer     ,						A_  )

												self.assertEqual(processor.image_processor.to_json_string()     ,						image_processor_add_kwargs.to_json_string()  )
												self.assertIsInstance(processor.image_processor     ,						A_  )






							def       _UpperCamelCase			(		self :      Optional[int]  )       ->       Optional[Any]:
												_UpperCamelCase      						=	self.get_image_processor()
												_UpperCamelCase      						=	self.get_tokenizer()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )

												_UpperCamelCase      						=	self.prepare_image_inputs()

												_UpperCamelCase      						=	image_processor(A_     ,						return_tensors='''np'''  )
												_UpperCamelCase      						=	processor(images=A_     ,						return_tensors='''np'''  )

												for key in input_image_proc.keys():
																	self.assertAlmostEqual(input_image_proc[key].sum()     ,						input_processor[key].sum()     ,						delta=1E-2  )






							def       _UpperCamelCase			(		self :      int  )       ->       Optional[int]:
												_UpperCamelCase      						=	self.get_image_processor()
												_UpperCamelCase      						=	self.get_tokenizer()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )

												_UpperCamelCase      						=	"lower newer"

												_UpperCamelCase      						=	processor(text=A_     ,						return_tensors='''np'''  )

												_UpperCamelCase      						=	tokenizer(A_     ,						return_tensors='''np'''  )

												for key in encoded_tok.keys():
																	self.assertListEqual(encoded_tok[key][0].tolist()     ,						encoded_processor[key][0].tolist()  )






							def       _UpperCamelCase			(		self :      Union[str, Any]  )       ->       List[str]:
												_UpperCamelCase      						=	self.get_image_processor()
												_UpperCamelCase      						=	self.get_tokenizer()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )

												_UpperCamelCase      						=	"lower newer"
												_UpperCamelCase      						=	self.prepare_image_inputs()

												_UpperCamelCase      						=	processor(text=A_     ,						images=A_  )

												self.assertListEqual(list(inputs.keys()  )     ,						['''input_ids''', '''attention_mask''', '''pixel_values''']  )

												# test if it raises when no input is passed
												with pytest.raises(A_  ):
																	processor()






							def       _UpperCamelCase			(		self :      Tuple  )       ->       Tuple:
												_UpperCamelCase      						=	"google/owlvit-base-patch32"
												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(A_  )

												_UpperCamelCase      						=	["cat", "nasa badge"]
												_UpperCamelCase      						=	processor(text=A_  )

												_UpperCamelCase      						=	16
												self.assertListEqual(list(inputs.keys()  )     ,						['''input_ids''', '''attention_mask''']  )
												self.assertEqual(inputs['''input_ids'''].shape     ,						(2, seq_length)  )

												# test if it raises when no input is passed
												with pytest.raises(A_  ):
																	processor()






							def       _UpperCamelCase			(		self :      Any  )       ->       List[str]:
												_UpperCamelCase      						=	"google/owlvit-base-patch32"
												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(A_  )

												_UpperCamelCase      						=	[["cat", "nasa badge"], ["person"]]
												_UpperCamelCase      						=	processor(text=A_  )

												_UpperCamelCase      						=	16
												_UpperCamelCase      						=	len(A_  )
												_UpperCamelCase      						=	max([len(A_  ) for texts in input_texts]  )

												self.assertListEqual(list(inputs.keys()  )     ,						['''input_ids''', '''attention_mask''']  )
												self.assertEqual(inputs['''input_ids'''].shape     ,						(batch_size * num_max_text_queries, seq_length)  )

												# test if it raises when no input is passed
												with pytest.raises(A_  ):
																	processor()






							def       _UpperCamelCase			(		self :      Optional[int]  )       ->       List[str]:
												_UpperCamelCase      						=	"google/owlvit-base-patch32"
												_UpperCamelCase      						=	OwlViTProcessor.from_pretrained(A_  )

												_UpperCamelCase      						=	["cat", "nasa badge"]
												_UpperCamelCase      						=	processor(text=A_  )

												_UpperCamelCase      						=	16
												_UpperCamelCase      						=	inputs["input_ids"]
												_UpperCamelCase      						=	[
												    [4_9406, 2368, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
												    [4_9406, 6841, 1_1301, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
												]

												self.assertListEqual(list(inputs.keys()  )     ,						['''input_ids''', '''attention_mask''']  )
												self.assertEqual(inputs['''input_ids'''].shape     ,						(2, seq_length)  )
												self.assertListEqual(list(input_ids[0]  )     ,						predicted_ids[0]  )
												self.assertListEqual(list(input_ids[1]  )     ,						predicted_ids[1]  )






							def       _UpperCamelCase			(		self :      int  )       ->       Optional[Any]:
												_UpperCamelCase      						=	self.get_image_processor()
												_UpperCamelCase      						=	self.get_tokenizer()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )

												_UpperCamelCase      						=	self.prepare_image_inputs()
												_UpperCamelCase      						=	self.prepare_image_inputs()

												_UpperCamelCase      						=	processor(images=A_     ,						query_images=A_  )

												self.assertListEqual(list(inputs.keys()  )     ,						['''query_pixel_values''', '''pixel_values''']  )

												# test if it raises when no input is passed
												with pytest.raises(A_  ):
																	processor()






							def       _UpperCamelCase			(		self :      List[str]  )       ->       int:
												_UpperCamelCase      						=	self.get_image_processor()
												_UpperCamelCase      						=	self.get_tokenizer()

												_UpperCamelCase      						=	OwlViTProcessor(tokenizer=A_     ,						image_processor=A_  )

												_UpperCamelCase      						=	[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

												_UpperCamelCase      						=	processor.batch_decode(A_  )
												_UpperCamelCase      						=	tokenizer.batch_decode(A_  )

												self.assertListEqual(A_     ,						A_  )







from sklearn.metrics import fa_score

import datasets


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


__lowerCamelCase       :     List[Any]   =     """
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    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.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    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'`.

        - '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.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - '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.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    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.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'f1': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['f1'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> 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])
        >>> print(round(results['f1'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")
        >>> print(round(results['f1'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'f1': array([0.8, 0. , 0. ])}
"""


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



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,   _KWARGS_DESCRIPTION			)
class 					A__   (       datasets.Metric			):





      def        __UpperCamelCase( self   ):
       '''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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_=None       ,							A_=1       ,							A_="binary"       ,							A_=None   ):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   fa_score(
           A_       ,							A_       ,							labels=A_       ,							pos_label=A_       ,							average=A_       ,							sample_weight=A_   )
       return {"f1": float(A_   ) if score.size == 1 else score}
