



'''simple docstring'''


import os

import pytest
import yaml

from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
    "files"     ,[
        ["full:README.md", "dataset_infos.json"],
        ["empty:README.md", "dataset_infos.json"],
        ["dataset_infos.json"],
        ["full:README.md"],
    ]     ,)
def 							UpperCAmelCase_  (						__lowerCamelCase : Tuple     ,__lowerCamelCase : Dict			):
   lowercase_      :Union[str, Any]         =			tmp_path_factory.mktemp("dset_infos_dir"			)
   if "full:README.md" in files:
      with open(dataset_infos_dir / "README.md"     ,"w"			) as f:
         f.write("---\ndataset_info:\n  dataset_size: 42\n---"			)
   if "empty:README.md" in files:
      with open(dataset_infos_dir / "README.md"     ,"w"			) as f:
         f.write(""			)
    # we want to support dataset_infos.json for backward compatibility
   if "dataset_infos.json" in files:
      with open(dataset_infos_dir / "dataset_infos.json"     ,"w"			) as f:
         f.write("{\"default\": {\"dataset_size\": 42}}"			)
   lowercase_      :Any         =			DatasetInfosDict.from_directory(__lowerCamelCase			)
   assert dataset_infos
   assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
    "dataset_info"     ,[
        DatasetInfo(),
        DatasetInfo(
            description="foo"     ,features=Features({"a": Value("int32"			)}			)     ,builder_name="builder"     ,config_name="config"     ,version="1.0.0"     ,splits=[{"name": "train"}]     ,download_size=42     ,),
    ]     ,)
def 							UpperCAmelCase_  (						__lowerCamelCase : Union[str, Any]     ,__lowerCamelCase : DatasetInfo			):
   lowercase_      :Tuple         =			str(__lowerCamelCase			)
   dataset_info.write_to_directory(__lowerCamelCase			)
   lowercase_      :Optional[int]         =			DatasetInfo.from_directory(__lowerCamelCase			)
   assert dataset_info == reloaded
   assert os.path.exists(os.path.join(__lowerCamelCase     ,"dataset_info.json"			)			)
def 							UpperCAmelCase_  (						):
   lowercase_      :Union[str, Any]         =			DatasetInfo(
       description="foo"     ,citation="bar"     ,homepage="https://foo.bar"     ,license="CC0"     ,features=Features({"a": Value("int32"			)}			)     ,post_processed={}     ,supervised_keys=()     ,task_templates=[]     ,builder_name="builder"     ,config_name="config"     ,version="1.0.0"     ,splits=[{"name": "train", "num_examples": 42}]     ,download_checksums={}     ,download_size=13_37     ,post_processing_size=4_42     ,dataset_size=12_34     ,size_in_bytes=13_37 + 4_42 + 12_34     ,)
   lowercase_      :int         =			dataset_info._to_yaml_dict()
   assert sorted(__lowerCamelCase			) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML			)
   for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
      assert key in dataset_info_yaml_dict
      assert isinstance(dataset_info_yaml_dict[key]     ,(list, dict, int, str)			)
   lowercase_      :str         =			yaml.safe_dump(__lowerCamelCase			)
   lowercase_      :str         =			yaml.safe_load(__lowerCamelCase			)
   assert dataset_info_yaml_dict == reloaded
def 							UpperCAmelCase_  (						):
   lowercase_      :Optional[int]         =			DatasetInfo()
   lowercase_      :Optional[int]         =			dataset_info._to_yaml_dict()
   assert dataset_info_yaml_dict == {}


@pytest.mark.parametrize(
    "dataset_infos_dict"     ,[
        DatasetInfosDict(),
        DatasetInfosDict({"default": DatasetInfo()}			),
        DatasetInfosDict({"my_config_name": DatasetInfo()}			),
        DatasetInfosDict(
            {
                "default": DatasetInfo(
                    description="foo"     ,features=Features({"a": Value("int32"			)}			)     ,builder_name="builder"     ,config_name="config"     ,version="1.0.0"     ,splits=[{"name": "train"}]     ,download_size=42     ,)
            }			),
        DatasetInfosDict(
            {
                "v1": DatasetInfo(dataset_size=42			),
                "v2": DatasetInfo(dataset_size=13_37			),
            }			),
    ]     ,)
