



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

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

@add_end_docstrings(_lowercase	)
class   _A   ( _lowercase	):


      '''simple docstring'''





      def __init__(	self	:							Tuple							,      *lowerCamelCase	:							Dict							,      **lowerCamelCase	:							Dict	):






       '''simple docstring'''



       super().__init__(*lowerCamelCase							,      **lowerCamelCase	)
       requires_backends(self							,      "decord"	)
       self.check_model_type(lowerCamelCase	)



      def     _snake_case	(	self	:							int							,      lowerCamelCase	:							List[str]=None							,      lowerCamelCase	:							Any=None							,      lowerCamelCase	:							Any=None	):






       '''simple docstring'''



       __lowercase		       =			{}
       if frame_sampling_rate is not None:
        __lowercase		       =			frame_sampling_rate
       if num_frames is not None:
        __lowercase		       =			num_frames

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



      def __call__(	self	:							List[str]							,      lowerCamelCase	:							Union[str, List[str]]							,      **lowerCamelCase	:							Any	):






       '''simple docstring'''



       return super().__call__(lowerCamelCase							,      **lowerCamelCase	)



      def     _snake_case	(	self	:							Any							,      lowerCamelCase	:							int							,      lowerCamelCase	:							Any=None							,      lowerCamelCase	:							Tuple=1	):






       '''simple docstring'''



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

       if video.startswith("http://"	) or video.startswith("https://"	):
        __lowercase		       =			BytesIO(requests.get(lowerCamelCase	).content	)

       __lowercase		       =			VideoReader(lowerCamelCase	)
       videoreader.seek(0	)

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

       __lowercase		       =			videoreader.get_batch(lowerCamelCase	).asnumpy()
       __lowercase		       =			list(lowerCamelCase	)

       __lowercase		       =			self.image_processor(lowerCamelCase							,      return_tensors=self.framework	)
       return model_inputs



      def     _snake_case	(	self	:							int							,      lowerCamelCase	:							str	):






       '''simple docstring'''



       __lowercase		       =			self.model(**lowerCamelCase	)
       return model_outputs



      def     _snake_case	(	self	:							int							,      lowerCamelCase	:							Any							,      lowerCamelCase	:							Any=5	):






       '''simple docstring'''



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

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

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








from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

snake_case__					:     Union[str, Any]    		=   TypeVar("""T""")
snake_case__					:     Optional[int]    		=   TypeVar("""U""")

class   _A   ( Generic[T, U]	):


						'''simple docstring'''





						def __init__(	self	:							Optional[int]							,      lowerCamelCase	:							T | None							,      lowerCamelCase	:							U | None	):






							'''simple docstring'''



							__lowercase		       =			key
							__lowercase		       =			val
							__lowercase		       =			None
							__lowercase		       =			None



						def __repr__(	self	:							Any	):






							'''simple docstring'''



							return (
							    f"""Node: key: {self.key}, val: {self.val}, """
							    f"""has next: {bool(self.next	)}, has prev: {bool(self.prev	)}"""
							)

class   _A   ( Generic[T, U]	):


						'''simple docstring'''





						def __init__(	self	:							Dict	):






							'''simple docstring'''



							__lowercase		       =			DoubleLinkedListNode(lowerCamelCase							,      lowerCamelCase	)
							__lowercase		       =			DoubleLinkedListNode(lowerCamelCase							,      lowerCamelCase	)
							__lowercase       ,    __lowercase		       =			self.rear, self.head



						def __repr__(	self	:							Optional[Any]	):






							'''simple docstring'''



							__lowercase		       =			["DoubleLinkedList"]
							__lowercase		       =			self.head
							while node.next is not None:
								rep.append(str(lowerCamelCase	)	)
								__lowercase		       =			node.next
							rep.append(str(self.rear	)	)
							return ",\n    ".join(lowerCamelCase	)



						def     _snake_case	(	self	:							Union[str, Any]							,      lowerCamelCase	:							DoubleLinkedListNode[T, U]	):






							'''simple docstring'''



							__lowercase		       =			self.rear.prev

							# All nodes other than self.head are guaranteed to have non-None previous
							assert previous is not None

							__lowercase		       =			node
							__lowercase		       =			previous
							__lowercase		       =			node
							__lowercase		       =			self.rear



						def     _snake_case	(	self	:							Optional[int]							,      lowerCamelCase	:							DoubleLinkedListNode[T, U]	):






							'''simple docstring'''



							if node.prev is None or node.next is None:
								return None

							__lowercase		       =			node.next
							__lowercase		       =			node.prev
							__lowercase		       =			None
							__lowercase		       =			None
							return node

