



"""simple docstring"""
import json
import logging
import os
import sys
from pathlib import Path

import finetune_rag

from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    require_ray,
    require_torch_gpu,
    require_torch_multi_gpu,
)


logging.basicConfig(level=logging.DEBUG)
A:     Optional[Any]										=	logging.getLogger()

A:     Optional[int]										=	logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__				):

			def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE		)						->   Dict:





				'''simple docstring'''




				os.makedirs(_SCREAMING_SNAKE_CASE   ,  exist_ok=_SCREAMING_SNAKE_CASE		)
				UpperCAmelCase			:      Any			=			{"""source""": """What is love ?""", """target""": """life"""}
				UpperCAmelCase			:      str			=			{"""train""": 12, """val""": 2, """test""": 2}
				for split in ["train", "test", "val"]:
					for field in ["source", "target"]:
						UpperCAmelCase			:      Union[str, Any]			=			"""\n""".join([contents[field]] * n_lines[split]		)
						with open(os.path.join(_SCREAMING_SNAKE_CASE   ,  F"{split}.{field}"		)   ,  """w"""		) as f:
							f.write(_SCREAMING_SNAKE_CASE		)

			def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE = "pytorch"		)						->   Optional[Any]:





				'''simple docstring'''




				UpperCAmelCase			:      List[Any]			=			self.get_auto_remove_tmp_dir()
				UpperCAmelCase			:      Dict			=			os.path.join(_SCREAMING_SNAKE_CASE   ,  """output"""		)
				UpperCAmelCase			:      Union[str, Any]			=			os.path.join(_SCREAMING_SNAKE_CASE   ,  """data"""		)
				self._create_dummy_data(data_dir=_SCREAMING_SNAKE_CASE		)

				UpperCAmelCase			:      Union[str, Any]			=			F"\n                --data_dir {data_dir} \\n                --output_dir {output_dir} \\n                --model_name_or_path facebook/rag-sequence-base \\n                --model_type rag_sequence \\n                --do_train \\n                --do_predict \\n                --n_val -1 \\n                --val_check_interval 1.0 \\n                --train_batch_size 2 \\n                --eval_batch_size 1 \\n                --max_source_length 25 \\n                --max_target_length 25 \\n                --val_max_target_length 25 \\n                --test_max_target_length 25 \\n                --label_smoothing 0.1 \\n                --dropout 0.1 \\n                --attention_dropout 0.1 \\n                --weight_decay 0.001 \\n                --adam_epsilon 1e-08 \\n                --max_grad_norm 0.1 \\n                --lr_scheduler polynomial \\n                --learning_rate 3e-04 \\n                --num_train_epochs 1 \\n                --warmup_steps 4 \\n                --gradient_accumulation_steps 1 \\n                --distributed-port 8787 \\n                --use_dummy_dataset 1 \\n                --distributed_retriever {distributed_retriever} \\n            ".split()

				if gpus > 0:
					testargs.append(F"--gpus={gpus}"		)
					if is_apex_available():
						testargs.append("""--fp16"""		)
				else:
					testargs.append("""--gpus=0"""		)
					testargs.append("""--distributed_backend=ddp_cpu"""		)
					testargs.append("""--num_processes=2"""		)

				UpperCAmelCase			:      Optional[int]			=			[sys.executable, str(Path(finetune_rag.__file__		).resolve()		)] + testargs
				execute_subprocess_async(_SCREAMING_SNAKE_CASE   ,  env=self.get_env()		)

				UpperCAmelCase			:      Union[str, Any]			=			os.path.join(_SCREAMING_SNAKE_CASE   ,  """metrics.json"""		)
				with open(_SCREAMING_SNAKE_CASE		) as f:
					UpperCAmelCase			:      Tuple			=			json.load(_SCREAMING_SNAKE_CASE		)
				return result

			@require_torch_gpu
			def 			SCREAMING_SNAKE_CASE  (     self		)						->   Union[str, Any]:





				'''simple docstring'''




				UpperCAmelCase			:      Optional[Any]			=			self._run_finetune(gpus=1		)
				self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,  0.2		)

			@require_torch_multi_gpu
			def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





				'''simple docstring'''




				UpperCAmelCase			:      Optional[int]			=			self._run_finetune(gpus=2		)
				self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,  0.2		)

			@require_torch_gpu
			@require_ray
			def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





				'''simple docstring'''




				UpperCAmelCase			:      Tuple			=			self._run_finetune(gpus=1   ,  distributed_retriever="""ray"""		)
				self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,  0.2		)




			@require_torch_multi_gpu
			@require_ray
			def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[int]:





				'''simple docstring'''




				UpperCAmelCase			:      Optional[int]			=			self._run_finetune(gpus=1   ,  distributed_retriever="""ray"""		)
				self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]   ,  0.2		)





