


"""simple docstring"""




import os
import random
import sys

from . import cryptomath_module as cryptomath
from . import rabin_miller

__UpperCamelCase						=      3


def     lowercase			(SCREAMING_SNAKE_CASE_		:				int  )   ->						Dict:
						print('Generating primitive root of p'  )
						while True:
												SCREAMING_SNAKE_CASE													=					random.randrange(3 ,			SCREAMING_SNAKE_CASE_  )
												if pow(SCREAMING_SNAKE_CASE_ ,			2 ,			SCREAMING_SNAKE_CASE_  ) == 1:
																		continue
												if pow(SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_  ) == 1:
																		continue
												return g


def     lowercase			(SCREAMING_SNAKE_CASE_		:				int  )   ->						List[Any]:
						print('Generating prime p...'  )
						SCREAMING_SNAKE_CASE													=					rabin_miller.generate_large_prime(SCREAMING_SNAKE_CASE_  )  # select large prime number.
						SCREAMING_SNAKE_CASE													=					primitive_root(SCREAMING_SNAKE_CASE_  )  # one primitive root on modulo p.
						SCREAMING_SNAKE_CASE													=					random.randrange(3 ,			SCREAMING_SNAKE_CASE_  )  # private_key -> have to be greater than 2 for safety.
						SCREAMING_SNAKE_CASE													=					cryptomath.find_mod_inverse(pow(SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_ ,			SCREAMING_SNAKE_CASE_  ) ,			SCREAMING_SNAKE_CASE_  )

						SCREAMING_SNAKE_CASE													=					(key_size, e_a, e_a, p)
						SCREAMING_SNAKE_CASE													=					(key_size, d)

						return public_key, private_key


def     lowercase			(SCREAMING_SNAKE_CASE_		:				str ,			SCREAMING_SNAKE_CASE_		:				int  )   ->						List[str]:
						if os.path.exists(F'{name}_pubkey.txt'  ) or os.path.exists(F'{name}_privkey.txt'  ):
												print('\nWARNING:'  )
												print(
												    F'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
												    'Use a different name or delete these files and re-run this program.'  )
												sys.exit()

						SCREAMING_SNAKE_CASE													=					generate_key(SCREAMING_SNAKE_CASE_  )
						print(F'\nWriting public key to file {name}_pubkey.txt...'  )
						with open(F'{name}_pubkey.txt' ,			'w'  ) as fo:
												fo.write(F'{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}'  )

						print(F'Writing private key to file {name}_privkey.txt...'  )
						with open(F'{name}_privkey.txt' ,			'w'  ) as fo:
												fo.write(F'{private_key[0]},{private_key[1]}'  )


def     lowercase			()   ->						List[str]:
						print('Making key files...'  )
						make_key_files('elgamal' ,			20_48  )
						print('Key files generation successful'  )


if __name__ == "__main__":
	main()







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


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




@add_end_docstrings(lowerCAmelCase_     )
class 					snake_case__						(       lowerCAmelCase_     ):






     """simple docstring"""


     def __init__(       self  :  Optional[Any], **_snake_case  :  str					)   ->Dict:
            super().__init__(**_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  :  Union[str, Any], _snake_case  :  Union[np.ndarray, bytes, str], **_snake_case  :  Tuple					)   ->Dict:
            return super().__call__(_snake_case, **_snake_case					)






     def    lowercase_   (       self  :  Tuple, **_snake_case  :  Any					)   ->Union[str, Any]:
            snake_case__							:	str   	=	{}
            if "candidate_labels" in kwargs:
                   snake_case__							:	str   	=	kwargs['candidate_labels']
            if "hypothesis_template" in kwargs:
                   snake_case__							:	str   	=	kwargs['hypothesis_template']

            return preprocess_params, {}, {}






     def    lowercase_   (       self  :  Dict, _snake_case  :  str, _snake_case  :  Optional[int]=None, _snake_case  :  List[str]="This is a sound of {}."					)   ->int:
            if isinstance(_snake_case, _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
                          snake_case__							:	List[Any]   	=	requests.get(_snake_case					).content
                   else:
                          with open(_snake_case, 'rb'					) as f:
                                 snake_case__							:	Union[str, Any]   	=	f.read()

            if isinstance(_snake_case, _snake_case					):
                   snake_case__							:	List[Any]   	=	ffmpeg_read(_snake_case, self.feature_extractor.sampling_rate					)

            if not isinstance(_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'					)

            snake_case__							:	Tuple   	=	self.feature_extractor(
                [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors='pt'					)
            snake_case__							:	int   	=	candidate_labels
            snake_case__							:	int   	=	[hypothesis_template.format(_snake_case					) for x in candidate_labels]
            snake_case__							:	Optional[int]   	=	self.tokenizer(_snake_case, return_tensors=self.framework, padding=_snake_case					)
            snake_case__							:	List[Any]   	=	[text_inputs]
            return inputs






     def    lowercase_   (       self  :  Optional[int], _snake_case  :  Optional[Any]					)   ->int:
            snake_case__							:	Optional[int]   	=	model_inputs.pop('candidate_labels'					)
            snake_case__							:	str   	=	model_inputs.pop('text_inputs'					)
            if isinstance(text_inputs[0], _snake_case					):
                   snake_case__							:	Optional[Any]   	=	text_inputs[0]
            else:
                   # Batching case.
                   snake_case__							:	int   	=	text_inputs[0][0]

            snake_case__							:	Any   	=	self.model(**_snake_case, **_snake_case					)

            snake_case__							:	List[Any]   	=	{
                'candidate_labels': candidate_labels,
                'logits': outputs.logits_per_audio,
            }
            return model_outputs






     def    lowercase_   (       self  :  Union[str, Any], _snake_case  :  str					)   ->List[str]:
            snake_case__							:	int   	=	model_outputs.pop('candidate_labels'					)
            snake_case__							:	List[Any]   	=	model_outputs['logits'][0]

            if self.framework == "pt":
                   snake_case__							:	Tuple   	=	logits.softmax(dim=0					)
                   snake_case__							:	Union[str, Any]   	=	probs.tolist()
            else:
                   raise ValueError('`tf` framework not supported.'					)

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






