




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

UpperCamelCase								=	logging.get_logger(__name__)





@add_end_docstrings(UpperCamelCase__       )
class 					__lowerCamelCase			(       UpperCamelCase__       ):




    """simple docstring"""

    def __init__(			self	:	List[Any]  ,      *SCREAMING_SNAKE_CASE__	:	int  ,      **SCREAMING_SNAKE_CASE__	:	Any  ) ->			List[Any]:
         super().__init__(*SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )
         requires_backends(self  ,      "decord"  )
         self.check_model_type(SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Dict  ,      SCREAMING_SNAKE_CASE__	:	Any=None  ,      SCREAMING_SNAKE_CASE__	:	str=None  ,      SCREAMING_SNAKE_CASE__	:	Optional[int]=None  ) ->			Any:
         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	:	Any  ,      SCREAMING_SNAKE_CASE__	:	Union[str, List[str]]  ,      **SCREAMING_SNAKE_CASE__	:	Any  ) ->			Optional[int]:
         return super().__call__(SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )


    def   a (			self	:	Any  ,      SCREAMING_SNAKE_CASE__	:	Any  ,      SCREAMING_SNAKE_CASE__	:	List[str]=None  ,      SCREAMING_SNAKE_CASE__	:	Union[str, Any]=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(SCREAMING_SNAKE_CASE__  ).content  )

         lowerCAmelCase__            =					VideoReader(SCREAMING_SNAKE_CASE__  )
         videoreader.seek(0  )

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

         lowerCAmelCase__            =					videoreader.get_batch(SCREAMING_SNAKE_CASE__  ).asnumpy()
         lowerCAmelCase__            =					list(SCREAMING_SNAKE_CASE__  )

         lowerCAmelCase__            =					self.image_processor(SCREAMING_SNAKE_CASE__  ,      return_tensors=self.framework  )
         return model_inputs


    def   a (			self	:	Optional[Any]  ,      SCREAMING_SNAKE_CASE__	:	Optional[int]  ) ->			Union[str, Any]:
         lowerCAmelCase__            =					self.model(**SCREAMING_SNAKE_CASE__  )
         return model_outputs


    def   a (			self	:	Dict  ,      SCREAMING_SNAKE_CASE__	:	List[str]  ,      SCREAMING_SNAKE_CASE__	:	List[str]=5  ) ->			Any:
         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(SCREAMING_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(SCREAMING_SNAKE_CASE__  ,      SCREAMING_SNAKE_CASE__  )]

'''simple docstring'''




import timeit

import numpy as np

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    def wrapper(*UpperCamelCase__							,    **UpperCamelCase__							):
        __lowerCamelCase            =    timeit.default_timer()
        __lowerCamelCase            =    func(*UpperCamelCase__							,    **UpperCamelCase__							)
        __lowerCamelCase            =    timeit.default_timer() - starttime
        return delta

    __lowerCamelCase            =    func.__name__

    return wrapper






def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__=1_00							,    UpperCamelCase__=None							)      ->       Dict:
    __lowerCamelCase            =    []
    __lowerCamelCase            =    seq_shapes or {}
    for i in range(UpperCamelCase__							):
        __lowerCamelCase            =    {}
        for col_id, (k, v) in enumerate(features.items()							):
            if isinstance(UpperCamelCase__							,    _ArrayXD							):
                __lowerCamelCase            =    np.random.rand(*v.shape							).astype(v.dtype							)
            elif isinstance(UpperCamelCase__							,    datasets.Value							):
                if v.dtype == "string":
                    __lowerCamelCase            =    '''The small grey turtle was surprisingly fast when challenged.'''
                else:
                    __lowerCamelCase            =    np.random.randint(10							,    size=1							).astype(v.dtype							).item()
            elif isinstance(UpperCamelCase__							,    datasets.Sequence							):
                while isinstance(UpperCamelCase__							,    datasets.Sequence							):
                    __lowerCamelCase            =    v.feature
                __lowerCamelCase            =    seq_shapes[k]
                __lowerCamelCase            =    np.random.rand(*UpperCamelCase__							).astype(v.dtype							)
            __lowerCamelCase            =    data

        dummy_data.append((i, example)							)

    return dummy_data






def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__							,    UpperCamelCase__=1_00							,    UpperCamelCase__=None							)      ->       Dict:
    __lowerCamelCase            =    generate_examples(UpperCamelCase__							,    num_examples=UpperCamelCase__							,    seq_shapes=UpperCamelCase__							)

    with ArrowWriter(features=UpperCamelCase__							,    path=UpperCamelCase__							) as writer:
        for key, record in dummy_data:
            __lowerCamelCase            =    features.encode_example(UpperCamelCase__							)
            writer.write(UpperCamelCase__							)

        __lowerCamelCase      ,    __lowerCamelCase            =    writer.finalize()

    if not num_final_examples == num_examples:
        raise ValueError(
            f"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}."""							)

    __lowerCamelCase            =    datasets.Dataset.from_file(filename=UpperCamelCase__							,    info=datasets.DatasetInfo(features=UpperCamelCase__							)							)

    return dataset
