

import enum
import warnings

from ..tokenization_utils import TruncationStrategy
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

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

SCREAMING_SNAKE_CASE		:Any						=     logging.get_logger(__name__)






class 						__magic_name__					(							enum.Enum				):
     UpperCamelCase_	:str										=      0
     UpperCamelCase_	:int										=      1






@add_end_docstrings(snake_case				)
class 						__magic_name__					(							snake_case				):
     UpperCamelCase_	:Tuple										=      """generated"""






     def __init__(				self		,						*_lowercase		,						**_lowercase	)->     Tuple:
         super().__init__(*_lowercase		,						**_lowercase	)

         self.check_model_type(
             TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
             if self.framework == "tf"
             else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING	)






     def 	UpperCAmelCase_				(				self		,						_lowercase=None		,						_lowercase=None		,						_lowercase=None		,						_lowercase=None		,						_lowercase=None		,						_lowercase=None		,						**_lowercase		,						)->     Optional[int]:
         UpperCamelCase_			  =						{}
         if truncation is not None:
             UpperCamelCase_			  =						truncation

         UpperCamelCase_			  =						generate_kwargs

         UpperCamelCase_			  =						{}
         if return_tensors is not None and return_type is None:
             UpperCamelCase_			  =						ReturnType.TENSORS if return_tensors else ReturnType.TEXT
         if return_type is not None:
             UpperCamelCase_			  =						return_type

         if clean_up_tokenization_spaces is not None:
             UpperCamelCase_			  =						clean_up_tokenization_spaces

         if stop_sequence is not None:
             UpperCamelCase_			  =						self.tokenizer.encode(_lowercase		,						add_special_tokens=_lowercase	)
             if len(_lowercase	) > 1:
                 warnings.warn(
                     "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
                     " the stop sequence will be used as the stop sequence string in the interim."	)
             UpperCamelCase_			  =						stop_sequence_ids[0]

         return preprocess_params, forward_params, postprocess_params






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase		,						_lowercase	)->     Optional[int]:
         return True






     def 	UpperCAmelCase_				(				self		,						*_lowercase		,						_lowercase	)->     List[Any]:
         UpperCamelCase_			  =						self.model.config.prefix if self.model.config.prefix is not None else ""
         if isinstance(args[0]		,						_lowercase	):
             if self.tokenizer.pad_token_id is None:
                 raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input"	)
             UpperCamelCase_			  =						([prefix + arg for arg in args[0]],)
             UpperCamelCase_			  =						True

         elif isinstance(args[0]		,						_lowercase	):
             UpperCamelCase_			  =						(prefix + args[0],)
             UpperCamelCase_			  =						False
         else:
             raise ValueError(
                 F" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`"	)
         UpperCamelCase_			  =						self.tokenizer(*_lowercase		,						padding=_lowercase		,						truncation=_lowercase		,						return_tensors=self.framework	)
         # This is produced by tokenizers but is an invalid generate kwargs
         if "token_type_ids" in inputs:
             del inputs["token_type_ids"]
         return inputs






     def __call__(				self		,						*_lowercase		,						**_lowercase	)->     List[Any]:
         UpperCamelCase_			  =						super().__call__(*_lowercase		,						**_lowercase	)
         if (
             isinstance(args[0]		,						_lowercase	)
             and all(isinstance(_lowercase		,						_lowercase	) for el in args[0]	)
             and all(len(_lowercase	) == 1 for res in result	)
         ):
             return [res[0] for res in result]
         return result






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase=TruncationStrategy.DO_NOT_TRUNCATE		,						**_lowercase	)->     List[Any]:
         UpperCamelCase_			  =						self._parse_and_tokenize(_lowercase		,						truncation=_lowercase		,						**_lowercase	)
         return inputs






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						**_lowercase	)->     Dict:
         if self.framework == "pt":
             UpperCamelCase_  ,       UpperCamelCase_			  =						model_inputs["input_ids"].shape
         elif self.framework == "tf":
             UpperCamelCase_  ,       UpperCamelCase_			  =						tf.shape(model_inputs["input_ids"]	).numpy()

         UpperCamelCase_			  =						generate_kwargs.get("min_length"		,						self.model.config.min_length	)
         UpperCamelCase_			  =						generate_kwargs.get("max_length"		,						self.model.config.max_length	)
         self.check_inputs(_lowercase		,						generate_kwargs["min_length"]		,						generate_kwargs["max_length"]	)
         UpperCamelCase_			  =						self.model.generate(**_lowercase		,						**_lowercase	)
         UpperCamelCase_			  =						output_ids.shape[0]
         if self.framework == "pt":
             UpperCamelCase_			  =						output_ids.reshape(_lowercase		,						out_b // in_b		,						*output_ids.shape[1:]	)
         elif self.framework == "tf":
             UpperCamelCase_			  =						tf.reshape(_lowercase		,						(in_b, out_b // in_b, *output_ids.shape[1:])	)
         return {"output_ids": output_ids}






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase=ReturnType.TEXT		,						_lowercase=False	)->     int:
         UpperCamelCase_			  =						[]
         for output_ids in model_outputs["output_ids"][0]:
             if return_type == ReturnType.TENSORS:
                 UpperCamelCase_			  =						{F"{self.return_name}_token_ids": output_ids}
             elif return_type == ReturnType.TEXT:
                 UpperCamelCase_			  =						{
                     F"{self.return_name}_text": self.tokenizer.decode(
                         _lowercase		,						skip_special_tokens=_lowercase		,						clean_up_tokenization_spaces=_lowercase		,						)
                 }
             records.append(_lowercase	)
         return records






@add_end_docstrings(snake_case				)
class 						__magic_name__					(							snake_case				):
     UpperCamelCase_	:List[Any]										=      """summary"""






     def __call__(				self		,						*_lowercase		,						**_lowercase	)->     Tuple:
         return super().__call__(*_lowercase		,						**_lowercase	)






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase		,						_lowercase	)->     bool:
         if max_length < min_length:
             logger.warning(F"Your min_length={min_length} must be inferior than your max_length={max_length}."	)

         if input_length < max_length:
             logger.warning(
                 F"Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is "
                 "a summarization task, where outputs shorter than the input are typically wanted, you might "
                 F"consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})"	)






@add_end_docstrings(snake_case				)
class 						__magic_name__					(							snake_case				):
     UpperCamelCase_	:Dict										=      """translation"""






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase		,						_lowercase	)->     Optional[int]:
         if input_length > 0.9 * max_length:
             logger.warning(
                 F"Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider "
                 "increasing your max_length manually, e.g. translator('...', max_length=400)"	)
         return True






     def 	UpperCAmelCase_				(				self		,						*_lowercase		,						_lowercase=TruncationStrategy.DO_NOT_TRUNCATE		,						_lowercase=None		,						_lowercase=None	)->     int:
         if getattr(self.tokenizer		,						"_build_translation_inputs"		,						_lowercase	):
             return self.tokenizer._build_translation_inputs(
                 *_lowercase		,						return_tensors=self.framework		,						truncation=_lowercase		,						src_lang=_lowercase		,						tgt_lang=_lowercase	)
         else:
             return super()._parse_and_tokenize(*_lowercase		,						truncation=_lowercase	)






     def 	UpperCAmelCase_				(				self		,						_lowercase=None		,						_lowercase=None		,						**_lowercase	)->     Union[str, Any]:
         UpperCamelCase_  ,       UpperCamelCase_  ,       UpperCamelCase_			  =						super()._sanitize_parameters(**_lowercase	)
         if src_lang is not None:
             UpperCamelCase_			  =						src_lang
         if tgt_lang is not None:
             UpperCamelCase_			  =						tgt_lang
         if src_lang is None and tgt_lang is None:
             # Backward compatibility, direct arguments use is preferred.
             UpperCamelCase_			  =						kwargs.get("task"		,						self.task	)
             UpperCamelCase_			  =						task.split("_"	)
             if task and len(_lowercase	) == 4:
                 # translation, XX, to YY
                 UpperCamelCase_			  =						items[1]
                 UpperCamelCase_			  =						items[3]
         return preprocess_params, forward_params, postprocess_params






     def __call__(				self		,						*_lowercase		,						**_lowercase	)->     Dict:
         return super().__call__(*_lowercase		,						**_lowercase	)



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 						__magic_name__					:






      @staticmethod
      def 	UpperCAmelCase_				(				*_lowercase		,						**_lowercase	)->     Optional[int]:
          pass






