




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

SCREAMING_SNAKE_CASE__       :      List[str]  =   logging.get_logger(__name__)




@add_end_docstrings(lowerCAmelCase__     )
class 		UpperCamelCase__	(lowerCAmelCase__     ):

    '''simple docstring'''



    def __init__(    self     ,  *UpperCamelCase__     ,  **UpperCamelCase__     )     ->      Tuple:
           super().__init__(*UpperCamelCase__     ,  **UpperCamelCase__     )
           requires_backends(self     ,  "decord"     )
           self.check_model_type(UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__=None     ,  UpperCamelCase__=None     ,  UpperCamelCase__=None     )     ->      Dict:
           lowerCamelCase   :      List[Any]			 =					{}
           if frame_sampling_rate is not None:
                  lowerCamelCase   :      Tuple			 =					frame_sampling_rate
           if num_frames is not None:
                  lowerCamelCase   :      List[str]			 =					num_frames

           lowerCamelCase   :      int			 =					{}
           if top_k is not None:
                  lowerCamelCase   :      str			 =					top_k
           return preprocess_params, {}, postprocess_params







    def __call__(    self     ,  UpperCamelCase__     ,  **UpperCamelCase__     )     ->      int:
           return super().__call__(UpperCamelCase__     ,  **UpperCamelCase__     )







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__=None     ,  UpperCamelCase__=1     )     ->      Dict:
           if num_frames is None:
                  lowerCamelCase   :      int			 =					self.model.config.num_frames

           if video.startswith("http://"     ) or video.startswith("https://"     ):
                  lowerCamelCase   :      Union[str, Any]			 =					BytesIO(requests.get(UpperCamelCase__     ).content     )

           lowerCamelCase   :      str			 =					VideoReader(UpperCamelCase__     )
           videoreader.seek(0     )

           lowerCamelCase   :      List[Any]			 =					0
           lowerCamelCase   :      Optional[int]			 =					num_frames * frame_sampling_rate - 1
           lowerCamelCase   :      Dict			 =					np.linspace(UpperCamelCase__     ,  UpperCamelCase__     ,  num=UpperCamelCase__     ,  dtype=np.intaa     )

           lowerCamelCase   :      List[Any]			 =					videoreader.get_batch(UpperCamelCase__     ).asnumpy()
           lowerCamelCase   :      Optional[int]			 =					list(UpperCamelCase__     )

           lowerCamelCase   :      int			 =					self.image_processor(UpperCamelCase__     ,  return_tensors=self.framework     )
           return model_inputs







    def     _lowercase     (    self     ,  UpperCamelCase__     )     ->      int:
           lowerCamelCase   :      List[Any]			 =					self.model(**UpperCamelCase__     )
           return model_outputs







    def     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__=5     )     ->      int:
           if top_k > self.model.config.num_labels:
                  lowerCamelCase   :      Any			 =					self.model.config.num_labels

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

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










class 			_lowercase :  # Public class to implement a graph


       """simple docstring"""




       def __init__(   self							:			Dict					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			list[list[bool]]       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  row
             lowerCamelCase__		:				Optional[Any]    =  col
             lowerCamelCase__		:				Union[str, Any]    =  graph





       def 						lowerCAmelCase     (   self							:			Optional[int]					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			list[list[bool]]       ):


             '''simple docstring'''



             return (
                 0 <= i < self.ROW
                 and 0 <= j < self.COL
                 and not visited[i][j]
                 and self.graph[i][j]
             )





       def 						lowerCAmelCase     (   self							:			Dict					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			list[list[bool]]       ):


             '''simple docstring'''



             lowerCamelCase__		:				str    =  [-1, -1, -1, 0, 0, 1, 1, 1]  # Coordinate order
             lowerCamelCase__		:				Tuple    =  [-1, 0, 1, -1, 1, -1, 0, 1]
             lowerCamelCase__		:				List[Any]    =  True  # Make those cells visited
             for k in range(8       ):
                   if self.is_safe(i + row_nbr[k]					,      j + col_nbr[k]					,      __lowerCamelCase       ):
                         self.diffs(i + row_nbr[k]					,      j + col_nbr[k]					,      __lowerCamelCase       )





       def 						lowerCAmelCase     (   self							:			List[Any]       ):  # And finally, count all islands.


             '''simple docstring'''



             lowerCamelCase__		:				List[Any]    =  [[False for j in range(self.COL       )] for i in range(self.ROW       )]
             lowerCamelCase__		:				Optional[Any]    =  0
             for i in range(self.ROW       ):
                   for j in range(self.COL       ):
                         if visited[i][j] is False and self.graph[i][j] == 1:
                               self.diffs(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase       )
                               count += 1
             return count


