




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

A									=logging.get_logger(__name__)


@add_end_docstrings(__a				)
class     _a						(			__a				):
       def __init__(			self		:			Any     ,       *lowercase		:			Optional[int]     ,       **lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           super().__init__(*lowercase     ,       **lowercase       )
           requires_backends(self     ,       '''decord'''       )
           self.check_model_type(lowercase       )
       def 					A   (			self		:			Optional[Any]     ,       lowercase		:			Dict=None     ,       lowercase		:			List[str]=None     ,       lowercase		:			int=None       ):



           '''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		:			Union[str, Any]     ,       lowercase		:			Union[str, List[str]]     ,       **lowercase		:			int       ):



           '''simple docstring'''

           return super().__call__(lowercase     ,       **lowercase       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			List[str]     ,       lowercase		:			str=None     ,       lowercase		:			List[Any]=1       ):



           '''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(lowercase       ).content       )

           UpperCAmelCase     =	VideoReader(lowercase       )
           videoreader.seek(0       )

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

           UpperCAmelCase     =	videoreader.get_batch(lowercase       ).asnumpy()
           UpperCAmelCase     =	list(lowercase       )

           UpperCAmelCase     =	self.image_processor(lowercase     ,       return_tensors=self.framework       )
           return model_inputs
       def 					A   (			self		:			Optional[int]     ,       lowercase		:			str       ):



           '''simple docstring'''

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







       def 					A   (			self		:			Tuple     ,       lowercase		:			Any     ,       lowercase		:			List[Any]=5       ):



           '''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(lowercase       )
           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(lowercase     ,       lowercase       )]










'''simple docstring'''







import json
import os
import unittest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class     _a						(			__a							,							unittest.TestCase				):
       __a       :  Any            =      MgpstrTokenizer
       __a       :  Optional[Any]            =      False
       __a       :  str            =      {}
       __a       :  Optional[int]            =      False
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           super().setUp()

           # fmt: off
           UpperCAmelCase     =	['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z''']
           # fmt: on
           UpperCAmelCase     =	dict(zip(lowercase     ,       range(len(lowercase       )       )       )       )

           UpperCAmelCase     =	os.path.join(self.tmpdirname     ,       VOCAB_FILES_NAMES['''vocab_file''']       )
           with open(self.vocab_file     ,       '''w'''     ,       encoding='''utf-8'''       ) as fp:
               fp.write(json.dumps(lowercase       ) + '''\n'''       )
       def 					A   (			self		:			int     ,       **lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           return MgpstrTokenizer.from_pretrained(self.tmpdirname     ,       **lowercase       )
       def 					A   (			self		:			int     ,       lowercase		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	'''tester'''
           UpperCAmelCase     =	'''tester'''
           return input_text, output_text
       @unittest.skip('''MGP-STR always lower cases letters.'''       )
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           pass
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.get_tokenizers(do_lower_case=lowercase       )
           for tokenizer in tokenizers:
               with self.subTest(f"{tokenizer.__class__.__name__}"       ):
                   UpperCAmelCase     =	'''[SPECIAL_TOKEN]'''

                   tokenizer.add_special_tokens({'''cls_token''': special_token}       )
                   UpperCAmelCase     =	tokenizer.encode([special_token]     ,       add_special_tokens=lowercase       )
                   self.assertEqual(len(lowercase       )     ,       1       )

                   UpperCAmelCase     =	tokenizer.decode(lowercase     ,       skip_special_tokens=lowercase       )
                   self.assertTrue(special_token not in decoded       )
       def 					A   (			self		:			List[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.get_tokenizers()
           for tokenizer in tokenizers:
               with self.subTest(f"{tokenizer.__class__.__name__}"       ):
                   UpperCAmelCase ,  UpperCAmelCase     =	self.get_input_output_texts(lowercase       )

                   UpperCAmelCase     =	tokenizer.tokenize(lowercase       )
                   UpperCAmelCase     =	tokenizer.convert_tokens_to_ids(lowercase       )
                   UpperCAmelCase     =	tokenizer.encode(lowercase     ,       add_special_tokens=lowercase       )
                   self.assertListEqual(lowercase     ,       lowercase       )

                   UpperCAmelCase     =	tokenizer.convert_ids_to_tokens(lowercase       )
                   self.assertNotEqual(len(lowercase       )     ,       0       )
                   UpperCAmelCase     =	tokenizer.decode(lowercase       )
                   self.assertIsInstance(lowercase     ,       lowercase       )

                   self.assertEqual(text_a.replace(''' '''     ,       ''''''       )     ,       lowercase       )
       @unittest.skip('''MGP-STR tokenizer only handles one sequence.'''       )
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           pass







       @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer'''       )
       def 					A   (			self		:			str       ):



           '''simple docstring'''

           pass