@is_pipeline_test
@require_vision
@require_torch
class 						__magic_name__					(							unittest.TestCase				):
     UpperCamelCase_	:Optional[Any]										=      MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase		,						_lowercase	)->     Union[str, Any]:
         UpperCamelCase_			  =						pipeline(
             "zero-shot-object-detection"		,						model="hf-internal-testing/tiny-random-owlvit-object-detection"	)

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






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase	)->     Union[str, Any]:
         UpperCamelCase_			  =						object_detector(examples[0]		,						threshold=0.0	)

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






     @require_tf
     @unittest.skip("Zero Shot Object Detection not implemented in TF"	)
     def 	UpperCAmelCase_				(				self	)->     str:
         pass






     @require_torch
     def 	UpperCAmelCase_				(				self	)->     List[Any]:
         UpperCamelCase_			  =						pipeline(
             "zero-shot-object-detection"		,						model="hf-internal-testing/tiny-random-owlvit-object-detection"	)

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

         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_456, "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.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
             ]		,						)

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

         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 [
                     {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_456, "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.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
                 ]
             ]		,						)






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Any:
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "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.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                 {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                 {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
             ]		,						)

         UpperCamelCase_			  =						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(_lowercase		,						decimals=4	)		,						[
                 [
                     {"score": 0.2_868, "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.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                     {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                     {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
                 ],
                 [
                     {"score": 0.2_868, "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.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                     {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                     {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
                 ],
             ]		,						)






     @require_tf
     @unittest.skip("Zero Shot Object Detection not implemented in TF"	)
     def 	UpperCAmelCase_				(				self	)->     Optional[int]:
         pass






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Optional[Any]:
         UpperCamelCase_			  =						0.2
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						threshold=_lowercase		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "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.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
             ]		,						)






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Optional[int]:
         UpperCamelCase_			  =						2
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						top_k=_lowercase		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "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}},
             ]		,						)
