






"""simple docstring"""
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
							import torch

if is_vision_available():
							import PIL


_lowerCAmelCase         =							logging.get_logger(__name__)






def 			__UpperCamelCase	(		snake_case__   ,   snake_case__   ,   snake_case__   ,   snake_case__					):
	def constraint_to_multiple_of(snake_case__   ,   snake_case__   ,   snake_case__=0   ,   snake_case__=None					):
		A_		:						int	    =   round(val / multiple					) * multiple

		if max_val is not None and x > max_val:
			A_		:						Any	    =   math.floor(val / multiple					) * multiple

		if x < min_val:
			A_		:						Tuple	    =   math.ceil(val / multiple					) * multiple

		return x

	A_		:						List[str]	    =   (output_size, output_size) if isinstance(snake_case__   ,   snake_case__					) else output_size

	A_    ,     A_		:						List[Any]	    =   get_image_size(snake_case__					)
	A_    ,     A_		:						List[Any]	    =   output_size

	# determine new height and width
	A_		:						Any	    =   output_height / input_height
	A_		:						Optional[int]	    =   output_width / input_width

	if keep_aspect_ratio:
		# scale as little as possible
		if abs(1 - scale_width					) < abs(1 - scale_height					):
			# fit width
			A_		:						Optional[Any]	    =   scale_width
		else:
			# fit height
			A_		:						Any	    =   scale_height

	A_		:						List[Any]	    =   constraint_to_multiple_of(scale_height * input_height   ,   multiple=snake_case__					)
	A_		:						Any	    =   constraint_to_multiple_of(scale_width * input_width   ,   multiple=snake_case__					)

	return (new_height, new_width)




