


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

_lowercase    :    int			     =  logging.get_logger(__name__)






@add_end_docstrings(_a )
class  lowerCamelCase_(     _a ):




				def __init__(	self    :				str   ,					*lowerCAmelCase    :				List[Any]   ,					**lowerCAmelCase    :				Any   )->  List[str]:

										"""simple docstring"""




										super().__init__(*_A   ,					**_A   )
										requires_backends(self   ,					'''decord'''   )
										self.check_model_type(_A   )




				def   a__(	self    :				int   ,					lowerCAmelCase    :				int=None   ,					lowerCAmelCase    :				List[Any]=None   ,					lowerCAmelCase    :				Optional[int]=None   )->  Dict:

										"""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    :				Optional[Any]   ,					lowerCAmelCase    :				List[Any]   ,					**lowerCAmelCase    :				Any   )->  Union[str, Any]:

										"""simple docstring"""




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




				def   a__(	self    :				Any   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				str=None   ,					lowerCAmelCase    :				Dict=1   )->  Any:

										"""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   a__(	self    :				Tuple   ,					lowerCAmelCase    :				Optional[int]   )->  Tuple:

										"""simple docstring"""




										UpperCAmelCase         =			self.model(**_A   )
										return model_outputs





				def   a__(	self    :				Optional[int]   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Optional[Any]=5   )->  Tuple:

										"""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   )]









'''simple docstring'''



# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


_lowercase    :    Any			     =  {
    """configuration_cpmant""": ["""CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CpmAntConfig"""],
    """tokenization_cpmant""": ["""CpmAntTokenizer"""],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	_lowercase    :    int			     =  [
	    """CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """CpmAntForCausalLM""",
	    """CpmAntModel""",
	    """CpmAntPreTrainedModel""",
	]


if TYPE_CHECKING:
	from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig
	from .tokenization_cpmant import CpmAntTokenizer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_cpmant import (
		    CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    CpmAntForCausalLM,
		    CpmAntModel,
		    CpmAntPreTrainedModel,
		)


else:
	import sys

	_lowercase    :    Dict			     =  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