def 							UpperCAmelCase_  (						__lowerCamelCase : Any     ,__lowerCamelCase : DatasetInfosDict			):
   lowercase_      :str         =			str(__lowerCamelCase			)
   dataset_infos_dict.write_to_directory(__lowerCamelCase			)
   lowercase_      :Any         =			DatasetInfosDict.from_directory(__lowerCamelCase			)

   # the config_name of the dataset_infos_dict take over the attribute
   for config_name, dataset_info in dataset_infos_dict.items():
      lowercase_      :List[str]         =			config_name
      # the yaml representation doesn't include fields like description or citation
      # so we just test that we can recover what we can from the yaml
      lowercase_      :List[str]         =			DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()			)
   assert dataset_infos_dict == reloaded

   if dataset_infos_dict:
      assert os.path.exists(os.path.join(__lowerCamelCase     ,"README.md"			)			)









'''simple docstring'''


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 :					Union[str, Any] 							=logging.get_logger(__name__)
@add_end_docstrings(_lowerCAmelCase							)
class 				a_       (    _lowerCAmelCase							):





     def __init__(			self		: List[Any]     ,				**lowercase		: Optional[int]						):





        """simple docstring"""




        super().__init__(**lowercase						)

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

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





     def __call__(			self		: Tuple     ,				lowercase		: Union[str, "Image.Image", List[Dict[str, Any]]]     ,				lowercase		: Union[str, List[str]] = None     ,				**lowercase		: str     ,				):





        """simple docstring"""




        if "text_queries" in kwargs:
           lowercase_      :List[Any]         =			kwargs.pop("text_queries"						)

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





     def 							lowercase__				(			self		: Optional[int]     ,				**lowercase		: List[str]						):





        """simple docstring"""




        lowercase_      :Tuple         =			{}
        if "threshold" in kwargs:
           lowercase_      :Dict         =			kwargs["threshold"]
        if "top_k" in kwargs:
           lowercase_      :Optional[Any]         =			kwargs["top_k"]
        return {}, {}, postprocess_params





     def 							lowercase__				(			self		: List[Any]     ,				lowercase		: Dict						):





        """simple docstring"""




        lowercase_      :Any         =			load_image(inputs["image"]						)
        lowercase_      :List[str]         =			inputs["candidate_labels"]
        if isinstance(lowercase     ,				lowercase						):
           lowercase_      :Union[str, Any]         =			candidate_labels.split(","						)

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





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: List[str]						):





        """simple docstring"""




        lowercase_      :Dict         =			model_inputs.pop("target_size"						)
        lowercase_      :str         =			model_inputs.pop("candidate_label"						)
        lowercase_      :List[Any]         =			model_inputs.pop("is_last"						)

        lowercase_      :Optional[Any]         =			self.model(**lowercase						)

        lowercase_      :str         =			{"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
        return model_outputs





     def 							lowercase__				(			self		: Optional[int]     ,				lowercase		: List[str]     ,				lowercase		: List[str]=0.1     ,				lowercase		: Optional[int]=None						):





        """simple docstring"""




        lowercase_      :Dict         =			[]
        for model_output in model_outputs:
           lowercase_      :int         =			model_output["candidate_label"]
           lowercase_      :str         =			BaseModelOutput(lowercase						)
           lowercase_      :List[Any]         =			self.image_processor.post_process_object_detection(
               outputs=lowercase     ,				threshold=lowercase     ,				target_sizes=model_output["target_size"]						)[0]

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

              lowercase_      :int         =			{"score": score, "label": label, "box": box}
              results.append(lowercase						)

        lowercase_      :Dict         =			sorted(lowercase     ,				key=lambda lowercase						: x["score"]     ,				reverse=lowercase						)
        if top_k:
           lowercase_      :List[str]         =			results[:top_k]

        return results







     def 							lowercase__				(			self		: Union[str, Any]     ,				lowercase		: "torch.Tensor"						):





        """simple docstring"""




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


