





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







@add_end_docstrings(UpperCamelCase__)
class 				__lowerCAmelCase       (    UpperCamelCase__):







      def __init__(    self		,      *lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						Union[str, Any]:



        '''simple docstring'''




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







      def    _lowercase  (    self		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None							)   ->						Union[str, Any]:



        '''simple docstring'''




        a__	:					int										={}
        if frame_sampling_rate is not None:
          a__	:					Dict										=frame_sampling_rate
        if num_frames is not None:
          a__	:					List[str]										=num_frames

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







      def __call__(    self		,      lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						List[Any]:



        '''simple docstring'''




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







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__=None		,      lowerCAmelCase__=1							)   ->						Any:



        '''simple docstring'''




        if num_frames is None:
          a__	:					Any										=self.model.config.num_frames

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

        a__	:					str										=VideoReader(lowerCAmelCase__							)
        videoreader.seek(0							)

        a__	:					Optional[Any]										=0
        a__	:					str										=num_frames * frame_sampling_rate - 1
        a__	:					Union[str, Any]										=np.linspace(lowerCAmelCase__		,      lowerCAmelCase__		,      num=lowerCAmelCase__		,      dtype=np.intaa							)

        a__	:					List[Any]										=videoreader.get_batch(lowerCAmelCase__							).asnumpy()
        a__	:					Tuple										=list(lowerCAmelCase__							)

        a__	:					Dict										=self.image_processor(lowerCAmelCase__		,      return_tensors=self.framework							)
        return model_inputs







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Any:



        '''simple docstring'''




        a__	:					Tuple										=self.model(**lowerCAmelCase__							)
        return model_outputs







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__=5							)   ->						List[Any]:



        '''simple docstring'''




        if top_k > self.model.config.num_labels:
          a__	:					Dict										=self.model.config.num_labels

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

        a__	:					Optional[int]										=scores.tolist()
        a__	:					Dict										=ids.tolist()
        return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCAmelCase__		,      lowerCAmelCase__							)]













# Copyright 2023 The HuggingFace Inc. 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool







class 				__lowerCAmelCase       (    UpperCamelCase__):
      _lowercase				:					Optional[Any]						=			"""philschmid/bart-large-cnn-samsum"""
      _lowercase				:					List[Any]						=			(
          """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """
          """and returns a summary of the text."""
      )
      _lowercase				:					Any						=			"""summarizer"""
      _lowercase				:					Any						=			AutoTokenizer
      _lowercase				:					str						=			AutoModelForSeqaSeqLM

      _lowercase				:					Optional[int]						=			["""text"""]
      _lowercase				:					Optional[int]						=			["""text"""]







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Tuple:



        '''simple docstring'''




        return self.pre_processor(lowerCAmelCase__		,      return_tensors="pt"		,      truncation=lowerCAmelCase__							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Union[str, Any]:



        '''simple docstring'''




        return self.model.generate(**lowerCAmelCase__							)[0]







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Any:



        '''simple docstring'''




        return self.pre_processor.decode(lowerCAmelCase__		,      skip_special_tokens=lowerCAmelCase__		,      clean_up_tokenization_spaces=lowerCAmelCase__							)






