





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

@add_end_docstrings(lowerCAmelCase_     )
class 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def __init__(							self		:					List[Any]		,*lowerCamelCase__		:					str		,**lowerCamelCase__		:					Optional[int] )  ->	Tuple:




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any]		,lowerCamelCase__		:					int=None		,lowerCamelCase__		:					List[Any]=None		,lowerCamelCase__		:					int=None )  ->	Any:




           '''simple docstring'''


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

           SCREAMING_SNAKE_CASE	=		{}
           if top_k is not None:
                 SCREAMING_SNAKE_CASE	=		top_k
           return preprocess_params, {}, postprocess_params






     def __call__(							self		:					List[Any]		,lowerCamelCase__		:					Union[str, List[str]]		,**lowerCamelCase__		:					List[str] )  ->	Optional[int]:




           '''simple docstring'''


           return super().__call__(lowerCamelCase__		,**lowerCamelCase__ )






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					Optional[int]		,lowerCamelCase__		:					Optional[int]=None		,lowerCamelCase__		:					int=1 )  ->	Optional[int]:




           '''simple docstring'''


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

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

           SCREAMING_SNAKE_CASE	=		VideoReader(lowerCamelCase__ )
           videoreader.seek(0 )

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

           SCREAMING_SNAKE_CASE	=		videoreader.get_batch(lowerCamelCase__ ).asnumpy()
           SCREAMING_SNAKE_CASE	=		list(lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.image_processor(lowerCamelCase__		,return_tensors=self.framework )
           return model_inputs






     def        SCREAMING_SNAKE_CASE__						(							self		:					Any		,lowerCamelCase__		:					Dict )  ->	int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.model(**lowerCamelCase__ )
           return model_outputs






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					Any=5 )  ->	Any:




           '''simple docstring'''


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

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

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









import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

class 	UpperCamelCase__				(   lowerCAmelCase_							,   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			str				=    VQModel
     __snake_case					:			Optional[Any]				=    "sample"






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					Optional[Any]=(32, 32) )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		4
           SCREAMING_SNAKE_CASE	=		3

           SCREAMING_SNAKE_CASE	=		floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase__ )

           return {"sample": image}






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	List[str]:




           '''simple docstring'''


           return (3, 32, 32)






     @property
     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	List[str]:




           '''simple docstring'''


           return (3, 32, 32)






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		{
               """block_out_channels""": [32, 64],
               """in_channels""": 3,
               """out_channels""": 3,
               """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],
               """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],
               """latent_channels""": 3,
           }
           SCREAMING_SNAKE_CASE	=		self.dummy_input
           return init_dict, inputs_dict






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	str:




           '''simple docstring'''


           pass






     def        SCREAMING_SNAKE_CASE__						(							self		:					Union[str, Any] )  ->	List[str]:




           '''simple docstring'''


           pass






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		VQModel.from_pretrained("""fusing/vqgan-dummy"""		,output_loading_info=lowerCamelCase__ )
           self.assertIsNotNone(lowerCamelCase__ )
           self.assertEqual(len(loading_info["""missing_keys"""] )		,0 )

           model.to(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		model(**self.dummy_input )

           assert image is not None, "Make sure output is not None"






     def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		VQModel.from_pretrained("""fusing/vqgan-dummy""" )
           model.to(lowerCamelCase__ ).eval()

           torch.manual_seed(0 )
           if torch.cuda.is_available():
                 torch.cuda.manual_seed_all(0 )

           SCREAMING_SNAKE_CASE	=		torch.randn(1		,model.config.in_channels		,model.config.sample_size		,model.config.sample_size )
           SCREAMING_SNAKE_CASE	=		image.to(lowerCamelCase__ )
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE	=		model(lowerCamelCase__ ).sample

           SCREAMING_SNAKE_CASE	=		output[0, -1, -3:, -3:].flatten().cpu()
           # fmt: off
           SCREAMING_SNAKE_CASE	=		torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] )
           # fmt: on
           self.assertTrue(torch.allclose(lowerCamelCase__		,lowerCamelCase__		,atol=1e-3 ) )


