
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			:     Tuple           =   logging.get_logger(__name__)




@add_end_docstrings(_A     )
class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  def __init__( self			: Union[str, Any]			,							*UpperCamelCase__			: Optional[int]			,							**UpperCamelCase__			: List[str]    )			->	Dict:







    """simple docstring"""






    super().__init__(*UpperCamelCase__			,							**UpperCamelCase__    )
    requires_backends(self			,							"""decord"""    )
    self.check_model_type(UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Tuple=None			,							UpperCamelCase__			: Tuple=None			,							UpperCamelCase__			: List[str]=None    )			->	Optional[Any]:







    """simple docstring"""






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

    __magic_name__				     =       {}
    if top_k is not None:
      __magic_name__				     =       top_k
    return preprocess_params, {}, postprocess_params
  def __call__( self			: Tuple			,							UpperCamelCase__			: Union[str, List[str]]			,							**UpperCamelCase__			: List[Any]    )			->	List[Any]:







    """simple docstring"""






    return super().__call__(UpperCamelCase__			,							**UpperCamelCase__    )
  def 							_lowercase							( self			: List[str]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: str=None			,							UpperCamelCase__			: str=1    )			->	int:







    """simple docstring"""






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

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

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

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

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

    __magic_name__				     =       self.image_processor(UpperCamelCase__			,							return_tensors=self.framework    )
    return model_inputs
  def 							_lowercase							( self			: Optional[Any]			,							UpperCamelCase__			: Optional[Any]    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       self.model(**UpperCamelCase__    )
    return model_outputs





  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: List[str]=5    )			->	str:







    """simple docstring"""






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

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

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



import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp

def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       ArgumentParser(
      description=(
          """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"""
      )					)

  # Optional arguments for the launch helper
  parser.add_argument("""--num_cores""",     type=A_,     default=1,     help="""Number of TPU cores to use (1 or 8)."""					)

  # positional
  parser.add_argument(
      """training_script""",     type=A_,     help=(
          """The full path to the single TPU training """
          """program/script to be launched in parallel, """
          """followed by all the arguments for the """
          """training script"""
      ),     )

  # rest from the training program
  parser.add_argument("""training_script_args""",     nargs=A_					)

  return parser.parse_args()

def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       parse_args()

  # Import training_script as a module.
  __magic_name__				     =       Path(args.training_script					)
  sys.path.append(str(script_fpath.parent.resolve()					)					)
  __magic_name__				     =       script_fpath.stem
  __magic_name__				     =       importlib.import_module(A_					)

  # Patch sys.argv
  __magic_name__				     =       [args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores					)]

  xmp.spawn(mod._mp_fn,     args=(),     nprocs=args.num_cores					)


if __name__ == "__main__":
    main()

