
"""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

SCREAMING_SNAKE_CASE_					     =	logging.get_logger(__name__)
@add_end_docstrings(A__ )
class       lowerCAmelCase_		(				A__ ):



							'''simple docstring'''





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




							def    A__						( self    ,				snake_case_=None    ,				snake_case_=None    ,				snake_case_=None				)       ->  Dict:
													__lowerCAmelCase     =  {}
													if frame_sampling_rate is not None:
																			__lowerCAmelCase     =  frame_sampling_rate
													if num_frames is not None:
																			__lowerCAmelCase     =  num_frames

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




							def __call__( self    ,				snake_case_    ,				**snake_case_				)       ->  List[str]:
													return super().__call__(snake_case_    ,				**snake_case_				)




							def    A__						( self    ,				snake_case_    ,				snake_case_=None    ,				snake_case_=1				)       ->  Optional[Any]:
													if num_frames is None:
																			__lowerCAmelCase     =  self.model.config.num_frames

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

													__lowerCAmelCase     =  VideoReader(snake_case_				)
													videoreader.seek(0				)

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

													__lowerCAmelCase     =  videoreader.get_batch(snake_case_				).asnumpy()
													__lowerCAmelCase     =  list(snake_case_				)

													__lowerCAmelCase     =  self.image_processor(snake_case_    ,				return_tensors=self.framework				)
													return model_inputs




							def    A__						( self    ,				snake_case_				)       ->  int:
													__lowerCAmelCase     =  self.model(**snake_case_				)
													return model_outputs




							def    A__						( self    ,				snake_case_    ,				snake_case_=5				)       ->  List[str]:
													if top_k > self.model.config.num_labels:
																			__lowerCAmelCase     =  self.model.config.num_labels

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

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


"""simple docstring"""
import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
			from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm

def  lowercase     (_lowerCAmelCase						):
						if is_torch_version("""<""" ,    """2.0.0"""						) or not hasattr(_lowerCAmelCase ,    """_dynamo"""						):
												return False
						return isinstance(_lowerCAmelCase ,    torch._dynamo.eval_frame.OptimizedModule						)

def  lowercase     (_lowerCAmelCase ,    _lowerCAmelCase = True						):
						__lowerCAmelCase     =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

						__lowerCAmelCase     =  is_compiled_module(_lowerCAmelCase						)
						if is_compiled:
												__lowerCAmelCase     =  model
												__lowerCAmelCase     =  model._orig_mod

						if is_deepspeed_available():
												options += (DeepSpeedEngine,)

						while isinstance(_lowerCAmelCase ,    _lowerCAmelCase						):
												__lowerCAmelCase     =  model.module

						if not keep_fpaa_wrapper:
												__lowerCAmelCase     =  getattr(_lowerCAmelCase ,    """forward"""						)
												__lowerCAmelCase     =  model.__dict__.pop("""_original_forward""" ,    _lowerCAmelCase						)
												if original_forward is not None:
																		while hasattr(_lowerCAmelCase ,    """__wrapped__"""						):
																								__lowerCAmelCase     =  forward.__wrapped__
																								if forward == original_forward:
																														break
																		__lowerCAmelCase     =  forward
												if getattr(_lowerCAmelCase ,    """_converted_to_transformer_engine""" ,    _lowerCAmelCase						):
																		convert_model(_lowerCAmelCase ,    to_transformer_engine=_lowerCAmelCase						)

						if is_compiled:
												__lowerCAmelCase     =  model
												__lowerCAmelCase     =  compiled_model

						return model

def  lowercase     ():
						PartialState().wait_for_everyone()

def  lowercase     (_lowerCAmelCase ,    _lowerCAmelCase						):
						if PartialState().distributed_type == DistributedType.TPU:
												xm.save(_lowerCAmelCase ,    _lowerCAmelCase						)
						elif PartialState().local_process_index == 0:
												torch.save(_lowerCAmelCase ,    _lowerCAmelCase						)

@contextmanager
def  lowercase     (**_lowerCAmelCase						):
						for key, value in kwargs.items():
												__lowerCAmelCase     =  str(_lowerCAmelCase						)

						yield

						for key in kwargs:
												if key.upper() in os.environ:
																		del os.environ[key.upper()]

def  lowercase     (_lowerCAmelCase						):
						if not hasattr(_lowerCAmelCase ,    """__qualname__"""						) and not hasattr(_lowerCAmelCase ,    """__name__"""						):
												__lowerCAmelCase     =  getattr(_lowerCAmelCase ,    """__class__""" ,    _lowerCAmelCase						)
						if hasattr(_lowerCAmelCase ,    """__qualname__"""						):
												return obj.__qualname__
						if hasattr(_lowerCAmelCase ,    """__name__"""						):
												return obj.__name__
						return str(_lowerCAmelCase						)

def  lowercase     (_lowerCAmelCase ,    _lowerCAmelCase						):
						for key, value in source.items():
												if isinstance(_lowerCAmelCase ,    _lowerCAmelCase						):
																		__lowerCAmelCase     =  destination.setdefault(_lowerCAmelCase ,    {}						)
																		merge_dicts(_lowerCAmelCase ,    _lowerCAmelCase						)
												else:
																		__lowerCAmelCase     =  value

						return destination



def  lowercase     (_lowerCAmelCase = None						):
						if port is None:
												__lowerCAmelCase     =  2_9500
						with socket.socket(socket.AF_INET ,    socket.SOCK_STREAM						) as s:
												return s.connect_ex(("""localhost""", port)						) == 0