class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	_A       :				Any    =				["""pixel_values"""]





	def __init__(self     ,     lowerCAmelCase_ = True     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = PILImageResampling.BILINEAR     ,     lowerCAmelCase_ = False     ,     lowerCAmelCase_ = 1     ,     lowerCAmelCase_ = True     ,     lowerCAmelCase_ = 1 / 255     ,     lowerCAmelCase_ = True     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     **lowerCAmelCase_     ,     ):
		super().__init__(**lowerCAmelCase_							)
		A_		:						Optional[Any]	    =   size if size is not None else {"""height""": 384, """width""": 384}
		A_		:						Union[str, Any]	    =   get_size_dict(lowerCAmelCase_							)
		A_		:						Dict	    =   do_resize
		A_		:						Tuple	    =   size
		A_		:						Optional[Any]	    =   keep_aspect_ratio
		A_		:						Tuple	    =   ensure_multiple_of
		A_		:						List[str]	    =   resample
		A_		:						Tuple	    =   do_rescale
		A_		:						Optional[Any]	    =   rescale_factor
		A_		:						Optional[Any]	    =   do_normalize
		A_		:						Optional[int]	    =   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
		A_		:						Union[str, Any]	    =   image_std if image_std is not None else IMAGENET_STANDARD_STD





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_ = False     ,     lowerCAmelCase_ = 1     ,     lowerCAmelCase_ = PILImageResampling.BICUBIC     ,     lowerCAmelCase_ = None     ,     **lowerCAmelCase_     ,     ):
		A_		:						Union[str, Any]	    =   get_size_dict(lowerCAmelCase_							)
		if "height" not in size or "width" not in size:
			raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}"""							)
		A_		:						List[str]	    =   get_resize_output_image_size(
		    lowerCAmelCase_     ,     output_size=(size["""height"""], size["""width"""])     ,     keep_aspect_ratio=lowerCAmelCase_     ,     multiple=lowerCAmelCase_     ,     )
		return resize(lowerCAmelCase_     ,     size=lowerCAmelCase_     ,     resample=lowerCAmelCase_     ,     data_format=lowerCAmelCase_     ,     **lowerCAmelCase_							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_ = None     ,     **lowerCAmelCase_     ,     ):
		return rescale(lowerCAmelCase_     ,     scale=lowerCAmelCase_     ,     data_format=lowerCAmelCase_     ,     **lowerCAmelCase_							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_ = None     ,     **lowerCAmelCase_     ,     ):
		return normalize(lowerCAmelCase_     ,     mean=lowerCAmelCase_     ,     std=lowerCAmelCase_     ,     data_format=lowerCAmelCase_     ,     **lowerCAmelCase_							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = None     ,     lowerCAmelCase_ = ChannelDimension.FIRST     ,     **lowerCAmelCase_     ,     ):
		A_		:						Dict	    =   do_resize if do_resize is not None else self.do_resize
		A_		:						List[Any]	    =   size if size is not None else self.size
		A_		:						str	    =   get_size_dict(lowerCAmelCase_							)
		A_		:						List[Any]	    =   keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
		A_		:						Tuple	    =   ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
		A_		:						List[Any]	    =   resample if resample is not None else self.resample
		A_		:						Optional[int]	    =   do_rescale if do_rescale is not None else self.do_rescale
		A_		:						Dict	    =   rescale_factor if rescale_factor is not None else self.rescale_factor
		A_		:						Optional[int]	    =   do_normalize if do_normalize is not None else self.do_normalize
		A_		:						str	    =   image_mean if image_mean is not None else self.image_mean
		A_		:						str	    =   image_std if image_std is not None else self.image_std

		A_		:						Tuple	    =   make_list_of_images(lowerCAmelCase_							)

		if not valid_images(lowerCAmelCase_							):
			raise ValueError(
			    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
			    """torch.Tensor, tf.Tensor or jax.ndarray."""							)

		if do_resize and size is None or resample is None:
			raise ValueError("""Size and resample must be specified if do_resize is True."""							)

		if do_rescale and rescale_factor is None:
			raise ValueError("""Rescale factor must be specified if do_rescale is True."""							)

		if do_normalize and (image_mean is None or image_std is None):
			raise ValueError("""Image mean and std must be specified if do_normalize is True."""							)

		# All transformations expect numpy arrays.
		A_		:						Union[str, Any]	    =   [to_numpy_array(lowerCAmelCase_							) for image in images]

		if do_resize:
			A_		:						Any	    =   [self.resize(image=lowerCAmelCase_     ,     size=lowerCAmelCase_     ,     resample=lowerCAmelCase_							) for image in images]

		if do_rescale:
			A_		:						Any	    =   [self.rescale(image=lowerCAmelCase_     ,     scale=lowerCAmelCase_							) for image in images]

		if do_normalize:
			A_		:						List[Any]	    =   [self.normalize(image=lowerCAmelCase_     ,     mean=lowerCAmelCase_     ,     std=lowerCAmelCase_							) for image in images]

		A_		:						List[str]	    =   [to_channel_dimension_format(lowerCAmelCase_     ,     lowerCAmelCase_							) for image in images]

		A_		:						Tuple	    =   {"""pixel_values""": images}
		return BatchFeature(data=lowerCAmelCase_     ,     tensor_type=lowerCAmelCase_							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_ = None							):
		A_		:						Any	    =   outputs.logits

		# Resize logits and compute semantic segmentation maps
		if target_sizes is not None:
			if len(lowerCAmelCase_							) != len(lowerCAmelCase_							):
				raise ValueError(
				    """Make sure that you pass in as many target sizes as the batch dimension of the logits"""							)

			if is_torch_tensor(lowerCAmelCase_							):
				A_		:						Any	    =   target_sizes.numpy()

			A_		:						Optional[int]	    =   []

			for idx in range(len(lowerCAmelCase_							)							):
				A_		:						Optional[Any]	    =   torch.nn.functional.interpolate(
				    logits[idx].unsqueeze(dim=0							)     ,     size=target_sizes[idx]     ,     mode="""bilinear"""     ,     align_corners=lowerCAmelCase_							)
				A_		:						List[Any]	    =   resized_logits[0].argmax(dim=0							)
				semantic_segmentation.append(lowerCAmelCase_							)
		else:
			A_		:						List[Any]	    =   logits.argmax(dim=1							)
			A_		:						Tuple	    =   [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]							)]

		return semantic_segmentation









"""simple docstring"""
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool



class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	_A       :				Optional[int]    =				"""facebook/bart-large-mnli"""
	_A       :				str    =				(
	    """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """
	    """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """
	    """It returns the most likely label in the list of provided `labels` for the input text."""
	)
	_A       :				List[str]    =				"""text_classifier"""
	_A       :				Optional[int]    =				AutoTokenizer
	_A       :				Optional[Any]    =				AutoModelForSequenceClassification

	_A       :				List[str]    =				["""text""", ["""text"""]]
	_A       :				Dict    =				["""text"""]





	def    lowerCamelCase(self							):
		super().setup()
		A_		:						int	    =   self.model.config
		A_		:						List[str]	    =   -1
		for idx, label in config.idalabel.items():
			if label.lower().startswith("""entail"""							):
				A_		:						List[Any]	    =   int(lowerCAmelCase_							)
		if self.entailment_id == -1:
			raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init."""							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						List[Any]	    =   labels
		return self.pre_processor(
		    [text] * len(lowerCAmelCase_							)     ,     [f"""This example is {label}""" for label in labels]     ,     return_tensors="""pt"""     ,     padding="""max_length"""     ,     )





	def    lowerCamelCase(self     ,     lowerCAmelCase_							):
		A_		:						str	    =   outputs.logits
		A_		:						Optional[int]	    =   torch.argmax(logits[:, 2]							).item()
		return self._labels[label_id]

