
'''simple docstring'''







import json
import logging
import os
import socket

import git
import numpy as np
import torch


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d -  %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
_lowercase :  Optional[Any]    							=       logging.getLogger(__name__)
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: str							):



						"""simple docstring"""





						lowercase_	:     Optional[int]													=       git.Repo(search_parent_directories=__SCREAMING_SNAKE_CASE							)
						lowercase_	:     Any													=       {
						    '''repo_id''': str(__SCREAMING_SNAKE_CASE							),
						    '''repo_sha''': str(repo.head.object.hexsha							),
						    '''repo_branch''': str(repo.active_branch							),
						}

						with open(os.path.join(__SCREAMING_SNAKE_CASE      ,      '''git_log.json'''							)      ,      '''w'''							) as f:
												json.dump(__SCREAMING_SNAKE_CASE      ,      __SCREAMING_SNAKE_CASE      ,      indent=4							)
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: str							):



						"""simple docstring"""





						if params.n_gpu <= 0:
												lowercase_	:     Any													=       0
												lowercase_	:     Any													=       -1
												lowercase_	:     str													=       True
												lowercase_	:     List[str]													=       False
												return

						assert torch.cuda.is_available()

						logger.info('''Initializing GPUs'''							)
						if params.n_gpu > 1:
												assert params.local_rank != -1

												lowercase_	:     str													=       int(os.environ['''WORLD_SIZE''']							)
												lowercase_	:     Any													=       int(os.environ['''N_GPU_NODE''']							)
												lowercase_	:     int													=       int(os.environ['''RANK''']							)

												# number of nodes / node ID
												lowercase_	:     Tuple													=       params.world_size // params.n_gpu_per_node
												lowercase_	:     Any													=       params.global_rank // params.n_gpu_per_node
												lowercase_	:     Dict													=       True

												assert params.n_nodes == int(os.environ['''N_NODES''']							)
												assert params.node_id == int(os.environ['''NODE_RANK''']							)

						# local job (single GPU)
						else:
												assert params.local_rank == -1

												lowercase_	:     List[str]													=       1
												lowercase_	:     Tuple													=       0
												lowercase_	:     Optional[int]													=       0
												lowercase_	:     Any													=       0
												lowercase_	:     Optional[Any]													=       1
												lowercase_	:     Union[str, Any]													=       1
												lowercase_	:     Any													=       False

						# sanity checks
						assert params.n_nodes >= 1
						assert 0 <= params.node_id < params.n_nodes
						assert 0 <= params.local_rank <= params.global_rank < params.world_size
						assert params.world_size == params.n_nodes * params.n_gpu_per_node

						# define whether this is the master process / if we are in multi-node distributed mode
						lowercase_	:     str													=       params.node_id == 0 and params.local_rank == 0
						lowercase_	:     List[str]													=       params.n_nodes > 1

						# summary
						lowercase_	:     List[Any]													=       F'''--- Global rank: {params.global_rank} - '''
						logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes							)
						logger.info(PREFIX + '''Node ID        : %i''' % params.node_id							)
						logger.info(PREFIX + '''Local rank     : %i''' % params.local_rank							)
						logger.info(PREFIX + '''World size     : %i''' % params.world_size							)
						logger.info(PREFIX + '''GPUs per node  : %i''' % params.n_gpu_per_node							)
						logger.info(PREFIX + '''Master         : %s''' % str(params.is_master							)							)
						logger.info(PREFIX + '''Multi-node     : %s''' % str(params.multi_node							)							)
						logger.info(PREFIX + '''Multi-GPU      : %s''' % str(params.multi_gpu							)							)
						logger.info(PREFIX + '''Hostname       : %s''' % socket.gethostname()							)

						# set GPU device
						torch.cuda.set_device(params.local_rank							)

						# initialize multi-GPU
						if params.multi_gpu:
												logger.info('''Initializing PyTorch distributed'''							)
												torch.distributed.init_process_group(
												    init_method='''env://'''      ,      backend='''nccl'''      ,      )




def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: str							):



						"""simple docstring"""





						np.random.seed(args.seed							)
						torch.manual_seed(args.seed							)
						if args.n_gpu > 0:
												torch.cuda.manual_seed_all(args.seed							)




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

__lowerCamelCase							 =     logging.get_logger(__name__)
@add_end_docstrings(__A       )
class 			UpperCamelCase__(	__A       ):





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





						def  snake_case__		(				self						,__UpperCAmelCase=None						,__UpperCAmelCase=None						,__UpperCAmelCase=None   )    -> int:
													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						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> Dict:
													return super().__call__(__UpperCAmelCase						,**__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=None						,__UpperCAmelCase=1   )    -> Union[str, Any]:
													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  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													A__		   =							self.model(**__UpperCAmelCase   )
													return model_outputs





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=5   )    -> Union[str, Any]:
													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   )]





