



"""simple docstring"""






from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

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

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

_lowercase : str      						=						logging.get_logger(__name__)

@add_end_docstrings(lowerCAmelCase_   )
class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def __init__(       self							:  List[str],  **lowerCamelCase							:  Optional[int]     )->					List[Any]:
								super().__init__(**lowerCamelCase     )

								requires_backends(self,  '''vision'''     )
								self.check_model_type(
								    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
								    if self.framework == '''tf'''
								    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING     )



					def __call__(       self							:  List[str],  lowerCamelCase							:  Union[str, List[str], "Image", List["Image"]],  **lowerCamelCase							:  Optional[int]     )->					Optional[int]:
								return super().__call__(lowerCamelCase,  **lowerCamelCase     )



					def 		snake_case       (       self							:  Any,  **lowerCamelCase							:  List[str]     )->					List[Any]:
								lowerCamelCase__		:		Union[str, Any]			={}
								if "candidate_labels" in kwargs:
											lowerCamelCase__		:		Dict			=kwargs['''candidate_labels''']
								if "hypothesis_template" in kwargs:
											lowerCamelCase__		:		List[Any]			=kwargs['''hypothesis_template''']

								return preprocess_params, {}, {}



					def 		snake_case       (       self							:  Any,  lowerCamelCase							:  Optional[int],  lowerCamelCase							:  str=None,  lowerCamelCase							:  Optional[int]="This is a photo of {}."     )->					Tuple:
								lowerCamelCase__		:		Any			=load_image(lowerCamelCase     )
								lowerCamelCase__		:		Any			=self.image_processor(images=[image],  return_tensors=self.framework     )
								lowerCamelCase__		:		str			=candidate_labels
								lowerCamelCase__		:		Dict			=[hypothesis_template.format(lowerCamelCase     ) for x in candidate_labels]
								lowerCamelCase__		:		Dict			=self.tokenizer(lowerCamelCase,  return_tensors=self.framework,  padding=lowerCamelCase     )
								lowerCamelCase__		:		Optional[int]			=[text_inputs]
								return inputs



					def 		snake_case       (       self							:  str,  lowerCamelCase							:  Optional[int]     )->					Optional[Any]:
								lowerCamelCase__		:		Optional[Any]			=model_inputs.pop('''candidate_labels'''     )
								lowerCamelCase__		:		Optional[int]			=model_inputs.pop('''text_inputs'''     )
								if isinstance(text_inputs[0],  lowerCamelCase     ):
											lowerCamelCase__		:		Union[str, Any]			=text_inputs[0]
								else:
											# Batching case.
											lowerCamelCase__		:		Union[str, Any]			=text_inputs[0][0]

								lowerCamelCase__		:		Optional[int]			=self.model(**lowerCamelCase,  **lowerCamelCase     )

								lowerCamelCase__		:		int			={
								    '''candidate_labels''': candidate_labels,
								    '''logits''': outputs.logits_per_image,
								}
								return model_outputs




					def 		snake_case       (       self							:  Optional[Any],  lowerCamelCase							:  Tuple     )->					Any:
								lowerCamelCase__		:		List[Any]			=model_outputs.pop('''candidate_labels'''     )
								lowerCamelCase__		:		List[str]			=model_outputs['''logits'''][0]
								if self.framework == "pt":
											lowerCamelCase__		:		int			=logits.softmax(dim=-1     ).squeeze(-1     )
											lowerCamelCase__		:		List[str]			=probs.tolist()
											if not isinstance(lowerCamelCase,  lowerCamelCase     ):
														lowerCamelCase__		:		Optional[Any]			=[scores]
								elif self.framework == "tf":
											lowerCamelCase__		:		Any			=stable_softmax(lowerCamelCase,  axis=-1     )
											lowerCamelCase__		:		int			=probs.numpy().tolist()
								else:
											raise ValueError(F'''Unsupported framework: {self.framework}'''     )

								lowerCamelCase__		:		Union[str, Any]			=[
								    {'''score''': score, '''label''': candidate_label}
								    for score, candidate_label in sorted(zip(lowerCamelCase,  lowerCamelCase     ),  key=lambda lowerCamelCase     : -x[0]     )
								]
								return result









"""simple docstring"""






def      snake_case__   (		):
			"""simple docstring"""
			return [list(range(1000 - i							,		-1000 - i							,		-1	)	) for i in range(1000	)]


_lowercase : str      						=						generate_large_matrix()
_lowercase : str      						=						(
    [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
    [[3, 2], [1, 0]],
    [[7, 7, 6]],
    [[7, 7, 6], [-1, -2, -3]],
    grid,
)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			assert all(row == sorted(__lowerCamelCase							,		reverse=__lowerCamelCase	) for row in grid	)
			assert all(list(__lowerCamelCase	) == sorted(__lowerCamelCase							,		reverse=__lowerCamelCase	) for col in zip(*__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    list[int]	):
			"""simple docstring"""
			lowerCamelCase__		:		int			=0
			lowerCamelCase__		:		Optional[int]			=len(__lowerCamelCase	) - 1

			# Edge cases such as no values or all numbers are negative.
			if not array or array[0] < 0:
						return 0

			while right + 1 > left:
						lowerCamelCase__		:		List[str]			=(left + right) // 2
						lowerCamelCase__		:		Union[str, Any]			=array[mid]

						# Num must be negative and the index must be greater than or equal to 0.
						if num < 0 and array[mid - 1] >= 0:
									return mid

						if num >= 0:
									lowerCamelCase__		:		Union[str, Any]			=mid + 1
						else:
									lowerCamelCase__		:		Dict			=mid - 1
    # No negative numbers so return the last index of the array + 1 which is the length.
			return len(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			lowerCamelCase__		:		Union[str, Any]			=0
			lowerCamelCase__		:		str			=len(grid[0]	)

			for i in range(len(__lowerCamelCase	)	):
						lowerCamelCase__		:		Any			=find_negative_index(grid[i][:bound]	)
						total += bound
			return (len(__lowerCamelCase	) * len(grid[0]	)) - total






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			return len([number for row in grid for number in row if number < 0]	)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			lowerCamelCase__		:		Tuple			=0
			for row in grid:
						for i, number in enumerate(__lowerCamelCase	):
									if number < 0:
												total += len(__lowerCamelCase	) - i
												break
			return total






def      snake_case__   (		):
			"""simple docstring"""
			from timeit import timeit

			print('''Running benchmarks'''	)
			lowerCamelCase__		:		List[str]			=(
			    '''from __main__ import count_negatives_binary_search, '''
			    '''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
			)
			for func in (
			    "count_negatives_binary_search",  # took 0.7727 seconds
			    "count_negatives_brute_force_with_break",  # took 4.6505 seconds
			    "count_negatives_brute_force",  # took 12.8160 seconds
			):
						lowerCamelCase__		:		Union[str, Any]			=timeit(f'''{func}(grid=grid)'''							,		setup=__lowerCamelCase							,		number=500	)
						print(f'''{func}() took {time:0.4f} seconds'''	)


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		benchmark()




