






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__							=     logging.get_logger(__name__)




@add_end_docstrings(lowercase_)
class 			snake_case__   (							lowercase_):

       '''simple docstring'''



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






            '''simple docstring'''





            super().__init__(**a__    )

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

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



       def __call__(							self			,						a__			,						a__ = None			,						**a__			,						) ->      Any:






            '''simple docstring'''





            if "text_queries" in kwargs:
                 __snake_case			:Optional[Any]          =						kwargs.pop("""text_queries"""    )

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



       def 					__lowercase						(							self			,						**a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						{}
            if "threshold" in kwargs:
                 __snake_case			:int          =						kwargs["""threshold"""]
            if "top_k" in kwargs:
                 __snake_case			:Any          =						kwargs["""top_k"""]
            return {}, {}, postprocess_params



       def 					__lowercase						(							self			,						a__    ) ->      int:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						load_image(inputs["""image"""]    )
            __snake_case			:Optional[int]          =						inputs["""candidate_labels"""]
            if isinstance(a__			,						a__    ):
                 __snake_case			:List[str]          =						candidate_labels.split(""","""    )

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



       def 					__lowercase						(							self			,						a__    ) ->      int:






            '''simple docstring'''





            __snake_case			:Tuple          =						model_inputs.pop("""target_size"""    )
            __snake_case			:Tuple          =						model_inputs.pop("""candidate_label"""    )
            __snake_case			:Dict          =						model_inputs.pop("""is_last"""    )

            __snake_case			:List[str]          =						self.model(**a__    )

            __snake_case			:Dict          =						{"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
            return model_outputs



       def 					__lowercase						(							self			,						a__			,						a__=0.1			,						a__=None    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case			:Any          =						[]
            for model_output in model_outputs:
                 __snake_case			:Optional[Any]          =						model_output["""candidate_label"""]
                 __snake_case			:Optional[int]          =						BaseModelOutput(a__    )
                 __snake_case			:str          =						self.image_processor.post_process_object_detection(
                     outputs=a__			,						threshold=a__			,						target_sizes=model_output["""target_size"""]    )[0]

                 for index in outputs["scores"].nonzero():
                      __snake_case			:Tuple          =						outputs["""scores"""][index].item()
                      __snake_case			:Union[str, Any]          =						self._get_bounding_box(outputs["""boxes"""][index][0]    )

                      __snake_case			:List[str]          =						{"""score""": score, """label""": label, """box""": box}
                      results.append(a__    )

            __snake_case			:str          =						sorted(a__			,						key=lambda a__    : x["score"]			,						reverse=a__    )
            if top_k:
                 __snake_case			:List[Any]          =						results[:top_k]

            return results



       def 					__lowercase						(							self			,						a__    ) ->      Dict[str, int]:






            '''simple docstring'''





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










import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


lowerCamelCase__							=     """
Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.

In March 2021, Hugging Face raised $40 million in a Series B funding round.[3]

On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]
"""




class 			snake_case__   (							unittest.TestCase	,    lowercase_):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:int          =						load_tool("""text-question-answering"""    )
            self.tool.setup()
            __snake_case			:Tuple          =						load_tool("""text-question-answering"""			,						remote=a__    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.tool(a__			,						"""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.remote_tool(a__			,						"""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						self.tool(text=a__			,						question="""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.remote_tool(text=a__			,						question="""What did Hugging Face do in April 2021?"""    )
            self.assertEqual(a__			,						"""launched the BigScience Research Workshop"""    )


