





'''simple docstring'''




from typing import Dict

import numpy as np

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


if is_tf_available():
  import tensorflow as tf

  from ..tf_utils import stable_softmax


if is_torch_available():
  import torch


lowercase__   :				Optional[int]      =   logging.get_logger(__name__)


@add_end_docstrings(
    a__ ,		r'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    ''' ,		)
class 			SCREAMING_SNAKE_CASE   (a__							):


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          if self.framework == "tf":
               __A						:			Tuple								=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
          elif self.framework == "pt":
               __A						:			str								=	torch.nonzero(input_ids == self.tokenizer.mask_token_id						,     as_tuple=_UpperCAmelCase)
          else:
               raise ValueError('Unsupported framework')
          return masked_index


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Optional[Any]								=	self.get_masked_index(_UpperCAmelCase)
          __A						:			List[str]								=	np.prod(masked_index.shape)
          if numel < 1:
               raise PipelineException(
                   'fill-mask'						,     self.model.base_model_prefix						,     F'No mask_token ({self.tokenizer.mask_token}) found on the input'						,     )


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase):
               for model_input in model_inputs:
                    self._ensure_exactly_one_mask_token(model_input['input_ids'][0])
          else:
               for input_ids in model_inputs["input_ids"]:
                    self._ensure_exactly_one_mask_token(_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=None						,     **_UpperCAmelCase):

          '''simple docstring'''






          if return_tensors is None:
               __A						:			List[Any]								=	self.framework
          __A						:			List[str]								=	self.tokenizer(_UpperCAmelCase						,     return_tensors=_UpperCAmelCase)
          self.ensure_exactly_one_mask_token(_UpperCAmelCase)
          return model_inputs


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Dict								=	self.model(**_UpperCAmelCase)
          __A						:			Optional[Any]								=	model_inputs['input_ids']
          return model_outputs


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=5						,     _UpperCAmelCase=None):

          '''simple docstring'''






          if target_ids is not None and target_ids.shape[0] < top_k:
               __A						:			Any								=	target_ids.shape[0]
          __A						:			Optional[Any]								=	model_outputs['input_ids'][0]
          __A						:			Dict								=	model_outputs['logits']

          if self.framework == "tf":
               __A						:			Tuple								=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

               __A						:			str								=	outputs.numpy()

               __A						:			Union[str, Any]								=	outputs[0, masked_index, :]
               __A						:			str								=	stable_softmax(_UpperCAmelCase						,     axis=-1)
               if target_ids is not None:
                    __A						:			Tuple								=	tf.gather_nd(tf.squeeze(_UpperCAmelCase						,     0)						,     target_ids.reshape(-1						,     1))
                    __A						:			Optional[int]								=	tf.expand_dims(_UpperCAmelCase						,     0)

               __A						:			int								=	tf.math.top_k(_UpperCAmelCase						,     k=_UpperCAmelCase)
               __A			,__A						:			str								=	topk.values.numpy(), topk.indices.numpy()
          else:
               __A						:			Optional[Any]								=	torch.nonzero(input_ids == self.tokenizer.mask_token_id						,     as_tuple=_UpperCAmelCase).squeeze(-1)
               # Fill mask pipeline supports only one ${mask_token} per sample

               __A						:			Tuple								=	outputs[0, masked_index, :]
               __A						:			Dict								=	logits.softmax(dim=-1)
               if target_ids is not None:
                    __A						:			Optional[Any]								=	probs[..., target_ids]

               __A			,__A						:			List[Any]								=	probs.topk(_UpperCAmelCase)

          __A						:			Dict								=	[]
          __A						:			Optional[int]								=	values.shape[0] == 1
          for i, (_values, _predictions) in enumerate(zip(values.tolist()						,     predictions.tolist())):
               __A						:			Dict								=	[]
               for v, p in zip(_values						,     _predictions):
                    # Copy is important since we're going to modify this array in place
                    __A						:			Optional[int]								=	input_ids.numpy().copy()
                    if target_ids is not None:
                         __A						:			Optional[int]								=	target_ids[p].tolist()

                    __A						:			List[Any]								=	p
                    # Filter padding out:
                    __A						:			Dict								=	tokens[np.where(tokens != self.tokenizer.pad_token_id)]
                    # Originally we skip special tokens to give readable output.
                    # For multi masks though, the other [MASK] would be removed otherwise
                    # making the output look odd, so we add them back
                    __A						:			Any								=	self.tokenizer.decode(_UpperCAmelCase						,     skip_special_tokens=_UpperCAmelCase)
                    __A						:			str								=	{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]), 'sequence': sequence}
                    row.append(_UpperCAmelCase)
               result.append(_UpperCAmelCase)
          if single_mask:
               return result[0]
          return result


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=None):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase):
               __A						:			Dict								=	[targets]
          try:
               __A						:			Optional[Any]								=	self.tokenizer.get_vocab()
          except Exception:
               __A						:			str								=	{}
          __A						:			List[str]								=	[]
          for target in targets:
               __A						:			Any								=	vocab.get(_UpperCAmelCase						,     _UpperCAmelCase)
               if id_ is None:
                    __A						:			str								=	self.tokenizer(
                        _UpperCAmelCase						,     add_special_tokens=_UpperCAmelCase						,     return_attention_mask=_UpperCAmelCase						,     return_token_type_ids=_UpperCAmelCase						,     max_length=1						,     truncation=_UpperCAmelCase						,     )['input_ids']
                    if len(_UpperCAmelCase) == 0:
                         logger.warning(
                             F'The specified target token `{target}` does not exist in the model vocabulary. '
                             'We cannot replace it with anything meaningful, ignoring it')
                         continue
                    __A						:			Dict								=	input_ids[0]
                    # XXX: If users encounter this pass
                    # it becomes pretty slow, so let's make sure
                    # The warning enables them to fix the input to
                    # get faster performance.
                    logger.warning(
                        F'The specified target token `{target}` does not exist in the model vocabulary. '
                        F'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.')
               target_ids.append(id_)
          __A						:			Dict								=	list(set(_UpperCAmelCase))
          if len(_UpperCAmelCase) == 0:
               raise ValueError('At least one target must be provided when passed.')
          __A						:			List[str]								=	np.array(_UpperCAmelCase)
          return target_ids


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase=None						,     _UpperCAmelCase=None):

          '''simple docstring'''






          __A						:			Optional[int]								=	{}

          if targets is not None:
               __A						:			Union[str, Any]								=	self.get_target_ids(_UpperCAmelCase						,     _UpperCAmelCase)
               __A						:			Dict								=	target_ids

          if top_k is not None:
               __A						:			Optional[int]								=	top_k

          if self.tokenizer.mask_token_id is None:
               raise PipelineException(
                   'fill-mask'						,     self.model.base_model_prefix						,     'The tokenizer does not define a `mask_token`.')
          return {}, {}, postprocess_params


     def __call__(						self						,     _UpperCAmelCase						,     *_UpperCAmelCase						,     **_UpperCAmelCase):

          '''simple docstring'''






          __A						:			Dict								=	super().__call__(_UpperCAmelCase						,     **_UpperCAmelCase)
          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase) and len(_UpperCAmelCase) == 1:
               return outputs[0]
          return outputs






