




"""simple docstring"""

from io import BytesIO
from typing import List, Union

import requests

from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_decord_available():
       import numpy as np
       from decord import VideoReader


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

a					=			logging.get_logger(__name__)





@add_end_docstrings(_a							)
class 				lowercase_       (     _a							):



 '''simple docstring'''

 def __init__( self       :       Any    ,							*_UpperCAmelCase       :       Dict    ,							**_UpperCAmelCase       :       Union[str, Any]		):
       super().__init__(*UpperCamelCase__    ,							**UpperCamelCase__		)
       requires_backends(self    ,							'decord'		)
       self.check_model_type(UpperCamelCase__		)

 def 			lowerCAmelCase_							( self       :       Optional[int]    ,							_UpperCAmelCase       :       Optional[int]=None    ,							_UpperCAmelCase       :       Optional[Any]=None    ,							_UpperCAmelCase       :       Optional[Any]=None		):
       _A					   =   {}
       if frame_sampling_rate is not None:
             _A					   =   frame_sampling_rate
       if num_frames is not None:
             _A					   =   num_frames

       _A					   =   {}
       if top_k is not None:
             _A					   =   top_k
       return preprocess_params, {}, postprocess_params

 def __call__( self       :       List[str]    ,							_UpperCAmelCase       :       Union[str, List[str]]    ,							**_UpperCAmelCase       :       Dict		):
       return super().__call__(UpperCamelCase__    ,							**UpperCamelCase__		)

 def 			lowerCAmelCase_							( self       :       Tuple    ,							_UpperCAmelCase       :       Union[str, Any]    ,							_UpperCAmelCase       :       Tuple=None    ,							_UpperCAmelCase       :       Tuple=1		):







       if num_frames is None:
             _A					   =   self.model.config.num_frames

       if video.startswith('http://'		) or video.startswith('https://'		):
             _A					   =   BytesIO(requests.get(UpperCamelCase__		).content		)

       _A					   =   VideoReader(UpperCamelCase__		)
       videoreader.seek(0		)

       _A					   =   0
       _A					   =   num_frames * frame_sampling_rate - 1
       _A					   =   np.linspace(UpperCamelCase__    ,							UpperCamelCase__    ,							num=UpperCamelCase__    ,							dtype=np.intaa		)

       _A					   =   videoreader.get_batch(UpperCamelCase__		).asnumpy()
       _A					   =   list(UpperCamelCase__		)

       _A					   =   self.image_processor(UpperCamelCase__    ,							return_tensors=self.framework		)
       return model_inputs

 def 			lowerCAmelCase_							( self       :       Union[str, Any]    ,							_UpperCAmelCase       :       List[str]		):
       _A					   =   self.model(**UpperCamelCase__		)
       return model_outputs



 def 			lowerCAmelCase_							( self       :       int    ,							_UpperCAmelCase       :       str    ,							_UpperCAmelCase       :       List[Any]=5		):







       if top_k > self.model.config.num_labels:
             _A					   =   self.model.config.num_labels

       if self.framework == "pt":
             _A					   =   model_outputs.logits.softmax(-1		)[0]
             _A   ,    _A					   =   probs.topk(UpperCamelCase__		)
       else:
             raise ValueError(F'''Unsupported framework: {self.framework}'''		)

       _A					   =   scores.tolist()
       _A					   =   ids.tolist()
       return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__    ,							UpperCamelCase__		)]






'''simple docstring'''


from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule







def 				__lowerCamelCase				(   A__    ,						A__    ,						A__=1e-1_2    )       ->	Dict:






   """simple docstring"""
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   return jnp.matmul(A__    ,						norm_emb_a.T    )

class  SCREAMING_SNAKE_CASE (  nn.Module		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  jnp.floataa






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  FlaxCLIPVisionModule(self.config.vision_config )
       UpperCamelCase					=  nn.Dense(self.config.projection_dim  ,						use_bias=UpperCamelCase__  ,						dtype=self.dtype )

       UpperCamelCase					=  self.param('concept_embeds'  ,						jax.nn.initializers.ones  ,						(1_7, self.config.projection_dim) )
       UpperCamelCase					=  self.param(
           'special_care_embeds'  ,						jax.nn.initializers.ones  ,						(3, self.config.projection_dim) )

       UpperCamelCase					=  self.param('concept_embeds_weights'  ,						jax.nn.initializers.ones  ,						(1_7,) )
       UpperCamelCase					=  self.param('special_care_embeds_weights'  ,						jax.nn.initializers.ones  ,						(3,) )






    def __call__(  self      :					str  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.vision_model(UpperCamelCase__ )[1]
       UpperCamelCase					=  self.visual_projection(UpperCamelCase__ )

       UpperCamelCase					=  jax_cosine_distance(UpperCamelCase__  ,						self.special_care_embeds )
       UpperCamelCase					=  jax_cosine_distance(UpperCamelCase__  ,						self.concept_embeds )

       # increase this value to create a stronger `nfsw` filter
       # at the cost of increasing the possibility of filtering benign image inputs
       UpperCamelCase					=  0.0

       UpperCamelCase					=  special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
       UpperCamelCase					=  jnp.round(UpperCamelCase__  ,						3 )
       UpperCamelCase					=  jnp.any(special_scores > 0  ,						axis=1  ,						keepdims=UpperCamelCase__ )
       # Use a lower threshold if an image has any special care concept
       UpperCamelCase					=  is_special_care * 0.0_1

       UpperCamelCase					=  cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
       UpperCamelCase					=  jnp.round(UpperCamelCase__  ,						3 )
       UpperCamelCase					=  jnp.any(concept_scores > 0  ,						axis=1 )

       return has_nsfw_concepts

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  CLIPConfig
    _SCREAMING_SNAKE_CASE	  =  """clip_input"""
    _SCREAMING_SNAKE_CASE	  =  FlaxStableDiffusionSafetyCheckerModule






    def __init__(  self      :					Union[str, Any]  ,						UpperCamelCase__      :					CLIPConfig  ,						UpperCamelCase__      :					Optional[Tuple] = None  ,						UpperCamelCase__      :					int = 0  ,						UpperCamelCase__      :					jnp.dtype = jnp.floataa  ,						UpperCamelCase__      :					bool = True  ,						**UpperCamelCase__      :					List[str]  ,						):


       """simple docstring"""







       if input_shape is None:
          UpperCamelCase					=  (1, 2_2_4, 2_2_4, 3)
       UpperCamelCase					=  self.module_class(config=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						**UpperCamelCase__ )
       super().__init__(UpperCamelCase__  ,						UpperCamelCase__  ,						input_shape=UpperCamelCase__  ,						seed=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						_do_init=_do_init )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					jax.random.KeyArray  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					FrozenDict = None ):


       """simple docstring"""







       UpperCamelCase					=  jax.random.normal(UpperCamelCase__  ,						UpperCamelCase__ )

       UpperCamelCase				,      UpperCamelCase					=  jax.random.split(UpperCamelCase__ )
       UpperCamelCase					=  {'params': params_rng, 'dropout': dropout_rng}

       UpperCamelCase					=  self.module.init(UpperCamelCase__  ,						UpperCamelCase__ )['params']

       return random_params






    def __call__(  self      :					List[Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					dict = None  ,						):


       """simple docstring"""







       UpperCamelCase					=  jnp.transpose(UpperCamelCase__  ,						(0, 2, 3, 1) )

       return self.module.apply(
           {'params': params or self.params}  ,						jnp.array(UpperCamelCase__  ,						dtype=jnp.floataa )  ,						rngs={}  ,						)

