



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

SCREAMING_SNAKE_CASE_:str					=						logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE__   )
class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def __init__(	self,		*lowerCamelCase__,		**lowerCamelCase__		):
        super().__init__(*lowerCamelCase__,		**lowerCamelCase__		)
        requires_backends(self,		"""decord"""		)
        self.check_model_type(lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__=None,		lowerCamelCase__=None,		lowerCamelCase__=None		):
        A			:	List[Any]										=       {}
        if frame_sampling_rate is not None:
            A			:	Union[str, Any]										=       frame_sampling_rate
        if num_frames is not None:
            A			:	str										=       num_frames

        A			:	Tuple										=       {}
        if top_k is not None:
            A			:	Dict										=       top_k
        return preprocess_params, {}, postprocess_params






    def __call__(	self,		lowerCamelCase__,		**lowerCamelCase__		):
        return super().__call__(lowerCamelCase__,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__=None,		lowerCamelCase__=1		):
        if num_frames is None:
            A			:	List[Any]										=       self.model.config.num_frames

        if video.startswith("""http://"""		) or video.startswith("""https://"""		):
            A			:	Any										=       BytesIO(requests.get(lowerCamelCase__		).content		)

        A			:	Any										=       VideoReader(lowerCamelCase__		)
        videoreader.seek(0		)

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

        A			:	List[Any]										=       videoreader.get_batch(lowerCamelCase__		).asnumpy()
        A			:	Dict										=       list(lowerCamelCase__		)

        A			:	Union[str, Any]										=       self.image_processor(lowerCamelCase__,		return_tensors=self.framework		)
        return model_inputs






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        A			:	Optional[Any]										=       self.model(**lowerCamelCase__		)
        return model_outputs






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__=5		):
        if top_k > self.model.config.num_labels:
            A			:	int										=       self.model.config.num_labels

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

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







import os
from pathlib import Path




def      __UpperCamelCase     (  )	->  Any:



    """simple docstring"""






    from torch.utils.cpp_extension import load

    A			:	Any										=       Path(_lowerCAmelCase		).resolve().parent.parent.parent / """kernels""" / """deformable_detr"""
    A			:	int										=       [
        root / filename
        for filename in [
            """vision.cpp""",
            os.path.join("""cpu"""				,					"""ms_deform_attn_cpu.cpp"""		),
            os.path.join("""cuda"""				,					"""ms_deform_attn_cuda.cu"""		),
        ]
    ]

    load(
        """MultiScaleDeformableAttention"""				,					_lowerCAmelCase				,					with_cuda=_lowerCAmelCase				,					extra_include_paths=[str(_lowerCAmelCase		)]				,					extra_cflags=["""-DWITH_CUDA=1"""]				,					extra_cuda_cflags=[
            """-DCUDA_HAS_FP16=1""",
            """-D__CUDA_NO_HALF_OPERATORS__""",
            """-D__CUDA_NO_HALF_CONVERSIONS__""",
            """-D__CUDA_NO_HALF2_OPERATORS__""",
        ]				,					)

    import MultiScaleDeformableAttention as MSDA

    return MSDA


