


"""simple docstring"""






import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
							import tensorflow as tf

if is_torch_available():
							import torch


UpperCAmelCase    :     Dict   						=		logging.get_logger(__name__)





class      lowerCamelCase__   :







					"""simple docstring"""


					def __init__(       self    : Tuple ,       UpperCamelCase    : str = None ,       UpperCamelCase    : uuid.UUID = None ,       UpperCamelCase    : Optional[Any]=None ,       UpperCamelCase    : List[Any]=None  ):
												'''simple docstring'''






												if not conversation_id:
																			__UpperCAmelCase   :						Dict      							=					uuid.uuida()
												if past_user_inputs is None:
																			__UpperCAmelCase   :						List[Any]      							=					[]
												if generated_responses is None:
																			__UpperCAmelCase   :						Union[str, Any]      							=					[]

												__UpperCAmelCase   :						uuid.UUID      							=					conversation_id
												__UpperCAmelCase   :						List[str]      							=					past_user_inputs
												__UpperCAmelCase   :						List[str]      							=					generated_responses
												__UpperCAmelCase   :						Optional[str]      							=					text






					def __eq__(       self    : str ,       UpperCamelCase    : Union[str, Any]  ):
												'''simple docstring'''






												if not isinstance(UpperCamelCase ,       UpperCamelCase  ):
																			return False
												if self.uuid == other.uuid:
																			return True
												return (
												    self.new_user_input == other.new_user_input
												    and self.past_user_inputs == other.past_user_inputs
												    and self.generated_responses == other.generated_responses
												)






					def lowerCamelCase__							(       self    : Union[str, Any] ,       UpperCamelCase    : str ,       UpperCamelCase    : bool = False  ):
												'''simple docstring'''






												if self.new_user_input:
																			if overwrite:
																										logger.warning(
																										    f'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '''
																										    f'''with: "{text}".'''  )
																										__UpperCAmelCase   :						Optional[Any]      							=					text
																			else:
																										logger.warning(
																										    f'''User input added while unprocessed input was existing: "{self.new_user_input}" new input '''
																										    f'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input'''  )
												else:
																			__UpperCAmelCase   :						Any      							=					text






					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												if self.new_user_input:
																			self.past_user_inputs.append(self.new_user_input  )
												__UpperCAmelCase   :						Tuple      							=					None






					def lowerCamelCase__							(       self    : Tuple ,       UpperCamelCase    : str  ):
												'''simple docstring'''






												self.generated_responses.append(UpperCamelCase  )






					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												for user_input, generated_response in zip(self.past_user_inputs ,       self.generated_responses  ):
																			yield True, user_input
																			yield False, generated_response
												if self.new_user_input:
																			yield True, self.new_user_input






					def __repr__(       self    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[str]      							=					f'''Conversation id: {self.uuid} \n'''
												for is_user, text in self.iter_texts():
																			__UpperCAmelCase   :						List[str]      							=					"""user""" if is_user else """bot"""
																			output += f'''{name} >> {text} \n'''
												return output






@add_end_docstrings(
    A     ,    r"""
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    """     ,    )
class      lowerCamelCase__   (     A				):







					"""simple docstring"""


					def __init__(       self    : Optional[int] ,       *UpperCamelCase    : Tuple ,       **UpperCamelCase    : Dict  ):
												'''simple docstring'''






												super().__init__(*UpperCamelCase ,       **UpperCamelCase  )
												if self.tokenizer.pad_token_id is None:
																			__UpperCAmelCase   :						Tuple      							=					self.tokenizer.eos_token






					def lowerCamelCase__							(       self    : Union[str, Any] ,       UpperCamelCase    : int=None ,       UpperCamelCase    : Optional[int]=None ,       UpperCamelCase    : List[Any]=None ,       **UpperCamelCase    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					{}
												__UpperCAmelCase   :						str      							=					{}
												__UpperCAmelCase   :						Union[str, Any]      							=					{}

												if min_length_for_response is not None:
																			__UpperCAmelCase   :						Any      							=					min_length_for_response
												if minimum_tokens is not None:
																			__UpperCAmelCase   :						Dict      							=					minimum_tokens

												if "max_length" in generate_kwargs:
																			__UpperCAmelCase   :						Any      							=					generate_kwargs["""max_length"""]
																			# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
												if clean_up_tokenization_spaces is not None:
																			__UpperCAmelCase   :						Any      							=					clean_up_tokenization_spaces

												if generate_kwargs:
																			forward_params.update(UpperCamelCase  )
												return preprocess_params, forward_params, postprocess_params






					def __call__(       self    : Optional[int] ,       UpperCamelCase    : Union[Conversation, List[Conversation]] ,       UpperCamelCase    : Optional[int]=0 ,       **UpperCamelCase    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Any      							=					super().__call__(UpperCamelCase ,       num_workers=UpperCamelCase ,       **UpperCamelCase  )
												if isinstance(UpperCamelCase ,       UpperCamelCase  ) and len(UpperCamelCase  ) == 1:
																			return outputs[0]
												return outputs






					def lowerCamelCase__							(       self    : Optional[Any] ,       UpperCamelCase    : Conversation ,       UpperCamelCase    : List[Any]=32  ):
												'''simple docstring'''






												if not isinstance(UpperCamelCase ,       UpperCamelCase  ):
																			raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""  )
												if conversation.new_user_input is None:
																			raise ValueError(
																			    f'''Conversation with UUID {type(conversation.uuid  )} does not contain new user input to process. '''
																			    """Add user inputs with the conversation's `add_user_input` method"""  )
												if hasattr(self.tokenizer ,       """_build_conversation_input_ids"""  ):
																			__UpperCAmelCase   :						Any      							=					self.tokenizer._build_conversation_input_ids(UpperCamelCase  )
												else:
																			# If the tokenizer cannot handle conversations, we default to only the old version
																			__UpperCAmelCase   :						str      							=					self._legacy_parse_and_tokenize(UpperCamelCase  )

												if self.framework == "pt":
																			__UpperCAmelCase   :						int      							=					torch.LongTensor([input_ids]  )
												elif self.framework == "tf":
																			__UpperCAmelCase   :						Optional[Any]      							=					tf.constant([input_ids]  )
												return {"input_ids": input_ids, "conversation": conversation}






					def lowerCamelCase__							(       self    : int ,       UpperCamelCase    : Union[str, Any] ,       UpperCamelCase    : Optional[int]=10 ,       **UpperCamelCase    : Dict  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					generate_kwargs.get("""max_length""" ,       self.model.config.max_length  )

												__UpperCAmelCase   :						List[Any]      							=					model_inputs["""input_ids"""].shape[1]
												if max_length - minimum_tokens < n:
																			logger.warning(f'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})'''  )
																			__UpperCAmelCase   :						Dict      							=					max_length - minimum_tokens
																			__UpperCAmelCase   :						List[str]      							=					model_inputs["""input_ids"""][:, -trim:]
																			if "attention_mask" in model_inputs:
																										__UpperCAmelCase   :						str      							=					model_inputs["""attention_mask"""][:, -trim:]
												__UpperCAmelCase   :						Dict      							=					model_inputs.pop("""conversation"""  )
												__UpperCAmelCase   :						Dict      							=					max_length
												__UpperCAmelCase   :						List[Any]      							=					self.model.generate(**UpperCamelCase ,       **UpperCamelCase  )
												if self.model.config.is_encoder_decoder:
																			__UpperCAmelCase   :						int      							=					1
												else:
																			__UpperCAmelCase   :						Dict      							=					n
												return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






					def lowerCamelCase__							(       self    : int ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : List[str]=True  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					model_outputs["""output_ids"""]
												__UpperCAmelCase   :						Optional[int]      							=					self.tokenizer.decode(
												    output_ids[0] ,       skip_special_tokens=UpperCamelCase ,       clean_up_tokenization_spaces=UpperCamelCase ,       )
												__UpperCAmelCase   :						Dict      							=					model_outputs["""conversation"""]
												conversation.mark_processed()
												conversation.append_response(UpperCamelCase  )
												return conversation






					def lowerCamelCase__							(       self    : Optional[Any] ,       UpperCamelCase    : Conversation  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[Any]      							=					self.tokenizer.eos_token_id
												__UpperCAmelCase   :						Union[str, Any]      							=					[]
												for is_user, text in conversation.iter_texts():
																			if eos_token_id is not None:
																										input_ids.extend(self.tokenizer.encode(UpperCamelCase ,       add_special_tokens=UpperCamelCase  ) + [eos_token_id]  )
																			else:
																										input_ids.extend(self.tokenizer.encode(UpperCamelCase ,       add_special_tokens=UpperCamelCase  )  )

												if len(UpperCamelCase  ) > self.tokenizer.model_max_length:
																			__UpperCAmelCase   :						Union[str, Any]      							=					input_ids[-self.tokenizer.model_max_length :]
												return input_ids




"""simple docstring"""






import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:





							class      lowerCamelCase__   :







												"""simple docstring"""


												@staticmethod
												def lowerCamelCase__							(       *UpperCamelCase    : List[str] ,       **UpperCamelCase    : Any  ):
																			'''simple docstring'''






																			pass





@is_pipeline_test
@require_vision
@require_torch
class      lowerCamelCase__   (     unittest.TestCase				):







					"""simple docstring"""


					__a	       =							MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING






					def lowerCamelCase__							(       self    : List[str] ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : Tuple  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[int]      							=					pipeline(
												    """zero-shot-object-detection""" ,       model="""hf-internal-testing/tiny-random-owlvit-object-detection"""  )

												__UpperCAmelCase   :						Tuple      							=					[
												    {
												        """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
												        """candidate_labels""": ["""cat""", """remote""", """couch"""],
												    }
												]
												return object_detector, examples






					def lowerCamelCase__							(       self    : int ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					object_detector(examples[0] ,       threshold=0.0  )

												__UpperCAmelCase   :						Tuple      							=					len(UpperCamelCase  )
												self.assertGreater(UpperCamelCase ,       0  )
												self.assertEqual(
												    UpperCamelCase ,       [
												        {
												            """score""": ANY(UpperCamelCase  ),
												            """label""": ANY(UpperCamelCase  ),
												            """box""": {"""xmin""": ANY(UpperCamelCase  ), """ymin""": ANY(UpperCamelCase  ), """xmax""": ANY(UpperCamelCase  ), """ymax""": ANY(UpperCamelCase  )},
												        }
												        for i in range(UpperCamelCase  )
												    ] ,       )






					@require_tf
					@unittest.skip("""Zero Shot Object Detection not implemented in TF"""  )
					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												pass






					@require_torch
					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					pipeline(
												    """zero-shot-object-detection""" ,       model="""hf-internal-testing/tiny-random-owlvit-object-detection"""  )

												__UpperCAmelCase   :						Tuple      							=					object_detector(
												    """./tests/fixtures/tests_samples/COCO/000000039769.png""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       threshold=0.64 ,       )

												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												        {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												        {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												        {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
												        {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												    ] ,       )

												__UpperCAmelCase   :						Any      							=					object_detector(
												    [
												        {
												            """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        }
												    ] ,       threshold=0.64 ,       )

												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        [
												            {"""score""": 0.7235, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.7218, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.7184, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
												            {"""score""": 0.6748, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6656, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6614, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
												            {"""score""": 0.6456, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												            {"""score""": 0.642, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
												            {"""score""": 0.6419, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
												        ]
												    ] ,       )






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : Optional[int]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Any      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						int      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												        {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												        {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												        {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												    ] ,       )

												__UpperCAmelCase   :						List[str]      							=					object_detector(
												    [
												        {
												            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        },
												        {
												            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
												            """candidate_labels""": ["""cat""", """remote""", """couch"""],
												        },
												    ] ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        [
												            {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												            {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												            {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												            {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												            {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												        ],
												        [
												            {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												            {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												            {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												            {"""score""": 0.1474, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
												            {"""score""": 0.1208, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
												        ],
												    ] ,       )






					@require_tf
					@unittest.skip("""Zero Shot Object Detection not implemented in TF"""  )
					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												pass






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[str]      							=					0.2
												__UpperCAmelCase   :						List[Any]      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						Any      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       threshold=UpperCamelCase ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												        {"""score""": 0.2537, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
												    ] ,       )






					@require_torch
					@slow
					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					2
												__UpperCAmelCase   :						Union[str, Any]      							=					pipeline("""zero-shot-object-detection"""  )

												__UpperCAmelCase   :						List[str]      							=					object_detector(
												    """http://images.cocodataset.org/val2017/000000039769.jpg""" ,       candidate_labels=["""cat""", """remote""", """couch"""] ,       top_k=UpperCamelCase ,       )
												self.assertEqual(
												    nested_simplify(UpperCamelCase ,       decimals=4  ) ,       [
												        {"""score""": 0.2868, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
												        {"""score""": 0.277, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
												    ] ,       )
