
from sklearn.metrics import mean_squared_error

import datasets


lowerCamelCase__     :		Tuple        = """\
@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}
}
"""

lowerCamelCase__     :		int        = """\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


lowerCamelCase__     :		Dict        = """
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        \"raw_values\" : Returns a full set of errors in case of multioutput input.

        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric(\"mse\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {'mse': 0.6123724356957945}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'mse': array([0.41666667, 1. ])}
"""



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


 def   lowercase__  (       self):


   '''simple docstring'''




   return datasets.MetricInfo(
       description=_DESCRIPTION       ,	citation=_CITATION       ,	inputs_description=_KWARGS_DESCRIPTION       ,	features=datasets.Features(self._get_feature_types())       ,	reference_urls=[
           """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"""
       ]       ,	)


 def   lowercase__  (       self):


   '''simple docstring'''




   if self.config_name == "multilist":
     return {
         "predictions": datasets.Sequence(datasets.Value("""float""")),
         "references": datasets.Sequence(datasets.Value("""float""")),
     }
   else:
     return {
         "predictions": datasets.Value("""float"""),
         "references": datasets.Value("""float"""),
     }



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=None       ,	SCREAMING_SNAKE_CASE_="uniform_average"       ,	SCREAMING_SNAKE_CASE_=True):


   '''simple docstring'''




   lowercase__	: Dict     		=   mean_squared_error(
       SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	sample_weight=SCREAMING_SNAKE_CASE_       ,	multioutput=SCREAMING_SNAKE_CASE_       ,	squared=SCREAMING_SNAKE_CASE_)

   return {"mse": mse}








from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_torch_available():
     import torch

     from transformers.modeling_outputs import BaseModelOutput

     from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

lowerCamelCase__     :		Optional[Any]        = logging.get_logger(__name__)



@add_end_docstrings(UpperCAmelCase_				)
class    _snake_case (						UpperCAmelCase_				):


 def __init__(       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   super().__init__(**SCREAMING_SNAKE_CASE_)

   if self.framework == "tf":
     raise ValueError(f'The {self.__class__} is only available in PyTorch.')

   requires_backends(self       ,	"""vision""")
   self.check_model_type(SCREAMING_SNAKE_CASE_)


 def __call__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




   if "text_queries" in kwargs:
     lowercase__	: Any     		=   kwargs.pop("""text_queries""")

   if isinstance(SCREAMING_SNAKE_CASE_       ,	(str, Image.Image)):
     lowercase__	: Optional[Any]     		=   {"""image""": image, """candidate_labels""": candidate_labels}
   else:
     lowercase__	: int     		=   image
   lowercase__	: List[str]     		=   super().__call__(SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_)
   return results


 def   lowercase__  (       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Tuple     		=   {}
   if "threshold" in kwargs:
     lowercase__	: List[Any]     		=   kwargs["""threshold"""]
   if "top_k" in kwargs:
     lowercase__	: int     		=   kwargs["""top_k"""]
   return {}, {}, postprocess_params


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   load_image(inputs["""image"""])
   lowercase__	: Any     		=   inputs["""candidate_labels"""]
   if isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):
     lowercase__	: List[str]     		=   candidate_labels.split(""",""")

   lowercase__	: Tuple     		=   torch.tensor([[image.height, image.width]]       ,	dtype=torch.intaa)
   for i, candidate_label in enumerate(SCREAMING_SNAKE_CASE_):
     lowercase__	: Optional[Any]     		=   self.tokenizer(SCREAMING_SNAKE_CASE_       ,	return_tensors=self.framework)
     lowercase__	: Union[str, Any]     		=   self.image_processor(SCREAMING_SNAKE_CASE_       ,	return_tensors=self.framework)
     yield {
         "is_last": i == len(SCREAMING_SNAKE_CASE_) - 1,
         "target_size": target_size,
         "candidate_label": candidate_label,
         **text_inputs,
         **image_features,
     }


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   model_inputs.pop("""target_size""")
   lowercase__	: Optional[int]     		=   model_inputs.pop("""candidate_label""")
   lowercase__	: Dict     		=   model_inputs.pop("""is_last""")

   lowercase__	: Union[str, Any]     		=   self.model(**SCREAMING_SNAKE_CASE_)

   lowercase__	: Union[str, Any]     		=   {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
   return model_outputs


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0.1       ,	SCREAMING_SNAKE_CASE_=None):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   []
   for model_output in model_outputs:
     lowercase__	: Optional[int]     		=   model_output["""candidate_label"""]
     lowercase__	: Tuple     		=   BaseModelOutput(SCREAMING_SNAKE_CASE_)
     lowercase__	: List[str]     		=   self.image_processor.post_process_object_detection(
         outputs=SCREAMING_SNAKE_CASE_       ,	threshold=SCREAMING_SNAKE_CASE_       ,	target_sizes=model_output["""target_size"""])[0]

     for index in outputs["scores"].nonzero():
       lowercase__	: Optional[Any]     		=   outputs["""scores"""][index].item()
       lowercase__	: Optional[Any]     		=   self._get_bounding_box(outputs["""boxes"""][index][0])

       lowercase__	: Tuple     		=   {"""score""": score, """label""": label, """box""": box}
       results.append(SCREAMING_SNAKE_CASE_)

   lowercase__	: int     		=   sorted(SCREAMING_SNAKE_CASE_       ,	key=lambda SCREAMING_SNAKE_CASE_: x["score"]       ,	reverse=SCREAMING_SNAKE_CASE_)
   if top_k:
     lowercase__	: Any     		=   results[:top_k]

   return results



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if self.framework != "pt":
     raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""")
   lowercase__		,     lowercase__		,     lowercase__		,     lowercase__	: List[Any]     		=   box.int().tolist()
   lowercase__	: Optional[int]     		=   {
       """xmin""": xmin,
       """ymin""": ymin,
       """xmax""": xmax,
       """ymax""": ymax,
   }
   return bbox






