






"""simple docstring"""
from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


lowerCamelCase_							      = logging.get_logger(__name__)







@add_end_docstrings(__A	)
class      UpperCamelCase_			(__A	):





	def __init__( self   :					Optional[Any]      ,      **lowerCAmelCase_   :					List[str]		)		->     Optional[Any]:
				super().__init__(**lowerCAmelCase_		)

				if self.framework != "pt":
							raise ValueError(f"""The {self.__class__} is only available in PyTorch."""		)
				# No specific FOR_XXX available yet





	def __call__( self   :					List[str]      ,      lowerCAmelCase_   :					Union[np.ndarray, bytes, str]      ,      **lowerCAmelCase_   :					List[str]		)		->     int:
				return super().__call__(lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      **lowerCAmelCase_   :					Any		)		->     Union[str, Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   {}
				if "candidate_labels" in kwargs:
							UpperCAmelCase_	:					int     	=   kwargs["candidate_labels"]
				if "hypothesis_template" in kwargs:
							UpperCAmelCase_	:					List[str]     	=   kwargs["hypothesis_template"]

				return preprocess_params, {}, {}





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      lowerCAmelCase_   :					List[Any]      ,      lowerCAmelCase_   :					Any=None      ,      lowerCAmelCase_   :					List[str]="This is a sound of {}."		)		->     Tuple:
				if isinstance(lowerCAmelCase_      ,      lowerCAmelCase_		):
							if audio.startswith("http://"		) or audio.startswith("https://"		):
										# We need to actually check for a real protocol, otherwise it's impossible to use a local file
										# like http_huggingface_co.png
										UpperCAmelCase_	:					Any     	=   requests.get(lowerCAmelCase_		).content
							else:
										with open(lowerCAmelCase_      ,      "rb"		) as f:
													UpperCAmelCase_	:					Dict     	=   f.read()

				if isinstance(lowerCAmelCase_      ,      lowerCAmelCase_		):
							UpperCAmelCase_	:					Optional[Any]     	=   ffmpeg_read(lowerCAmelCase_      ,      self.feature_extractor.sampling_rate		)

				if not isinstance(lowerCAmelCase_      ,      np.ndarray		):
							raise ValueError("We expect a numpy ndarray as input"		)
				if len(audio.shape		) != 1:
							raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline"		)

				UpperCAmelCase_	:					Union[str, Any]     	=   self.feature_extractor(
				    [audio]      ,      sampling_rate=self.feature_extractor.sampling_rate      ,      return_tensors="pt"		)
				UpperCAmelCase_	:					Any     	=   candidate_labels
				UpperCAmelCase_	:					Union[str, Any]     	=   [hypothesis_template.format(lowerCAmelCase_		) for x in candidate_labels]
				UpperCAmelCase_	:					List[str]     	=   self.tokenizer(lowerCAmelCase_      ,      return_tensors=self.framework      ,      padding=lowerCAmelCase_		)
				UpperCAmelCase_	:					int     	=   [text_inputs]
				return inputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]      ,      lowerCAmelCase_   :					Optional[int]		)		->     Any:
				UpperCAmelCase_	:					Dict     	=   model_inputs.pop("candidate_labels"		)
				UpperCAmelCase_	:					List[str]     	=   model_inputs.pop("text_inputs"		)
				if isinstance(text_inputs[0]      ,      lowerCAmelCase_		):
							UpperCAmelCase_	:					Optional[int]     	=   text_inputs[0]
				else:
							# Batching case.
							UpperCAmelCase_	:					Optional[Any]     	=   text_inputs[0][0]

				UpperCAmelCase_	:					Any     	=   self.model(**lowerCAmelCase_      ,      **lowerCAmelCase_		)

				UpperCAmelCase_	:					str     	=   {
				    "candidate_labels": candidate_labels,
				    "logits": outputs.logits_per_audio,
				}
				return model_outputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      lowerCAmelCase_   :					Optional[Any]		)		->     Tuple:
				UpperCAmelCase_	:					int     	=   model_outputs.pop("candidate_labels"		)
				UpperCAmelCase_	:					Optional[int]     	=   model_outputs["logits"][0]

				if self.framework == "pt":
							UpperCAmelCase_	:					Tuple     	=   logits.softmax(dim=0		)
							UpperCAmelCase_	:					int     	=   probs.tolist()
				else:
							raise ValueError("`tf` framework not supported."		)

				UpperCAmelCase_	:					Union[str, Any]     	=   [
				    {"score": score, "label": candidate_label}
				    for score, candidate_label in sorted(zip(lowerCAmelCase_      ,      lowerCAmelCase_		)      ,      key=lambda lowerCAmelCase_		: -x[0]		)
				]
				return result











