



import os
import unittest

from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class    _A	(     __UpperCAmelCase				,unittest.TestCase   ):
       UpperCamelCase__  :   int						 =						FunnelTokenizer
       UpperCamelCase__  :   Dict						 =						FunnelTokenizerFast
       UpperCamelCase__  :   Tuple						 =						True
       UpperCamelCase__  :   List[str]						 =						True



       def 		_lowerCamelCase      (		self							:					Tuple):


           '''simple docstring'''

           super().setUp()

           __a							=    [
               '''<unk>''',
               '''<cls>''',
               '''<sep>''',
               '''want''',
               '''##want''',
               '''##ed''',
               '''wa''',
               '''un''',
               '''runn''',
               '''##ing''',
               ''',''',
               '''low''',
               '''lowest''',
           ]
           __a							=    os.path.join(self.tmpdirname					,		VOCAB_FILES_NAMES['''vocab_file'''])
           with open(self.vocab_file					,		'''w'''					,		encoding='''utf-8''') as vocab_writer:
               vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]))



       def 		_lowerCamelCase      (		self							:					List[Any]					,		**__SCREAMING_SNAKE_CASE							:					Optional[Any]):


           '''simple docstring'''

           return FunnelTokenizer.from_pretrained(self.tmpdirname					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					int					,		**__SCREAMING_SNAKE_CASE							:					List[Any]):


           '''simple docstring'''

           return FunnelTokenizerFast.from_pretrained(self.tmpdirname					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Any					,		__SCREAMING_SNAKE_CASE							:					List[Any]):


           '''simple docstring'''

           __a							=    '''UNwant\u00E9d,running'''
           __a							=    '''unwanted, running'''
           return input_text, output_text



       def 		_lowerCamelCase      (		self							:					Dict):


           '''simple docstring'''

           __a							=    self.tokenizer_class(self.vocab_file)

           __a							=    tokenizer.tokenize('''UNwant\u00E9d,running''')
           self.assertListEqual(__SCREAMING_SNAKE_CASE					,		['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''])
           self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE)					,		[7, 4, 5, 10, 8, 9])





       def 		_lowerCamelCase      (		self							:					str):


           '''simple docstring'''

           __a							=    self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE)
           for tokenizer in tokenizers:
               __a							=    tokenizer('''UNwant\u00E9d,running''')
               __a							=    len(inputs['''input_ids''']) - 1
               self.assertListEqual(inputs['''token_type_ids''']					,		[2] + [0] * sentence_len)

               __a							=    tokenizer('''UNwant\u00E9d,running'''					,		'''UNwant\u00E9d,running''')
               self.assertListEqual(inputs['''token_type_ids''']					,		[2] + [0] * sentence_len + [1] * sentence_len)










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

__snake_case						:Tuple						=					logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase   ):



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


           '''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							:					List[Any]					,		__SCREAMING_SNAKE_CASE							:					Union[str, "Image.Image", List[Dict[str, Any]]]					,		__SCREAMING_SNAKE_CASE							:					Union[str, List[str]] = None					,		**__SCREAMING_SNAKE_CASE							:					Union[str, Any]					,		):


           '''simple docstring'''

           if "text_queries" in kwargs:
               __a							=    kwargs.pop('''text_queries''')

           if isinstance(__SCREAMING_SNAKE_CASE					,		(str, Image.Image)):
               __a							=    {'''image''': image, '''candidate_labels''': candidate_labels}
           else:
               __a							=    image
           __a							=    super().__call__(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           return results



       def 		_lowerCamelCase      (		self							:					str					,		**__SCREAMING_SNAKE_CASE							:					Union[str, Any]):


           '''simple docstring'''

           __a							=    {}
           if "threshold" in kwargs:
               __a							=    kwargs['''threshold''']
           if "top_k" in kwargs:
               __a							=    kwargs['''top_k''']
           return {}, {}, postprocess_params



       def 		_lowerCamelCase      (		self							:					List[str]					,		__SCREAMING_SNAKE_CASE							:					Tuple):


           '''simple docstring'''

           __a							=    load_image(inputs['''image'''])
           __a							=    inputs['''candidate_labels''']
           if isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE):
               __a							=    candidate_labels.split(''',''')

           __a							=    torch.tensor([[image.height, image.width]]					,		dtype=torch.intaa)
           for i, candidate_label in enumerate(__SCREAMING_SNAKE_CASE):
               __a							=    self.tokenizer(__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
               __a							=    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 		_lowerCamelCase      (		self							:					int					,		__SCREAMING_SNAKE_CASE							:					Tuple):


           '''simple docstring'''

           __a							=    model_inputs.pop('''target_size''')
           __a							=    model_inputs.pop('''candidate_label''')
           __a							=    model_inputs.pop('''is_last''')

           __a							=    self.model(**__SCREAMING_SNAKE_CASE)

           __a							=    {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
           return model_outputs



       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Tuple=0.1					,		__SCREAMING_SNAKE_CASE							:					Union[str, Any]=None):


           '''simple docstring'''

           __a							=    []
           for model_output in model_outputs:
               __a							=    model_output['''candidate_label''']
               __a							=    BaseModelOutput(__SCREAMING_SNAKE_CASE)
               __a							=    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():
                   __a							=    outputs['''scores'''][index].item()
                   __a							=    self._get_bounding_box(outputs['''boxes'''][index][0])

                   __a							=    {'''score''': score, '''label''': label, '''box''': box}
                   results.append(__SCREAMING_SNAKE_CASE)

           __a							=    sorted(__SCREAMING_SNAKE_CASE					,		key=lambda __SCREAMING_SNAKE_CASE: x["score"]					,		reverse=__SCREAMING_SNAKE_CASE)
           if top_k:
               __a							=    results[:top_k]

           return results





       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		__SCREAMING_SNAKE_CASE							:					"torch.Tensor"):


           '''simple docstring'''

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





