





"""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(__UpperCAmelCase       )
class 				_lowerCamelCase					(				__UpperCAmelCase       ):


						def __init__(self      ,							**__a						)       ->      Any:
								super().__init__(**__SCREAMING_SNAKE_CASE						)

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


						def __call__(self      ,							__a      ,							**__a						)       ->      Optional[Any]:
								return super().__call__(__SCREAMING_SNAKE_CASE      ,							**__SCREAMING_SNAKE_CASE						)


						def 			snake_case_      (self      ,							**__a						)       ->      Tuple:
								UpperCamelCase      =		{}
								if "candidate_labels" in kwargs:
										UpperCamelCase      =		kwargs["candidate_labels"]
								if "hypothesis_template" in kwargs:
										UpperCamelCase      =		kwargs["hypothesis_template"]

								return preprocess_params, {}, {}


						def 			snake_case_      (self      ,							__a      ,							__a=None      ,							__a="This is a sound of {}."						)       ->      Optional[Any]:

								if isinstance(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE						):
										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      =		requests.get(__SCREAMING_SNAKE_CASE						).content
										else:
												with open(__SCREAMING_SNAKE_CASE      ,							"rb"						) as f:
														UpperCamelCase      =		f.read()

								if isinstance(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE						):
										UpperCamelCase      =		ffmpeg_read(__SCREAMING_SNAKE_CASE      ,							self.feature_extractor.sampling_rate						)

								if not isinstance(__SCREAMING_SNAKE_CASE      ,							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      =		self.feature_extractor(
								    [audio]      ,							sampling_rate=self.feature_extractor.sampling_rate      ,							return_tensors="pt"						)
								UpperCamelCase      =		candidate_labels
								UpperCamelCase      =		[hypothesis_template.format(__SCREAMING_SNAKE_CASE						) for x in candidate_labels]
								UpperCamelCase      =		self.tokenizer(__SCREAMING_SNAKE_CASE      ,							return_tensors=self.framework      ,							padding=__SCREAMING_SNAKE_CASE						)
								UpperCamelCase      =		[text_inputs]
								return inputs


						def 			snake_case_      (self      ,							__a						)       ->      Optional[int]:
								UpperCamelCase      =		model_inputs.pop("candidate_labels"						)
								UpperCamelCase      =		model_inputs.pop("text_inputs"						)
								if isinstance(text_inputs[0]      ,							__SCREAMING_SNAKE_CASE						):
										UpperCamelCase      =		text_inputs[0]
								else:
										# Batching case.
										UpperCamelCase      =		text_inputs[0][0]

								UpperCamelCase      =		self.model(**__SCREAMING_SNAKE_CASE      ,							**__SCREAMING_SNAKE_CASE						)

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




						def 			snake_case_      (self      ,							__a						)       ->      Tuple:
								UpperCamelCase      =		model_outputs.pop("candidate_labels"						)
								UpperCamelCase      =		model_outputs["logits"][0]

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

								UpperCamelCase      =		[
								    {"score": score, "label": candidate_label}
								    for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE						)      ,							key=lambda __a						: -x[0]						)
								]
								return result











import argparse

import torch

from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert
from transformers.utils import logging


logging.set_verbosity_info()





def      __snake_case	(			_UpperCAmelCase   , _UpperCAmelCase   , _UpperCAmelCase				):
    # Initialise PyTorch model
    __a						       =				LxmertConfig.from_json_file(_UpperCAmelCase				)
    print(f'Building PyTorch model from configuration: {config}'				)
    __a						       =				LxmertForPreTraining(_UpperCAmelCase				)

    # Load weights from tf checkpoint
    load_tf_weights_in_lxmert(_UpperCAmelCase   , _UpperCAmelCase   , _UpperCAmelCase				)

    # Save pytorch-model
    print(f'Save PyTorch model to {pytorch_dump_path}'				)
    torch.save(model.state_dict()   , _UpperCAmelCase				)


if __name__ == "__main__":
 __snake_case						:List[Any]      		=     argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
 )
 parser.add_argument(
     '''--config_file''',
     default=None,
     type=str,
     required=True,
     help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''',
 )
 parser.add_argument(
     '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
 )
 __snake_case						:Optional[Any]      		=     parser.parse_args()
 convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)





