





'''simple docstring'''


import re
from pathlib import Path
from unittest import TestCase

import pytest






@pytest.mark.integration
class     lowerCAmelCase__ (				UpperCAmelCase_    ):

       '''simple docstring'''

       def 			__snake_case      ( self					:				List[Any]       ,     a__					:				str						):

              with open(a__       ,     encoding='''utf-8'''						) as input_file:
                     UpperCAmelCase  =						re.compile(R'''(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)'''						)
                     UpperCAmelCase  =						input_file.read()
                     UpperCAmelCase  =						regexp.search(a__						)

              return match

       def 			__snake_case      ( self					:				Any       ,     a__					:				str						):

              with open(a__       ,     encoding='''utf-8'''						) as input_file:
                     UpperCAmelCase  =						re.compile(R'''#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()'''       ,     re.DOTALL						)
                     UpperCAmelCase  =						input_file.read()
                     # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
                     UpperCAmelCase  =						regexp.finditer(a__						)

              UpperCAmelCase  =						[match for match in matches if match is not None and match.group(1						) is not None]
              return matches[0] if matches else None

       def 			__snake_case      ( self					:				Optional[Any]						):
              UpperCAmelCase  =						Path('''./datasets'''						)
              UpperCAmelCase  =						list(dataset_paths.absolute().glob('''**/*.py'''						)						)

              for dataset in dataset_files:
                     if self._no_encoding_on_file_open(str(a__						)						):
                            raise AssertionError(f"open(...) must use utf-8 encoding in {dataset}"						)



       def 			__snake_case      ( self					:				int						):
              UpperCAmelCase  =						Path('''./datasets'''						)
              UpperCAmelCase  =						list(dataset_paths.absolute().glob('''**/*.py'''						)						)

              for dataset in dataset_files:
                     if self._no_print_statements(str(a__						)						):
                            raise AssertionError(f"print statement found in {dataset}. Use datasets.logger/logging instead."						)





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

_a					:			List[Any]							=    logging.get_logger(__name__)



@add_end_docstrings(a			)
class 							lowercase_						(		a			):

  '''simple docstring'''





  def __init__(  self ,			*a_ ,			**a_  )				->					str:


    """simple docstring"""
    super().__init__(*a_ ,			**a_  )
    requires_backends(self ,			'decord'  )
    self.check_model_type(a_  )
  def     snake_case_      (  self ,			a_=None ,			a_=None ,			a_=None  )				->					int:


    """simple docstring"""
    UpperCAmelCase    				=						{}
    if frame_sampling_rate is not None:
      UpperCAmelCase    				=						frame_sampling_rate
    if num_frames is not None:
      UpperCAmelCase    				=						num_frames

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


    """simple docstring"""
    return super().__call__(a_ ,			**a_  )
  def     snake_case_      (  self ,			a_ ,			a_=None ,			a_=1  )				->					Tuple:


    """simple docstring"""
    if num_frames is None:
      UpperCAmelCase    				=						self.model.config.num_frames

    if video.startswith('http://'  ) or video.startswith('https://'  ):
      UpperCAmelCase    				=						BytesIO(requests.get(a_  ).content  )

    UpperCAmelCase    				=						VideoReader(a_  )
    videoreader.seek(0  )

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

    UpperCAmelCase    				=						videoreader.get_batch(a_  ).asnumpy()
    UpperCAmelCase    				=						list(a_  )

    UpperCAmelCase    				=						self.image_processor(a_ ,			return_tensors=self.framework  )
    return model_inputs
  def     snake_case_      (  self ,			a_  )				->					Union[str, Any]:


    """simple docstring"""
    UpperCAmelCase    				=						self.model(**a_  )
    return model_outputs





  def     snake_case_      (  self ,			a_ ,			a_=5  )				->					Union[str, Any]:


    """simple docstring"""
    if top_k > self.model.config.num_labels:
      UpperCAmelCase    				=						self.model.config.num_labels

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

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


