




import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


lowerCamelCase	:	List[Any]				=   logging.getLogger()




@unittest.skip("""Temporarily disable the doc tests."""							)
@require_torch
@require_tf
@slow
class 						__lowercase		(unittest.TestCase							):




      """simple docstring"""





      def      UpperCAmelCase				(				self    ,				A    ,				A = None    ,				A = None    ,				A = None    ,				A = True    ,				)		->    List[str]:
         snake_case				:    int           =	[file for file in os.listdir(A     ) if os.path.isfile(os.path.join(A    ,				A     )     )]

         if identifier is not None:
            snake_case				:    List[Any]           =	[file for file in files if identifier in file]

         if n_identifier is not None:
            if isinstance(A    ,				A     ):
               for n_ in n_identifier:
                  snake_case				:    Optional[int]           =	[file for file in files if n_ not in file]
            else:
               snake_case				:    int           =	[file for file in files if n_identifier not in file]

         snake_case				:    Any           =	ignore_files or []
         ignore_files.append("""__init__.py"""     )
         snake_case				:    Dict           =	[file for file in files if file not in ignore_files]

         for file in files:
            # Open all files
            print("""Testing"""    ,				A     )

            if only_modules:
               snake_case				:    Any           =	file.split("""."""     )[0]
               try:
                  snake_case				:    List[Any]           =	getattr(A    ,				A     )
                  snake_case				:    List[Any]           =	doctest.DocTestSuite(A     )
                  snake_case				:    Tuple           =	unittest.TextTestRunner().run(A     )
                  self.assertIs(len(result.failures     )    ,				0     )
               except AttributeError:
                  logger.info(f"""{module_identifier} is not a module."""     )
            else:
               snake_case				:    Tuple           =	doctest.testfile(str("""..""" / directory / file     )    ,				optionflags=doctest.ELLIPSIS     )
               self.assertIs(result.failed    ,				0     )

      def      UpperCAmelCase				(				self     )		->    str:
         snake_case				:    Optional[int]           =	Path("""src/transformers"""     )
         snake_case				:    str           =	"""modeling"""
         snake_case				:    Tuple           =	[
             """modeling_ctrl.py""",
             """modeling_tf_ctrl.py""",
         ]
         self.analyze_directory(A    ,				identifier=A    ,				ignore_files=A     )

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    str           =	Path("""src/transformers"""     )
         snake_case				:    List[str]           =	"""tokenization"""
         self.analyze_directory(A    ,				identifier=A     )

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case				:    Tuple           =	Path("""src/transformers"""     )
         snake_case				:    str           =	"""configuration"""
         self.analyze_directory(A    ,				identifier=A     )

      def      UpperCAmelCase				(				self     )		->    List[str]:
         snake_case				:    Union[str, Any]           =	Path("""src/transformers"""     )
         snake_case				:    int           =	["""configuration""", """modeling""", """tokenization"""]
         self.analyze_directory(A    ,				n_identifier=A     )

      def      UpperCAmelCase				(				self     )		->    List[Any]:
         snake_case				:    Union[str, Any]           =	Path("""docs/source"""     )
         snake_case				:    Optional[int]           =	["""favicon.ico"""]
         self.analyze_directory(A    ,				ignore_files=A    ,				only_modules=A     )











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




@add_end_docstrings(UpperCamelCase__							)
class 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      def __init__(				self    ,				*A    ,				**A     )		->    Optional[int]:
         super().__init__(*A    ,				**A     )
         requires_backends(self    ,				"""decord"""     )
         self.check_model_type(A     )

      def      UpperCAmelCase				(				self    ,				A=None    ,				A=None    ,				A=None     )		->    int:
         snake_case				:    Any           =	{}
         if frame_sampling_rate is not None:
            snake_case				:    int           =	frame_sampling_rate
         if num_frames is not None:
            snake_case				:    Union[str, Any]           =	num_frames

         snake_case				:    str           =	{}
         if top_k is not None:
            snake_case				:    Optional[int]           =	top_k
         return preprocess_params, {}, postprocess_params

      def __call__(				self    ,				A    ,				**A     )		->    Dict:
         return super().__call__(A    ,				**A     )

      def      UpperCAmelCase				(				self    ,				A    ,				A=None    ,				A=1     )		->    Tuple:
         if num_frames is None:
            snake_case				:    Tuple           =	self.model.config.num_frames

         if video.startswith("""http://"""     ) or video.startswith("""https://"""     ):
            snake_case				:    Optional[int]           =	BytesIO(requests.get(A     ).content     )

         snake_case				:    Optional[Any]           =	VideoReader(A     )
         videoreader.seek(0     )

         snake_case				:    Optional[Any]           =	0
         snake_case				:    Optional[Any]           =	num_frames * frame_sampling_rate - 1
         snake_case				:    Any           =	np.linspace(A    ,				A    ,				num=A    ,				dtype=np.intaa     )

         snake_case				:    int           =	videoreader.get_batch(A     ).asnumpy()
         snake_case				:    List[Any]           =	list(A     )

         snake_case				:    Optional[Any]           =	self.image_processor(A    ,				return_tensors=self.framework     )
         return model_inputs

      def      UpperCAmelCase				(				self    ,				A     )		->    List[str]:
         snake_case				:    Dict           =	self.model(**A     )
         return model_outputs

      def      UpperCAmelCase				(				self    ,				A    ,				A=5     )		->    int:
         if top_k > self.model.config.num_labels:
            snake_case				:    str           =	self.model.config.num_labels

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

         snake_case				:    List[Any]           =	scores.tolist()
         snake_case				:    str           =	ids.tolist()
         return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(A    ,				A     )]





