


from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
     from ..tf_utils import stable_softmax

snake_case    :   List[Any]	    =					logging.get_logger(__name__)







@add_end_docstrings(SCREAMING_SNAKE_CASE__							)
class 		_snake_case  (				SCREAMING_SNAKE_CASE__							):




 def __init__(		self ,  **_lowerCamelCase   ):
       super().__init__(**A__   )

       requires_backends(self ,  '''vision'''   )
       self.check_model_type(
           TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
           if self.framework == '''tf'''
           else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING   )




 def __call__(		self ,  _lowerCamelCase ,  **_lowerCamelCase   ):
       return super().__call__(A__ ,  **A__   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  **_lowerCamelCase   ):
       a						:str										=	{}
       if "candidate_labels" in kwargs:
             a						:Tuple										=	kwargs['''candidate_labels''']
       if "hypothesis_template" in kwargs:
             a						:int										=	kwargs['''hypothesis_template''']

       return preprocess_params, {}, {}




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase=None ,  _lowerCamelCase="This is a photo of {}."   ):
       a						:List[str]										=	load_image(A__   )
       a						:List[str]										=	self.image_processor(images=[image] ,  return_tensors=self.framework   )
       a						:int										=	candidate_labels
       a						:Tuple										=	[hypothesis_template.format(A__   ) for x in candidate_labels]
       a						:Dict										=	self.tokenizer(A__ ,  return_tensors=self.framework ,  padding=A__   )
       a						:Dict										=	[text_inputs]
       return inputs




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       a						:int										=	model_inputs.pop('''candidate_labels'''   )
       a						:List[Any]										=	model_inputs.pop('''text_inputs'''   )
       if isinstance(text_inputs[0] ,  A__   ):
             a						:Dict										=	text_inputs[0]
       else:
             # Batching case.
             a						:Union[str, Any]										=	text_inputs[0][0]

       a						:List[Any]										=	self.model(**A__ ,  **A__   )

       a						:Dict										=	{
           '''candidate_labels''': candidate_labels,
           '''logits''': outputs.logits_per_image,
       }
       return model_outputs




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       a						:List[str]										=	model_outputs.pop('''candidate_labels'''   )
       a						:Tuple										=	model_outputs['''logits'''][0]
       if self.framework == "pt":
             a						:Tuple										=	logits.softmax(dim=-1   ).squeeze(-1   )
             a						:Dict										=	probs.tolist()
             if not isinstance(A__ ,  A__   ):
                   a						:Optional[Any]										=	[scores]
       elif self.framework == "tf":
             a						:Any										=	stable_softmax(A__ ,  axis=-1   )
             a						:Any										=	probs.numpy().tolist()
       else:
             raise ValueError(F'''Unsupported framework: {self.framework}'''   )

       a						:Any										=	[
           {'''score''': score, '''label''': candidate_label}
           for score, candidate_label in sorted(zip(A__ ,  A__   ) ,  key=lambda _lowerCamelCase   : -x[0]   )
       ]
       return result









# 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.
import torch

from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool


if is_datasets_available():
     from datasets import load_dataset







class 		_snake_case  (				_snake_case							):
 SCREAMING_SNAKE_CASE__				=	'microsoft/speecht5_tts'
 SCREAMING_SNAKE_CASE__				=	(
     'This is a tool that reads an English text out loud. It takes an input named `text` which should contain the '
     'text to read (in English) and returns a waveform object containing the sound.'
 )
 SCREAMING_SNAKE_CASE__				=	'text_reader'
 SCREAMING_SNAKE_CASE__				=	SpeechTaProcessor
 SCREAMING_SNAKE_CASE__				=	SpeechTaForTextToSpeech
 SCREAMING_SNAKE_CASE__				=	SpeechTaHifiGan

 SCREAMING_SNAKE_CASE__				=	['text']
 SCREAMING_SNAKE_CASE__				=	['audio']




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       if self.post_processor is None:
             a						:List[Any]										=	'''microsoft/speecht5_hifigan'''
       super().setup()




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase=None   ):
       a						:Tuple										=	self.pre_processor(text=_lowerCamelCase ,  return_tensors='''pt''' ,  truncation=_lowerCamelCase   )

       if speaker_embeddings is None:
             if not is_datasets_available():
                   raise ImportError('''Datasets needs to be installed if not passing speaker embeddings.'''   )

             a						:List[Any]										=	load_dataset('''Matthijs/cmu-arctic-xvectors''' ,  split='''validation'''   )
             a						:int										=	torch.tensor(embeddings_dataset[7305]['''xvector''']   ).unsqueeze(0   )

       return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       with torch.no_grad():
             return self.model.generate_speech(**_lowerCamelCase   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       with torch.no_grad():
             return self.post_processor(_lowerCamelCase   ).cpu().detach()