'''simple docstring'''




from math import pi, sqrt, tan






def 	_lowerCAmelCase      (  __snake_case  :			float      )					->					float:
     if side_length < 0:
          raise ValueError('surface_area_cube() only accepts non-negative values'      )
     return 6 * side_length**2






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if length < 0 or breadth < 0 or height < 0:
          raise ValueError('surface_area_cuboid() only accepts non-negative values'      )
     return 2 * ((length * breadth) + (breadth * height) + (length * height))






def 	_lowerCAmelCase      (  __snake_case  :			float      )					->					float:
     if radius < 0:
          raise ValueError('surface_area_sphere() only accepts non-negative values'      )
     return 4 * pi * radius**2






def 	_lowerCAmelCase      (  __snake_case  :			float      )					->					float:
     if radius < 0:
          raise ValueError('surface_area_hemisphere() only accepts non-negative values'      )
     return 3 * pi * radius**2






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if radius < 0 or height < 0:
          raise ValueError('surface_area_cone() only accepts non-negative values'      )
     return pi * radius * (radius + (height**2 + radius**2) ** 0.5)






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if radius_a < 0 or radius_a < 0 or height < 0:
          raise ValueError(
              'surface_area_conical_frustum() only accepts non-negative values'      )
     __A						:			Union[str, Any]								=	(height**2 + (radius_a - radius_a) ** 2) ** 0.5
     return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2)






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if radius < 0 or height < 0:
          raise ValueError('surface_area_cylinder() only accepts non-negative values'      )
     return 2 * pi * radius * (height + radius)






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if torus_radius < 0 or tube_radius < 0:
          raise ValueError('surface_area_torus() only accepts non-negative values'      )
     if torus_radius < tube_radius:
          raise ValueError(
              'surface_area_torus() does not support spindle or self intersecting tori'      )
     return 4 * pow(__snake_case			,							2      ) * torus_radius * tube_radius






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if length < 0 or width < 0:
          raise ValueError('area_rectangle() only accepts non-negative values'      )
     return length * width






