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







@add_end_docstrings(UpperCAmelCase__			)
class 				_lowercase     (				UpperCAmelCase__			):


 '''simple docstring'''






 def __init__(      self   :	Tuple      ,       *SCREAMING_SNAKE_CASE__   :	Tuple      ,       **SCREAMING_SNAKE_CASE__   :	Any							)  ->    Dict:
  super().__init__(*SCREAMING_SNAKE_CASE__      ,       **SCREAMING_SNAKE_CASE__							)
  requires_backends(self      ,       """decord"""							)
  self.check_model_type(SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	Tuple=None      ,       SCREAMING_SNAKE_CASE__   :	Any=None      ,       SCREAMING_SNAKE_CASE__   :	Tuple=None							)  ->    Optional[int]:
  __lowerCAmelCase											=						{}
  if frame_sampling_rate is not None:
   __lowerCAmelCase											=						frame_sampling_rate
  if num_frames is not None:
   __lowerCAmelCase											=						num_frames

  __lowerCAmelCase											=						{}
  if top_k is not None:
   __lowerCAmelCase											=						top_k
  return preprocess_params, {}, postprocess_params
 def __call__(      self   :	List[Any]      ,       SCREAMING_SNAKE_CASE__   :	Union[str, List[str]]      ,       **SCREAMING_SNAKE_CASE__   :	Dict							)  ->    List[Any]:
  return super().__call__(SCREAMING_SNAKE_CASE__      ,       **SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	List[str]      ,       SCREAMING_SNAKE_CASE__   :	int=None      ,       SCREAMING_SNAKE_CASE__   :	str=1							)  ->    List[str]:
  if num_frames is None:
   __lowerCAmelCase											=						self.model.config.num_frames

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

  __lowerCAmelCase											=						VideoReader(SCREAMING_SNAKE_CASE__							)
  videoreader.seek(0							)

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

  __lowerCAmelCase											=						videoreader.get_batch(SCREAMING_SNAKE_CASE__							).asnumpy()
  __lowerCAmelCase											=						list(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase											=						self.image_processor(SCREAMING_SNAKE_CASE__      ,       return_tensors=self.framework							)
  return model_inputs
 def a					(      self   :	List[str]      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]							)  ->    int:
  __lowerCAmelCase											=						self.model(**SCREAMING_SNAKE_CASE__							)
  return model_outputs





 def a					(      self   :	Any      ,       SCREAMING_SNAKE_CASE__   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	str=5							)  ->    int:
  if top_k > self.model.config.num_labels:
   __lowerCAmelCase											=						self.model.config.num_labels

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

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







'''simple docstring'''

import numpy as np
import torch
from torch.utils.data import DataLoader

from accelerate.utils.dataclasses import DistributedType







class 				_lowercase     :


 '''simple docstring'''






 def __init__(      self   :	Optional[int]      ,       SCREAMING_SNAKE_CASE__   :	List[str]=2      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=3      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=64      ,       SCREAMING_SNAKE_CASE__   :	int=None							)  ->    Optional[int]:
  __lowerCAmelCase											=						np.random.default_rng(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						length
  __lowerCAmelCase											=						rng.normal(size=(length,)							).astype(np.floataa							)
  __lowerCAmelCase											=						a * self.x + b + rng.normal(scale=0.1      ,       size=(length,)							).astype(np.floataa							)
 def __len__(      self   :	Union[str, Any]							)  ->    Optional[Any]:
  return self.length





 def __getitem__(      self   :	str      ,       SCREAMING_SNAKE_CASE__   :	Dict							)  ->    Optional[int]:
  return {"x": self.x[i], "y": self.y[i]}







class 				_lowercase     (				torch.nn.Module			):


 '''simple docstring'''






 def __init__(      self   :	List[Any]      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=0      ,       SCREAMING_SNAKE_CASE__   :	Tuple=0      ,       SCREAMING_SNAKE_CASE__   :	Tuple=False							)  ->    Any:
  super().__init__()
  __lowerCAmelCase											=						torch.nn.Parameter(torch.tensor([2, 3]							).float()							)
  __lowerCAmelCase											=						torch.nn.Parameter(torch.tensor([2, 3]							).float()							)
  __lowerCAmelCase											=						True





 def a					(      self   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	List[Any]=None							)  ->    str:
  if self.first_batch:
   print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}"""							)
   __lowerCAmelCase											=						False
  return x * self.a[0] + self.b[0]







class 				_lowercase     (				torch.nn.Module			):


 '''simple docstring'''






 def __init__(      self   :	Any      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=0      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=0      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=False							)  ->    Optional[Any]:
  super().__init__()
  __lowerCAmelCase											=						torch.nn.Parameter(torch.tensor(SCREAMING_SNAKE_CASE__							).float()							)
  __lowerCAmelCase											=						torch.nn.Parameter(torch.tensor(SCREAMING_SNAKE_CASE__							).float()							)
  __lowerCAmelCase											=						True





 def a					(      self   :	List[str]      ,       SCREAMING_SNAKE_CASE__   :	Any=None							)  ->    int:
  if self.first_batch:
   print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}"""							)
   __lowerCAmelCase											=						False
  return x * self.a + self.b







def      UpperCamelCase_						(					snake_case_       :       List[str]						,		snake_case_       :       int = 16      )					->     int:






 '''simple docstring'''

 from datasets import load_dataset
 from transformers import AutoTokenizer

 __lowerCAmelCase											=						AutoTokenizer.from_pretrained("""bert-base-cased"""      )
 __lowerCAmelCase											=						{"""train""": """tests/test_samples/MRPC/train.csv""", """validation""": """tests/test_samples/MRPC/dev.csv"""}
 __lowerCAmelCase											=						load_dataset("""csv"""						,		data_files=snake_case_      )
 __lowerCAmelCase											=						datasets["""train"""].unique("""label"""      )

 __lowerCAmelCase											=						{v: i for i, v in enumerate(snake_case_      )}

 def tokenize_function(snake_case_       :       Optional[int]      ):
  # max_length=None => use the model max length (it's actually the default)
  __lowerCAmelCase											=						tokenizer(
      examples["""sentence1"""]						,		examples["""sentence2"""]						,		truncation=snake_case_						,		max_length=snake_case_						,		padding="""max_length"""      )
  if "label" in examples:
   __lowerCAmelCase											=						[label_to_id[l] for l in examples["""label"""]]
  return outputs

 # Apply the method we just defined to all the examples in all the splits of the dataset
 __lowerCAmelCase											=						datasets.map(
     snake_case_						,		batched=snake_case_						,		remove_columns=["""sentence1""", """sentence2""", """label"""]						,		)

 def collate_fn(snake_case_       :       List[Any]      ):
  # On TPU it's best to pad everything to the same length or training will be very slow.
  if accelerator.distributed_type == DistributedType.TPU:
   return tokenizer.pad(snake_case_						,		padding="""max_length"""						,		max_length=1_28						,		return_tensors="""pt"""      )
  return tokenizer.pad(snake_case_						,		padding="""longest"""						,		return_tensors="""pt"""      )

 # Instantiate dataloaders.
 __lowerCAmelCase											=						DataLoader(tokenized_datasets["""train"""]						,		shuffle=snake_case_						,		collate_fn=snake_case_						,		batch_size=2      )
 __lowerCAmelCase											=						DataLoader(tokenized_datasets["""validation"""]						,		shuffle=snake_case_						,		collate_fn=snake_case_						,		batch_size=1      )

 return train_dataloader, eval_dataloader