"""simple docstring"""
import json
import os
from typing import Dict, List, Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCamelCase_							      = logging.get_logger(__name__)


lowerCamelCase_							      = {
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

lowerCamelCase_							      = {
    '''vocab_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'''
    },
    '''merges_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'''
    },
    '''tokenizer_config_file''': {
        '''facebook/blenderbot_small-90M''': (
            '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'''
        )
    },
}

lowerCamelCase_							      = {'''facebook/blenderbot_small-90M''': 512}

def 							snake_case (  A__		):
			UpperCAmelCase_	:					str     	=   set()
			UpperCAmelCase_	:					int     	=   word[0]
			for char in word[1:]:
						pairs.add((prev_char, char)		)
						UpperCAmelCase_	:					Dict     	=   char

			UpperCAmelCase_	:					List[Any]     	=   set(A__		)
			return pairs







class      UpperCamelCase_			(__A	):
	__magic_name__       =							VOCAB_FILES_NAMES
	__magic_name__       =							PRETRAINED_VOCAB_FILES_MAP
	__magic_name__       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	__magic_name__       =							['''input_ids''', '''attention_mask''']





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					Optional[int]="__start__"      ,      lowerCAmelCase_   :					str="__end__"      ,      lowerCAmelCase_   :					Union[str, Any]="__unk__"      ,      lowerCAmelCase_   :					Union[str, Any]="__null__"      ,      **lowerCAmelCase_   :					List[Any]      ,      )		->     str:
				super().__init__(unk_token=lowerCAmelCase_      ,      bos_token=lowerCAmelCase_      ,      eos_token=lowerCAmelCase_      ,      pad_token=lowerCAmelCase_      ,      **lowerCAmelCase_		)

				with open(lowerCAmelCase_      ,      encoding="utf-8"		) as vocab_handle:
							UpperCAmelCase_	:					str     	=   json.load(lowerCAmelCase_		)
				UpperCAmelCase_	:					Union[str, Any]     	=   {v: k for k, v in self.encoder.items()}
				with open(lowerCAmelCase_      ,      encoding="utf-8"		) as merges_handle:
							UpperCAmelCase_	:					Optional[Any]     	=   merges_handle.read().split("\n"		)[1:-1]
				UpperCAmelCase_	:					str     	=   [tuple(merge.split()		) for merge in merges]
				UpperCAmelCase_	:					Any     	=   dict(zip(lowerCAmelCase_      ,      range(len(lowerCAmelCase_		)		)		)		)
				UpperCAmelCase_	:					Any     	=   {}





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					str		)		->     int:
				return len(self.encoder		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]		)		->     Dict:
				return dict(self.encoder      ,      **self.added_tokens_encoder		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]      ,      lowerCAmelCase_   :					str		)		->     str:
				if token in self.cache:
							return self.cache[token]
				UpperCAmelCase_	:					Dict     	=   re.sub("([.,!?()])"      ,      R" \1"      ,      lowerCAmelCase_		)
				UpperCAmelCase_	:					int     	=   re.sub("(')"      ,      R" \1 "      ,      lowerCAmelCase_		)
				UpperCAmelCase_	:					List[str]     	=   re.sub(R"\s{2,}"      ,      " "      ,      lowerCAmelCase_		)
				if "\n" in token:
							UpperCAmelCase_	:					Tuple     	=   token.replace("\n"      ,      " __newln__"		)

				UpperCAmelCase_	:					Tuple     	=   token.split(" "		)
				UpperCAmelCase_	:					int     	=   []
				for token in tokens:
							if not len(lowerCAmelCase_		):
										continue

							UpperCAmelCase_	:					Any     	=   token.lower()
							UpperCAmelCase_	:					List[str]     	=   tuple(lowerCAmelCase_		)
							UpperCAmelCase_	:					List[str]     	=   tuple(list(word[:-1]		) + [word[-1] + "</w>"]		)
							UpperCAmelCase_	:					List[Any]     	=   get_pairs(lowerCAmelCase_		)

							if not pairs:
										words.append(lowerCAmelCase_		)
										continue

							while True:
										UpperCAmelCase_	:					Union[str, Any]     	=   min(lowerCAmelCase_      ,      key=lambda lowerCAmelCase_		: self.bpe_ranks.get(lowerCAmelCase_      ,      float("inf"		)		)		)
										if bigram not in self.bpe_ranks:
													break
										UpperCAmelCase_	,      UpperCAmelCase_	:					Dict     	=   bigram
										UpperCAmelCase_	:					Dict     	=   []
										UpperCAmelCase_	:					Dict     	=   0

										while i < len(lowerCAmelCase_		):
													try:
																UpperCAmelCase_	:					int     	=   word.index(lowerCAmelCase_      ,      lowerCAmelCase_		)
																new_word.extend(word[i:j]		)
																UpperCAmelCase_	:					Any     	=   j
													except ValueError:
																new_word.extend(word[i:]		)
																break

													if word[i] == first and i < len(lowerCAmelCase_		) - 1 and word[i + 1] == second:
																new_word.append(first + second		)
																i += 2
													else:
																new_word.append(word[i]		)
																i += 1
										UpperCAmelCase_	:					Dict     	=   tuple(lowerCAmelCase_		)
										UpperCAmelCase_	:					Any     	=   new_word
										if len(lowerCAmelCase_		) == 1:
													break
										else:
													UpperCAmelCase_	:					Union[str, Any]     	=   get_pairs(lowerCAmelCase_		)
							UpperCAmelCase_	:					Optional[int]     	=   "@@ ".join(lowerCAmelCase_		)
							UpperCAmelCase_	:					List[str]     	=   word[:-4]

							UpperCAmelCase_	:					Optional[Any]     	=   word
							words.append(lowerCAmelCase_		)
				return " ".join(lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple      ,      lowerCAmelCase_   :					str		)		->     List[str]:
				UpperCAmelCase_	:					Union[str, Any]     	=   []

				UpperCAmelCase_	:					List[Any]     	=   re.findall(R"\S+\n?"      ,      lowerCAmelCase_		)

				for token in words:
							split_tokens.extend(list(self.bpe(lowerCAmelCase_		).split(" "		)		)		)
				return split_tokens





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict      ,      lowerCAmelCase_   :					str		)		->     int:
				UpperCAmelCase_	:					List[Any]     	=   token.lower()
				return self.encoder.get(lowerCAmelCase_      ,      self.encoder.get(self.unk_token		)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]      ,      lowerCAmelCase_   :					int		)		->     str:
				return self.decoder.get(lowerCAmelCase_      ,      self.unk_token		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple      ,      lowerCAmelCase_   :					List[str]		)		->     str:
				UpperCAmelCase_	:					List[str]     	=   " ".join(lowerCAmelCase_		).replace("@@ "      ,      ""		).strip()
				return out_string





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					str      ,      lowerCAmelCase_   :					Optional[str] = None		)		->     Tuple[str]:
				if not os.path.isdir(lowerCAmelCase_		):
							logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""		)
							return
				UpperCAmelCase_	:					Dict     	=   os.path.join(
				    lowerCAmelCase_      ,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)
				UpperCAmelCase_	:					Union[str, Any]     	=   os.path.join(
				    lowerCAmelCase_      ,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]		)

				with open(lowerCAmelCase_      ,      "w"      ,      encoding="utf-8"		) as f:
							f.write(json.dumps(self.encoder      ,      indent=2      ,      sort_keys=lowerCAmelCase_      ,      ensure_ascii=lowerCAmelCase_		) + "\n"		)

				UpperCAmelCase_	:					Any     	=   0
				with open(lowerCAmelCase_      ,      "w"      ,      encoding="utf-8"		) as writer:
							writer.write("#version: 0.2\n"		)
							for bpe_tokens, token_index in sorted(self.bpe_ranks.items()      ,      key=lambda lowerCAmelCase_		: kv[1]		):
										if index != token_index:
													logger.warning(
													    f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
													    " Please check that the tokenizer is not corrupted!"		)
													UpperCAmelCase_	:					List[Any]     	=   token_index
										writer.write(" ".join(lowerCAmelCase_		) + "\n"		)
										index += 1

				return vocab_file, merge_file