def 	_lowerCAmelCase      (  __snake_case  :			float      )					->					float:
     if side_length < 0:
          raise ValueError('area_square() only accepts non-negative values'      )
     return side_length**2






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if base < 0 or height < 0:
          raise ValueError('area_triangle() only accepts non-negative values'      )
     return (base * height) / 2






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if sidea < 0 or sidea < 0 or sidea < 0:
          raise ValueError('area_triangle_three_sides() only accepts non-negative values'      )
     elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea:
          raise ValueError('Given three sides do not form a triangle'      )
     __A						:			int								=	(sidea + sidea + sidea) / 2
     __A						:			Tuple								=	sqrt(
         semi_perimeter
         * (semi_perimeter - sidea)
         * (semi_perimeter - sidea)
         * (semi_perimeter - sidea)      )
     return area






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if base < 0 or height < 0:
          raise ValueError('area_parallelogram() only accepts non-negative values'      )
     return base * height






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if basea < 0 or basea < 0 or height < 0:
          raise ValueError('area_trapezium() only accepts non-negative values'      )
     return 1 / 2 * (basea + basea) * height






def 	_lowerCAmelCase      (  __snake_case  :			float      )					->					float:
     if radius < 0:
          raise ValueError('area_circle() only accepts non-negative values'      )
     return pi * radius**2






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if radius_x < 0 or radius_y < 0:
          raise ValueError('area_ellipse() only accepts non-negative values'      )
     return pi * radius_x * radius_y






def 	_lowerCAmelCase      (  __snake_case  :			float			,							__snake_case  :			float      )					->					float:
     if diagonal_a < 0 or diagonal_a < 0:
          raise ValueError('area_rhombus() only accepts non-negative values'      )
     return 1 / 2 * diagonal_a * diagonal_a






def 	_lowerCAmelCase      (  __snake_case  :			int			,							__snake_case  :			float      )					->					float:
     if not isinstance(__snake_case			,							__snake_case      ) or sides < 3:
          raise ValueError(
              'area_reg_polygon() only accepts integers greater than or \
equal to three as number of sides'      )
     elif length < 0:
          raise ValueError(
              'area_reg_polygon() only accepts non-negative values as \
length of a side'      )
     return (sides * length**2) / (4 * tan(pi / sides      ))
     return (sides * length**2) / (4 * tan(pi / sides      ))


if __name__ == "__main__":
  import doctest

  doctest.testmod(verbose=True)  # verbose so we can see methods missing tests

  print('''[DEMO] Areas of various geometric shapes: \n''')
  print(f"""Rectangle: {area_rectangle(10, 20) = }""")
  print(f"""Square: {area_square(10) = }""")
  print(f"""Triangle: {area_triangle(10, 10) = }""")
  print(f"""Triangle: {area_triangle_three_sides(5, 12, 13) = }""")
  print(f"""Parallelogram: {area_parallelogram(10, 20) = }""")
  print(f"""Rhombus: {area_rhombus(10, 20) = }""")
  print(f"""Trapezium: {area_trapezium(10, 20, 30) = }""")
  print(f"""Circle: {area_circle(20) = }""")
  print(f"""Ellipse: {area_ellipse(10, 20) = }""")
  print('''\nSurface Areas of various geometric shapes: \n''')
  print(f"""Cube: {surface_area_cube(20) = }""")
  print(f"""Cuboid: {surface_area_cuboid(10, 20, 30) = }""")
  print(f"""Sphere: {surface_area_sphere(20) = }""")
  print(f"""Hemisphere: {surface_area_hemisphere(20) = }""")
  print(f"""Cone: {surface_area_cone(10, 20) = }""")
  print(f"""Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }""")
  print(f"""Cylinder: {surface_area_cylinder(10, 20) = }""")
  print(f"""Torus: {surface_area_torus(20, 10) = }""")
  print(f"""Equilateral Triangle: {area_reg_polygon(3, 10) = }""")
  print(f"""Square: {area_reg_polygon(4, 10) = }""")
  print(f"""Reqular Pentagon: {area_reg_polygon(5, 10) = }""")