"""simple docstring"""
import json
import os
from typing import Optional

import numpy as np

from ...feature_extraction_utils import BatchFeature
from ...processing_utils import ProcessorMixin
from ...utils import logging
from ...utils.hub import get_file_from_repo
from ..auto import AutoTokenizer


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



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__				):
   __lowerCAmelCase						:     Optional[int]		=		'AutoTokenizer'
   __lowerCAmelCase						:     str		=		['tokenizer']

   __lowerCAmelCase						:     Any		=		{
       'semantic_prompt': 1,
       'coarse_prompt': 2,
       'fine_prompt': 2,
   }

   def __init__(     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=None		)						->   int:





    '''simple docstring'''




    super().__init__(_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Optional[int]			=			speaker_embeddings

   @classmethod
   def 			SCREAMING_SNAKE_CASE  (     cls   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json"   ,  **_SCREAMING_SNAKE_CASE		)						->   List[Any]:





    '''simple docstring'''




    if speaker_embeddings_dict_path is not None:
     UpperCAmelCase			:      Any			=			get_file_from_repo(
         _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  subfolder=kwargs.pop("""subfolder"""   ,  _SCREAMING_SNAKE_CASE		)   ,  cache_dir=kwargs.pop("""cache_dir"""   ,  _SCREAMING_SNAKE_CASE		)   ,  force_download=kwargs.pop("""force_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  proxies=kwargs.pop("""proxies"""   ,  _SCREAMING_SNAKE_CASE		)   ,  resume_download=kwargs.pop("""resume_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  local_files_only=kwargs.pop("""local_files_only"""   ,  _SCREAMING_SNAKE_CASE		)   ,  use_auth_token=kwargs.pop("""use_auth_token"""   ,  _SCREAMING_SNAKE_CASE		)   ,  revision=kwargs.pop("""revision"""   ,  _SCREAMING_SNAKE_CASE		)   ,  )
     if speaker_embeddings_path is None:
      logger.warning(
          F"`{os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)}` does not exists\n                    , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n                    dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`."		)
      UpperCAmelCase			:      Optional[int]			=			None
     else:
      with open(_SCREAMING_SNAKE_CASE		) as speaker_embeddings_json:
       UpperCAmelCase			:      List[str]			=			json.load(_SCREAMING_SNAKE_CASE		)
    else:
     UpperCAmelCase			:      List[str]			=			None

    UpperCAmelCase			:      List[Any]			=			AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)

    return cls(tokenizer=_SCREAMING_SNAKE_CASE   ,  speaker_embeddings=_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json"   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings"   ,  _SCREAMING_SNAKE_CASE = False   ,  **_SCREAMING_SNAKE_CASE   ,  )						->   Union[str, Any]:





    '''simple docstring'''




    if self.speaker_embeddings is not None:
     os.makedirs(os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  """v2"""		)   ,  exist_ok=_SCREAMING_SNAKE_CASE		)

     UpperCAmelCase			:      str			=			{}

     UpperCAmelCase			:      Union[str, Any]			=			save_directory

     for prompt_key in self.speaker_embeddings:
      if prompt_key != "repo_or_path":
       UpperCAmelCase			:      Optional[Any]			=			self._load_voice_preset(_SCREAMING_SNAKE_CASE		)

       UpperCAmelCase			:      Any			=			{}
       for key in self.speaker_embeddings[prompt_key]:
        np.save(
            os.path.join(
                embeddings_dict["""repo_or_path"""]   ,  _SCREAMING_SNAKE_CASE   ,  F"{prompt_key}_{key}"		)   ,  voice_preset[key]   ,  allow_pickle=_SCREAMING_SNAKE_CASE   ,  )
        UpperCAmelCase			:      Optional[int]			=			os.path.join(_SCREAMING_SNAKE_CASE   ,  F"{prompt_key}_{key}.npy"		)

       UpperCAmelCase			:      Tuple			=			tmp_dict

     with open(os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)   ,  """w"""		) as fp:
      json.dump(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

    super().save_pretrained(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE = None   ,  **_SCREAMING_SNAKE_CASE		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			self.speaker_embeddings[voice_preset]

    UpperCAmelCase			:      List[Any]			=			{}
    for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
     if key not in voice_preset_paths:
      raise ValueError(
          F"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]."		)

     UpperCAmelCase			:      List[str]			=			get_file_from_repo(
         self.speaker_embeddings.get("""repo_or_path"""   ,  """/"""		)   ,  voice_preset_paths[key]   ,  subfolder=kwargs.pop("""subfolder"""   ,  _SCREAMING_SNAKE_CASE		)   ,  cache_dir=kwargs.pop("""cache_dir"""   ,  _SCREAMING_SNAKE_CASE		)   ,  force_download=kwargs.pop("""force_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  proxies=kwargs.pop("""proxies"""   ,  _SCREAMING_SNAKE_CASE		)   ,  resume_download=kwargs.pop("""resume_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  local_files_only=kwargs.pop("""local_files_only"""   ,  _SCREAMING_SNAKE_CASE		)   ,  use_auth_token=kwargs.pop("""use_auth_token"""   ,  _SCREAMING_SNAKE_CASE		)   ,  revision=kwargs.pop("""revision"""   ,  _SCREAMING_SNAKE_CASE		)   ,  )
     if path is None:
      raise ValueError(
          F"`{os.path.join(self.speaker_embeddings.get('repo_or_path'   ,  '/'		)   ,  voice_preset_paths[key]		)}` does not exists\n                    , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n                    embeddings."		)

     UpperCAmelCase			:      List[str]			=			np.load(_SCREAMING_SNAKE_CASE		)

    return voice_preset_dict

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE = None		)						->   List[str]:





    '''simple docstring'''




    for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
     if key not in voice_preset:
      raise ValueError(F"Voice preset unrecognized, missing {key} as a key."		)

     if not isinstance(voice_preset[key]   ,  np.ndarray		):
      raise ValueError(F"{key} voice preset must be a {str(self.preset_shape[key]		)}D ndarray."		)

     if len(voice_preset[key].shape		) != self.preset_shape[key]:
      raise ValueError(F"{key} voice preset must be a {str(self.preset_shape[key]		)}D ndarray."		)




   def __call__(     self   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE="pt"   ,  _SCREAMING_SNAKE_CASE=256   ,  _SCREAMING_SNAKE_CASE=False   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=False   ,  **_SCREAMING_SNAKE_CASE   ,  )						->   Optional[int]:





    '''simple docstring'''




    if voice_preset is not None and not isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     if (
         isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)
         and self.speaker_embeddings is not None
         and voice_preset in self.speaker_embeddings
     ):
      UpperCAmelCase			:      Dict			=			self._load_voice_preset(_SCREAMING_SNAKE_CASE		)

     else:
      if isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		) and not voice_preset.endswith(""".npz"""		):
       UpperCAmelCase			:      Tuple			=			voice_preset + """.npz"""

      UpperCAmelCase			:      Union[str, Any]			=			np.load(_SCREAMING_SNAKE_CASE		)

    if voice_preset is not None:
     self._validate_voice_preset_dict(_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)
     UpperCAmelCase			:      List[Any]			=			BatchFeature(data=_SCREAMING_SNAKE_CASE   ,  tensor_type=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      List[str]			=			self.tokenizer(
        _SCREAMING_SNAKE_CASE   ,  return_tensors=_SCREAMING_SNAKE_CASE   ,  padding="""max_length"""   ,  max_length=_SCREAMING_SNAKE_CASE   ,  return_attention_mask=_SCREAMING_SNAKE_CASE   ,  return_token_type_ids=_SCREAMING_SNAKE_CASE   ,  add_special_tokens=_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE   ,  )

    if voice_preset is not None:
     UpperCAmelCase			:      List[Any]			=			voice_preset

    return encoded_text