class   _A   ( Generic[T, U]	):


						'''simple docstring'''





						_snake_case			:     dict[Callable[[T], U], LRUCache[T, U]]      							=      {}



						def __init__(	self	:							List[Any]							,      lowerCamelCase	:							int	):






							'''simple docstring'''



							__lowercase		       =			DoubleLinkedList()
							__lowercase		       =			capacity
							__lowercase		       =			0
							__lowercase		       =			0
							__lowercase		       =			0
							__lowercase		       =			{}



						def __repr__(	self	:							Optional[Any]	):






							'''simple docstring'''



							return (
							    f"""CacheInfo(hits={self.hits}, misses={self.miss}, """
							    f"""capacity={self.capacity}, current size={self.num_keys})"""
							)



						def __contains__(	self	:							Dict							,      lowerCamelCase	:							T	):






							'''simple docstring'''



							return key in self.cache



						def     _snake_case	(	self	:							List[Any]							,      lowerCamelCase	:							T	):






							'''simple docstring'''



							if key in self.cache:
								self.hits += 1
								__lowercase		       =			self.cache[key]
								__lowercase		       =			self.list.remove(self.cache[key]	)
								assert node == value_node

								# node is guaranteed not None because it is in self.cache
								assert node is not None
								self.list.add(lowerCamelCase	)
								return node.val
							self.miss += 1
							return None



						def     _snake_case	(	self	:							Union[str, Any]							,      lowerCamelCase	:							T							,      lowerCamelCase	:							U	):






							'''simple docstring'''



							if key not in self.cache:
								if self.num_keys >= self.capacity:
									# delete first node (oldest) when over capacity
									__lowercase		       =			self.list.head.next

									# guaranteed to have a non-None first node when num_keys > 0
									# explain to type checker via assertions
									assert first_node is not None
									assert first_node.key is not None
									assert (
									    self.list.remove(lowerCamelCase	) is not None
									)  # node guaranteed to be in list assert node.key is not None

									del self.cache[first_node.key]
									self.num_keys -= 1
								__lowercase		       =			DoubleLinkedListNode(lowerCamelCase							,      lowerCamelCase	)
								self.list.add(self.cache[key]	)
								self.num_keys += 1

							else:
								# bump node to the end of the list, update value
								__lowercase		       =			self.list.remove(self.cache[key]	)
								assert node is not None  # node guaranteed to be in list
								__lowercase		       =			value
								self.list.add(lowerCamelCase	)



						@classmethod
						def     _snake_case	(	cls	:							Union[str, Any]							,      lowerCamelCase	:							int = 128	):






							'''simple docstring'''



							def cache_decorator_inner(lowerCamelCase	:							Callable[[T], U]	) -> Callable[..., U]:
								def cache_decorator_wrapper(*lowerCamelCase	:							T	) -> U:
									if func not in cls.decorator_function_to_instance_map:
										__lowercase		       =			LRUCache(lowerCamelCase	)

									__lowercase		       =			cls.decorator_function_to_instance_map[func].get(args[0]	)
									if result is None:
										__lowercase		       =			func(*lowerCamelCase	)
										cls.decorator_function_to_instance_map[func].put(args[0]							,      lowerCamelCase	)
									return result

								def cache_info() -> LRUCache[T, U]:
									return cls.decorator_function_to_instance_map[func]

								setattr(lowerCamelCase							,      "cache_info"							,      lowerCamelCase	)  # noqa: B010

								return cache_decorator_wrapper

							return cache_decorator_inner


if __name__ == "__main__":
	import doctest

	doctest.testmod()



